gpt4 book ai didi

java - 如何模拟本地 OAuth2RestTemplate restTemplate?

转载 作者:行者123 更新时间:2023-11-30 01:40:47 24 4
gpt4 key购买 nike

我有一个方法:

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 之后的代码覆盖率。我在这里错过了什么,我要疯了!

最佳答案

看来您需要使用 Mockito 中的匹配器。

在您的情况下,restTemplate 的 3 个参数有点令人困惑。第一个是 String 值,因此使用 anyString() 来匹配它并模拟 somethingElse.getUrl(),该代码不在该示例不确定它的作用,但它必须返回一个 String 而不是 null。看起来你想匹配第二个任何字符串,对于 Mockito,你需要使用 anyString()any() 如果它不是 String 来实现这一点。第三个是 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);
}

关于java - 如何模拟本地 OAuth2RestTemplate restTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com