0

I want to test the response of my request.

I have a controller like this,

    @RequestMapping("/user")    
    public class StandardController(@RequestBody Object body) {
            @PostMapping(path=/info")
            public ResponseEntity<String> getUserInfo(@Validated @RequestBody CustomDTO customDTO) throws customException {
              try {
                //process something with customDTO
              } catch (Exception e) {
                //throw exception
              }
        }
    }

Now I have made one of the properties of CustomDTO as @NotNull. When I test the endpoint through Postman I will successfully get 400 as expected if I supply the required field as null value. But how do I test this scenario with Mockito?

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152

2 Answers2

0

If you want to test Spring MVC controllers, don't use unit tests; you need to ensure that everything works correctly including mappings, validation, and serialization. Use MockMvc (in regular, not standalone mode), and if you like you can use Mockito to mock service dependencies.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

If you want to test your controller, you have two categories of test:

  1. Unit test by using spring test slice.

  2. Integration test

Read this post also for more understanding.

Harry Coder
  • 2,429
  • 2
  • 28
  • 32
  • I see in guide that it's extending `SpringExtension.class`. Is it possible to do with `MockitoExtension.class`? since that's what I am using for unit testing for rest of the stuff. –  Mar 25 '22 at 12:59
  • @paul23 yes you can use `Mockito` but as said before, it is better to use `test slice`. `SpringExtension` is the extension for `jupiter`. https://rieckpil.de/what-the-heck-is-the-springextension-used-for/ – Harry Coder Mar 26 '22 at 05:07