Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Mockito更改方法中方法的值_Java_Junit_Mockito - Fatal编程技术网

Java 使用Mockito更改方法中方法的值

Java 使用Mockito更改方法中方法的值,java,junit,mockito,Java,Junit,Mockito,我想编写一个Junit测试用例,测试下面代码中的else{id=null;}语句。我试图做的是查看站点是否处于活动状态,是否处于活动状态,然后生成一个ID,但如果站点不处于活动状态(或下降一点),则将ID返回为null public static String createID() { String id = null; HttpURLConnection connection = accessProv(); if (checkConfigs()) { t

我想编写一个Junit测试用例,测试下面代码中的else{id=null;}语句。我试图做的是查看站点是否处于活动状态,是否处于活动状态,然后生成一个ID,但如果站点不处于活动状态(或下降一点),则将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(provenceutils.checkConfigs())中得到错误。然后返回(true);


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

问题是您将太多的责任推到了一个类中

示例:您有一个静态方法checkConfigs()。如果你想用类似的东西来代替它

interface ConfigurationChecker() {
  boolean isConfigurationValid();
..

class ConfigurationCheckerImpl implements ...
然后,您的测试类包含一个ConfigurationChecker类型的字段;并且您使用依赖注入(这样您的单元测试就可以将一个模拟的配置检查器推送到您的被测试类中)。。。突然,您获得了对影响方法行为的元素的完全控制

换句话说:你的代码,就像现在写的一样,很难测试。你需要控制的所有元素;测试代码根本无法(轻松)访问

您可以使用Powermock/mockito来测试它。。。或者退一步,学习如何编写易于测试的代码(例如通过观看);重做你的设计。。。最终得到的东西是A)设计更好的B)完全可测试的(没有“讨厌的”变通方法)。

记住,除非您使用

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

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


如果您正在测试
createID
,那么除了
checkConfigs
checkSiteResponse
之外,您不应该模拟任何东西。尽管这部分代码不是必需的。我将对其进行重构,使其看起来更像这样:
@Rule
public WireMockRule wireMockRule = new WireMockRule();

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