gpt4 book ai didi

java - 使用 Mockito 更改方法内方法的值

转载 作者:行者123 更新时间:2023-11-30 07:12:42 25 4
gpt4 key购买 nike

我想编写一个 Junit 测试用例来测试 else {id = null;下面代码中的语句。我想做的是查看该网站是否处于 Activity 状态,如果是,则生成一个 ID,但如果它不处于 Activity 状态(或出现故障),则将 id 返回为 null。

public static String createID() {
String id = null;
HttpURLConnection connection = accessProv();
if (checkConfigs()) {
try {
if(checkSiteResponse(connection)) {
id = generateID(connection);
} else {
//test this statement
id = null;
}
} catch (IOException e) {
LOG.error("IOException");
}
} else {
id = generateRandomID();
}
return id;
}

public static boolean checkConfigs() {
return (stormConf != null && (boolean)stormConf.get(ENABLE_ID_REGISTRATION) && !((boolean)stormConf.get(SUBMIT_TOPOLOGY_LOCALLY)));

public static HttpURLConnection accessProv() {
HttpURLConnection connection = null;
try {
URL url = new URL(PROV_CREATE_ID_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
} catch (IOException e) {
LOG.error("IOException");
}
return connection;
}
public static boolean checkSiteResponse(HttpURLConnection connection) throws IOException {
Boolean response;
if (connection.getResponseCode() == 200) {
response = true;
} else { response = false; }
return response;
}

我使用 Mockito 编写了下面的测试用例:

@Test
public void testRequestError() throws ParseException, IOException {
HttpURLConnection mockHttpConnection = Mockito.mock(HttpURLConnection.class);
ProvenanceUtils provenanceUtils = Mockito.mock(ProvenanceUtils.class);
provenanceUtils.checkSiteResponse(mockHttpConnection);
when(provenanceUtils.checkConfigs()).thenReturn(true);
when(provenanceUtils.accessProvenance().getResponseCode()).thenReturn(100);
System.out.println(provenanceUtils.createID());

但我收到错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Boolean cannot be returned by getResponseCode()
getResponseCode() should return int

我是 Mockito 新手,不知道如何将 getResponseCode 设置为 200 以外的值。我在第一个 when 语句 (when(provenanceUtils.checkConfigs) 中收到错误()).thenReturn(true);)。

基本上,我希望 checkConfigs() 返回 true,checkSiteResponse(connection) 返回 false。有没有办法用 Mockito 做到这一点?如果可以的话,我想避免使用 PowerMock。

最佳答案

请记住static methods can not be mocked with Mockito除非你使用PowerMockito .

除此之外,方法 accessProvenance() 返回的不是 mock (是实际的 HttpURLConnection 实例),因此 mockito 无法修改其行为。

您可以尝试使用 WireMock 来模拟 http 请求

@Rule
public WireMockRule wireMockRule = new WireMockRule();

...
public void testRequestError() throws ParseException, IOException {
stubFor(post(urlEqualTo(PROV_CREATE_ID_URL))
.willReturn(aResponse()
.withStatus(100)));
...
}

关于java - 使用 Mockito 更改方法内方法的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38944704/

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