Unit Test Spring MVC Rest Service: MockMVC, JUnit, Mockito

You may also like...

  • Mahi

    Nice article. The code is working as expected as well. But the only issue I found is “UserControllerIntegrationTest” class is throwing exceptions. Is there any additional configuration needed to run the integration tests?

    org.springframework.web.client.HttpClientErrorException: 404 Not Found

    test_update_user_success(com.memorynotfound.test.UserControllerIntegrationTest) Time elapsed: 0.138 sec <<< ERROR!
    org.springframework.web.client.HttpClientErrorException: 403 Forbidden

  • Vincent Cheng

    A nice tutorial, but I have a question, in my User class, I have a dateOfBirth field with reference type is LocalDate(from joda-time), what is the correct syntax for testing that field? I try “.andExpect(jsonPath(“$[0].dateOfBirth”, is(new LocalDate(1990, 12, 1))))”, but I am getting “Expected: is
    but: was ”

    Thank you for your help

    • Vincent Cheng

      OK, I found the solutions, I need to write the custom JsonSerializer class to Serialize the date I want

  • Yura

    Hi,
    Thank you for the post and information.
    Have an issue.
    Trying to run unit tests with your reccomendations, but getting such error.

    java.lang.AssertionError: JSON path “$”
    Expected: a collection with size
    but: collection size was
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
    at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:86)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.softserve.edu.Resources.controller.LookUpControllerTest.testLoadResourceTypes(LookUpControllerTest.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

    This is my TestClass
    public class LookUpControllerTest {

    @InjectMocks
    LookUpController lookUpController;

    @Mock
    ResourceTypeService resourceTypeService;

    MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(lookUpController).build();
    }

    @Test
    public void testLoadResourceTypes() throws Exception{
    List resourceTypes = new ArrayList();
    ResourceType resType1 = new ResourceType();
    resType1.setId(1L);
    resType1.setTypeName(“Cars”);
    resType1.setTableName(“cars”);
    ResourceType resType2 = new ResourceType();
    resType1.setId(2L);
    resType1.setTypeName(“Building”);
    resType1.setTableName(“building”);

    when(resourceTypeService.getInstances()).thenReturn(resourceTypes);
    mockMvc.perform(get(“/lookUp/resourceTypes”))
    .andExpect(status().isOk())
    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
    .andExpect(jsonPath(“$”, hasSize(2)))
    .andExpect(jsonPath(“$[0].id”, is(1L)))
    .andExpect(jsonPath(“$[0].typeName”, is(“Cars”)))
    .andExpect(jsonPath(“$[0].tableName”, is(“cars”)))
    .andExpect(jsonPath(“$[1].id”, is(2L)))
    .andExpect(jsonPath(“$[1].typeName”, is(“Building”)))
    .andExpect(jsonPath(“$[1].tableName”, is(“building”)));

    verify(resourceTypeService, times(1)).getInstances();
    verifyNoMoreInteractions(resourceTypeService);
    }

    What could be wrong?

    • Dear Yura,

      You’ve created a resourceTypes list but have not inserted any objects into that list.
      After you create the ResourceType instances, you have to insert them into the list you created.

      Kr,
      Memorynotfound

      • Yura

        yeah, thanks, i find and recover this stupid mistake yesterday).
        but there is another error:

        Java.lang.AssertionError: JSON path “$[0].id”
        Expected: is 1
        but: was 2
        Such kind of mistake accures with this kind of controller method:
        @RequestMapping(value = “/lookUp/resourceTypes”, method = RequestMethod.GET)
        public List loadResourceTypes(){

        return resourceTypeService.getInstances());

        }

        BUT when i`m testing it with some DTO utill class and using static method:
        @RequestMapping(value = “/lookUp/resourceTypes”, method = RequestMethod.GET)
        public List loadResourceTypes(){

        return DtoUtilMapper.resTypesToResTypesDTO(resourceTypeService.getInstances());

        }
        public class DtoUtilMapper {

        public static List resTypesToResTypesDTO (List resTypes){

        List resTypeDTOs = new ArrayList();

        for (ResourceType resType : resTypes) {
        resTypeDTOs.add(new ResourceTypeDTO(resType.getId(), resType.getTableName(), resType.getTypeName()));
        }

        return resTypeDTOs;
        }

        IT Throws these kind of errors first rows:
        org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
        at com.softserve.edu.Resources.controller.LookUpControllerTest.testLoadResourceTypes(LookUpControllerTest.java:55)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
        Caused by: java.lang.NullPointerException
        at com.softserve.edu.Resources.dto.ResourceTypeDTO.(ResourceTypeDTO.java:27)
        at com.softserve.edu.Resources.dto.DtoUtilMapper.resTypesToResTypesDTO(DtoUtilMapper.java:15)
        at com.softserve.edu.Resources.controller.LookUpController.loadResourceTypes(LookUpController.

        Could it be because of static method isn’t mocked?
        i`m intrested more for second method testing, what can you suggest?
        also, it is interesting why in the first controller method example, it changed the order of objects, and Against 1, was 2 id number?

        • Dear Yura,

          What’s the difference between the first and second approach?
          In the fist approach, you are directly returning the result,
          But in the second approach you are mapping/copying the list with no other functionality?

          Anyway, I cannot see your entire source-code. But from your stack-trace I can see it fails somewhere in the ‘ResourceTypeDTO’ on line 27. Do you have some kind of initialization going on in your constructor? I gan definitely see a NullPointerException occurring there..

          Kr,
          Memorynotfound

  • Laurent

    Hi,
    Thank you for this tutorial.
    Is it possible to use “spring-test” with JAX-WS Webservice ?

  • Mukul Varshney

    Is it possible to add Headers in the request??

    • Yes you can add headers using get(“/users).header(“X-Header”, “value”)