Junit方法中的模拟变量



如果我为以下方法写JUNIT,我该如何模拟clientInstance.execute

public class ClassName{
    public static <type> fun(){
        HttpClient clientInstance = null;
        // clientInstance initialised here 
        response = clientInstance.execute();
        //I am trying to mock clientInstance.execute 
    }
}

正如克里格(Kryger)指出的那样,您最好对代码进行重新设计以进行测试:

public class ClassName {
    public static <type> fun(HttpClient clientInstance){
        response = clientInstance.execute();
        //I am trying to mock response.execute 
    }
}

这称为依赖注入。这是将负担承担此代码的呼叫者的奇特术语。J.B.Rainsberger写了一篇很棒的文章。

如果您无法修改fun()的签名,因为太多其他代码取决于它,则可以超载:

public class ClassName {
    /* this method is *not* going to be tested */
    public static <type> fun(HttpClient clientInstance){
        HttpClient clientInstance = null;
        // clientInstance initialised here 
        return fun(clientInstance);
    }
    /* this method is going to be tested */
    public static <type> fun(HttpClient clientInstance){
        response = clientInstance.execute();
        // mocking clientInstance.execute() will be easy now
    }
}

如果HttpClient初始化很棘手,您想测试它怎么办?您可以将其重构为另一种方法:

public class ClassName {
    /**
      * Package-private for testing reasons.
      * Do not call it from within the class in production code!
    */
    static HttpClient createHttpClient() {
        HttpClient clientInstance = null;
        // clientInstance initialised here 
        return clientInstance;
    }
    /* this method is *not* going to be tested */
    public static <type> fun(HttpClient clientInstance){
        HttpClient clientInstance = createHttpClient();
        return fun(clientInstance);
    }
    /* this method is going to be tested */
    public static <type> fun(HttpClient clientInstance){
        response = clientInstance.execute();
        // mocking clientInstance.execute() will be easy now
    }
}

如果其他一切都失败了,则可以使用PowerMock来模拟构造函数。我从未见过值得麻烦的情况。无论如何,此Q&amp; A解释了如何使用它。

您可以使用Mockito.mock为客户端创建模拟实例,然后使用Mockito.when定义其返回的内容,例如:

HttpClient clientInstance = Mockito.mock(HttpClient.class); // initialize mock
Object mockReturn = new Object(); // define your return object
Mockito.when(clientInstance.execute()).thenReturn(mockReturn); // define what mock returns
Object response = clientInstance.execute(); // call your mock

相关内容

  • 没有找到相关文章

最新更新