I am writing tests for some async methods where I want to mock that an exception is thrown. These methods were synchronous and the tests we working fine until now that I made them async and for some reasy the mocked exception isn't being thrown.
My test:
@MockBean
private RestTemplate rest
@Autowired
private ServiceImpl mockedService;
@Test(expected = MyException.class)
public void test1() {
when(rest.exchange(Mockito.anyString(),
Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class),
Mockito.eq(ParameterizedTypeReference.class)))
.thenThrow(new MyException());
this.mockedService.method();
}
The method I am trying to test:
@Autowired
private RestTemplate rest;
@Override
@Async
public void method() {
...
try {
rest.exchange(builder.toUriString(), HttpMethod.GET, entity, new ParameterizedTypeReference<MyObject>() {});
responseEntity.getBody();
} catch (HttpClientErrorException | HttpServerErrorException e) {
log.error("Hello");
throw (e);
}
}
I am getting a NullPointerException
because responseEntity.getBody();
is being called when it shouldn't because the line above should cause an exception.
What's wrong? Thank you!