Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC mocking

I am trying to use Spring MVC mock module to unit test my controllers. I have added this:

    @Before
    public void beforeTest() {
        MockitoAnnotations.initMocks(this);
        standaloneSetup(new CarController());
    }

which works fine. However I have created a controller advice that have a method annotated with @ExceptionHandler. I want to test that it works during unit testing. I saw that I can build a MockMvc object and pass that to standaloneSetup(..):

MockMvcBuilders.standaloneSetup(
    new CarController()).setHandlerExceptionResolvers(...).build();

However when I do this the test that checks that the exception handler works passes but all the other tests that access the response with jsonpath fails with this error:

java.lang.IllegalStateException: Expected response body to be verified as JSON,
    HTML or XML but content-type 'null' is not supported out of the box.
Try registering a custom parser using:
   RestAssured.registerParser("null", <parser type>);
Content was:

How do I fix this? What is wrong?

Bottom line is that I want to unit test my rest api. How should I do this when I have added a exception handler for instance?

like image 288
LuckyLuke Avatar asked Dec 05 '25 04:12

LuckyLuke


1 Answers

Bottom line is that I want to unit test my rest api. How should I do this when I have added a exception handler for instance?

For one I would use the built in spring mock framework, available from version 3.2, and not rest assured (it might be good, but can;t imagine it is integrated as well). This might cover the basics of getting started.

Secondly, you can just try and catch in your test method, then assert on a boolean as to whether a exception was thrown. Or test for whether an exception message was returned from controller doing an expect on status code 500, for example. This will depend on your api.

like image 64
NimChimpsky Avatar answered Dec 07 '25 18:12

NimChimpsky