spring-boot-mockito

fgw7neuy  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(152)

我正在为一些异步方法编写测试,其中我想模拟抛出异常。这些方法是同步的,我们的测试工作得很好,直到现在我使它们异步,有些原因是没有抛出模拟异常。
我的测试:

@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);
  }

}
我得到一个 NullPointerException 因为 responseEntity.getBody(); 在不应该调用时被调用,因为上面的行应该引起异常。
怎么了?谢谢您!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题