Java Spring启动-在@Async函数中忽略Mockito
我正在为一些异步方法编写测试,其中我想模拟抛出异常。这些方法是同步的,我们的测试工作得很好,直到现在,我使它们异步,并且实际上没有抛出模拟异常 我的测试:Java Spring启动-在@Async函数中忽略Mockito,java,spring-boot,junit,mockito,springmockito,Java,Spring Boot,Junit,Mockito,Springmockito,我正在为一些异步方法编写测试,其中我想模拟抛出异常。这些方法是同步的,我们的测试工作得很好,直到现在,我使它们异步,并且实际上没有抛出模拟异常 我的测试: @MockBean private RestTemplate rest @Autowired private ServiceImpl mockedService; @Test(expected = MyException.class) public void test1() { when(rest.exchange(Mockito
@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();
}
我尝试测试的方法:
@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);
}
@Autowired
私人休息;
@凌驾
@异步的
公开作废法(){
...
试一试{
exchange(builder.toUriString(),HttpMethod.GET,entity,new parametedTypeReference(){});
responseEntity.getBody();
}捕获(HttpClientErrorException | HttpServerErrorException e){
log.error(“Hello”);
投掷(e);
}
}
我得到一个NullPointerException
,因为responseEntity.getBody()代码>不应该被调用,因为上面的行应该导致异常
怎么了?
谢谢大家! 您是否确保使用(Mockito.initMocks(this)
)或使用JUnit运行来初始化mock@RunWith(MockitoJUnitRunner.class)
?你能提供更多的代码吗?@NagarajTantri我正在使用@RunWith(SpringJUnit4ClassRunner.class)这个解决方案对我来说很有效,你能试一下吗?一次:@如果有@Saurabha,那就太好了。我试过这个解决方案,多亏了它,我才接近它。现在,期望被抛出到我想要的地方,但我没有在“期望”端收到我在测试中想要的期望。