0

I want to write a simple test for one of my @RestController and assert that the input @RequestBody has been properly mapped to the PersonDTO:

@RestController
public class PersonServlet {
    @PostMapping("/person") 
    public PersonRsp find(@RequestBody PersonDTO dto) {
        //business logic
    }
}

public class PersonDTO {
    private String firstname, lastname;
}

Question: how can I send a JSON request body to that servlet. And more over inspect the PersonDTO fields that all of them have been correctly set?

It's probably similar to this, but I don't know how to inspect/spy the parsed DTO?

@RunWith(SpringRunner.class)
@WebMvcTest(PersonSerlvet.class)
public class PersonTests {
    @Autowired
    private MockMvc mvc;

    @Test
    public void testExample() throws Exception {
        this.mvc.perform(get("/person"))
                .andExpect(status().isOk());
    }
}

@Duplicate marker: this is not a duplicate of the linked question (which is about how to read the response body string). I'm actually asking for request body testing.

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • I don't think validating logger output is a good unit test assertion! – membersound Nov 08 '17 at 15:41
  • In fack you are not asking for a Unit test, you want to do an integration test, If you want to test the input in a test and don't modify It for production, you can use a mock appender or an method interceptor. – David Pérez Cabrera Nov 08 '17 at 15:45
  • No, I'm asking to test the single method, and just the parsing of the request (input) to the DTO (@RequestBody) that is constructed by spring based on the input. – membersound Nov 08 '17 at 15:47
  • Why do you call a controller PersonServlet? It contradicts @RestController annotation. Here is a good example HelloControllerIT explaining how to test a Spring Boot controller. https://spring.io/guides/gs/spring-boot/ . In order to test the input argument you can use a Test Spy http://xunitpatterns.com/Test%20Spy.html – Boris Nov 08 '17 at 16:03

1 Answers1

2

Testing the deserialising of Json to a DTO is not really the responsibility of your Controller, you would be be testing the the underlying object mapper, which is an external library (Jackson, Gson ..??)

Not sure which library is being used but if you want to test your usage of it you would need to manually construct the appropriate object mapper in the similar manner as your application framework and use its api to serialise from the Json String to the Target DTO

tom01
  • 125
  • 3
  • 11
  • Ok I see, but I'd prefer testing the object mapper that is created within the spring context, and not an object mapper that is different (ie created myself during the test only). – membersound Nov 08 '17 at 15:47
  • Yeah that is understandable, are you able to autowire it directly in the context of the test @Autowired private ObjectMapper objectMapper; ? – tom01 Nov 08 '17 at 16:56