我想写测试其他{ID = NULL JUnit测试用例中更改的方法值; }声明在下面的代码中。我想要做的是看看网站是否有活动,如果它是生成一个ID,但如果它不活(或下降了一点)返回id为空。使用到的Mockito的方法
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(provenanceUtils.checkConfigs()).thenReturn(true);
时收到错误。
基本上我想checkConfigs()
返回true和checkSiteResponse(connection)
返回false。有没有办法与Mockito做到这一点?我想避免使用PowerMock,如果我可以帮助它。
嘲讽的HTTP请求,如果您正在测试'createID'你不应该嘲笑比'checkConfigs'和'checkSiteResponse'的任何其他。尽管这部分代码不是必需的。我会重构它看起来更像这样:https://gist.github.com/davelnewton/92b768d9925baa683e6323a4fd9f82cd –