Skip to content
Advertisement

NullPointerException Mock when use RestTemplate

I am new to using mockito and I have a problem. I wrote a controller test and it uses restTemplate to get data from another api, but when I run the test, the variable of this type is null. In result NullPointerException.

What could be the problem?

Controlle:

 @GetMapping(value = "api/cstat", produces = "application/json")
    public ResponseEntity<List<String>> cstat() {
               ResponseEntity<DTO> response =                  // <=====NPE
                            restTemplate.exchange(uri, HttpMethod.GET, entity, DTO.class);    

                    if (response.getBody() != null).     //<==== AND HERE NPE(on future))
                    {
                       ...
                    } else {
                        ...
                    }
}

Test:

   
            Dto expected = new Dto();

            String actual = mockMvc.perform(MockMvcRequestBuilders
                                .get("/api/cstat").with(roleLmsRead()))
                        .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

Advertisement

Answer

This is because you don’t have restTemplate, so restTemplate is null.

To initialise this, in the test:

  • You need to declare restTemplate. E.g.
@Mock
private RestTemplate restTemplate;
  • Then you need to inject this to your mockMvc. E.g.
@Inject
private Mvc mockMvc;

In case of you’re not writing test using the annotation style like this. You can do:

@Before
public void setUp() {
    restTemplate = Mockito.mock(RestTemplate.class);
    mockMvc = new MockMvc(restTemplate);
}

P/S: If mockMvc is the one you’re gonna test, so don’t name it as prefix mock, it’s confused.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement