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:
JavaScript
x
@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:
JavaScript
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.
JavaScript
@Mock
private RestTemplate restTemplate;
- Then you need to inject this to your
mockMvc
. E.g.
JavaScript
@Inject
private Mvc mockMvc;
In case of you’re not writing test using the annotation style like this. You can do:
JavaScript
@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.