0

I am getting a null pointer when unit testing a controller. The null pointer is occurring in the controller when calling a mocked service to get an id. I tried many things but I am still getting the same error.

Below is a snippet from the controller code where the null pointer is occurring:

@RestController
@RequestMapping(ELEMENTS_BASE_URI)
@EnableCommonRestHeaders
public class ElementController {
    @Autowired
    private ElementService elementService;
...
public ResponseEntity<ElementDto> createElement(
            @Valid @RequestBody ElementDto elementDto) {

        ElementDto saved = elementService.createElement(elementDto);

        HttpHeaders headers = new HttpHeaders();

        URI location = UriBuilder.builder(ELEMENT_LINK_URI)
                .pathVariable(ELEMENT_ID, saved.getId())
                .create();
        headers.setLocation(location);

        return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
    }
...

}

In the controller code above, The null pointer occurs at the line below: saved is null

   ElementDto saved = elementService.createElement(elementDto);

The test code is as below:

import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonObject;
import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonPath;

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = ElementController.class, excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
@ActiveProfiles(value = {"test", "hsql", "disable-oauth2"})
@TestPropertySource("classpath:/test.properties")
public class ElementControllerTest {


    @MockBean
    private ElementService elementService;

    @Autowired
    ElementController elementController;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper mapper;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders
                .standaloneSetup(elementController)
                .build();
    }

    @Test
    public void testCreateElementSuccess() throws Exception {
        ElementDto element = new ElementDto();
        element.setName("firstname");
        element.setModifiedTimeStamp(new Date());

        ElementDto createdElement = new ElementDto();
        String elementId = "123";
        createdElement.setId(elementId);
        createdElement.setName("firstname");
        createdElement.setLabel("firstname");
        createdElement.setAttribute(true);
        createdElement.setKeep(true);


        when(elementService.create(element)).thenReturn(createdElement);

        // make sure returns location with new element id
        mockMvc.perform(
                post(ServiceConstants.ELEMENTS_BASE_URI)
                     .content(mapper.writeValueAsBytes(element))
                     .accept(ElementDto.MEDIA_TYPE_JSON_VALUE)
                     .contentType(ElementDto.MEDIA_TYPE_JSON_VALUE))
                     .andExpect(status().isCreated())
                     .andExpect(header().string("Location",
                        Matchers.endsWith(ServiceConstants.SERVICE_URI + ServiceConstants.ELEMENTS_BASE_URI + "/" + elementId)))
                     .andExpect(header().string("Last-Modified", not(isEmptyString())))
                     .andExpect(jsonObject().is(createdElement))
                     .andExpect(jsonPath("name").value(element.getName()))
                     .andReturn();
    }
}

The line:

when(elementService.create(element)).thenReturn(createdElement);

does not seem to have any effect. Any help on this is really appreciated.

Regards, Firas

5
  • Because ElementDto in your test and ElementDto in the controller will not be the same instance. I suspect you want to use: when(elementService.create(Mockito.any())).thenReturn(createdElement); Commented Feb 19, 2020 at 16:14
  • @AlanHay, I replaced it with this line: when(elementService.create(Mockito.any())).thenReturn(createdElement); I am still getting same error. Thanks. Commented Feb 19, 2020 at 16:18
  • I also tried the following, but still same issue: when(elementService.create(Mockito.any(ElementDto.class))).thenReturn(createdElement); Commented Feb 19, 2020 at 16:29
  • What is it that is actually null, the service or the created item? Your mocking annotations look wrong. See here for examples: stackoverflow.com/questions/16170572/… Commented Feb 19, 2020 at 16:43
  • @AlanHay as I mentioned in the question, the null is happening at this line: ElementDto saved = elementService.createElement(elementDto); saved is null. Not sure what you mean my mocking notations are wrong. They are standard testing annotations. Commented Feb 19, 2020 at 17:27

1 Answer 1

0

The cause for this issue, was a mistake I made. The function is createElement and the when/any was referencing create function.

I changed:

when(elementService.create(eq(element))).thenReturn(createdElement);

to:

when(elementService.createElement(eq(element))).thenReturn(createdElement);

The rest of the code and notations are correct.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.