Java 如何模拟本地OAuth2RestTemplate restTemplate?
我有一个方法:Java 如何模拟本地OAuth2RestTemplate restTemplate?,java,rest,unit-testing,testing,mockito,Java,Rest,Unit Testing,Testing,Mockito,我有一个方法: public void putObj(Doc doc) { for (int i = 0; i < 3; i++) { try { OAuth2RestTemplate restTemplate = something.thatReturnsOAuth2RestTemplate(props); restTemplate.postForEntity(somethingEls
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
}
}
}
无论我做什么,
然后抛出
都不会抛出异常。测试通过后,不会为捕获后的代码提供覆盖。我错过了什么,我快疯了 看起来您需要使用Mockito提供的匹配器
在您的例子中,restemplate
的3个参数有点混乱。第一个是String
值,因此使用anyString()
匹配它并模拟somethingElse.getUrl()
,该代码不在示例中,因此不确定它做了什么,但它必须返回String
且不为null
。看起来您想要为第二个字符串匹配任何字符串,使用Mockito,您需要使用anyString()
或any()
,如果它不是字符串,则需要使用any()
。第三个是String.class的实际值,因此再次使用eq()
。注意,如果任何参数为null,则它将不匹配。此外,如果不小心,很容易模拟出不同的重载postForEntity
对于返回SOAuth2RestTemplate的something.that,如果没有匹配器,您可能还可以。如果Props
类定义了equals,并且测试代码值和生产代码值相等。但是,该示例没有显示此信息,因此我也添加了any(Props.class)
import static org.mockito.ArgumentMatchers.any;
导入静态org.mockito.ArgumentMatchers.anyString;
导入静态org.mockito.ArgumentMatchers.eq;
@试验
public void testExceptionCaughtWhenThrownByRestTemplate(){
mockStatic(OkHttp3TemplateUtil.class);
Doc Doc=new Doc.docBuilder().setSomething(“”);
当(某物返回soauth2restTemplate(any(Props.class)),然后返回(restTemplate);
当(restemplate.postForEntity(anyString(),any(),eq(String.class)))。然后返回(response);
}
我得到了与上述代码完全相同的结果:(OkHttp3TemplateUtil
的内容是什么?它没有出现在生产代码中抱歉,OkHttp3TemplateUtil
=something
。我在重命名这里发布的方法时错过了它。如果somethingElse.getUrl()
或doc.toJSONString())
returnnull
或任何不是字符串的东西,例如URI
因为postForEntity有很多重载,所以它将不匹配。这是我调用的postForEntity()
方法:public ResponseEntity postForEntity(URI url、@Nullable Object request、Class responseType)
@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);
}
}