我有一个方法:
public void putObj(Doc doc) {
for (int i = 0; i < 3; i++) {
try {
OAuth2RestTemplate restTemplate = something.thatReturnsOAuth2RestTemplate(props);
restTemplate.postForEntity(somethingElse.getUrl(), doc.toJSONString(), String.class);
break;
} catch (HttpClientErrorException | HttpServerErrorException e) {
//do stuff in here
}
}
}和我的测试类:
@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(OkHttp3TemplateUtil.class)
public class TestingClass {
@InjectMocks
private static MyService myService;
@Mock
private static Something something;
@Mock
private static Props props;
@Mock
private static OAuth2RestTemplate restTemplate;
@Test
public void testExceptionCaughtWhenThrownByRestTemplate(){
PowerMockito.mockStatic(OkHttp3TemplateUtil.class);
Doc doc = new Doc.docBuilder().setSomething("");
when(something.thatReturnsOAuth2RestTemplate(props)).thenReturn(restTemplate);
when(restTemplate.postForEntity("http://dummy.com", String.class, String.class)).thenThrow(HttpClientErrorException.class);
myService.putObj(doc);
}
}无论我做什么,thenThrow都不会抛出异常。测试通过后,不会为catch之后的代码提供覆盖率。我错过了什么,我快疯了!
发布于 2020-02-07 10:42:19
看起来你需要使用来自Mockito的匹配器。
在您的例子中,restTemplate的3个参数有点混乱。第一个是一个String值,所以使用anyString()来匹配它并模拟somethingElse.getUrl(),该代码不在示例中,所以不确定它做了什么,但它必须返回一个String,而不是null。看起来你想要匹配第二个字符串,如果不是String,你需要使用anyString()或any()来完成。第三个是String.class的实际值,因此再次使用eq()。请注意,如果任何参数为空,则它将不匹配。此外,如果您不小心,很容易最终模拟出一个不同的重载postForEntity。
对于something.thatReturnsOAuth2RestTemplate来说,没有匹配器可能也没问题。如果Props类定义了equals,并且测试代码值和生产代码值相等。但是,该示例没有显示此信息,因此我也添加了该信息的any(Props.class)。
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@Test
public void testExceptionCaughtWhenThrownByRestTemplate(){
PowerMockito.mockStatic(OkHttp3TemplateUtil.class);
Doc doc = new Doc.docBuilder().setSomething("");
when(something.thatReturnsOAuth2RestTemplate(any(Props.class))).thenReturn(restTemplate);
when(restTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(response);
}https://stackoverflow.com/questions/60106145
复制相似问题