【问题标题】:How to unit test a method of a class which inturn calls a method from another class如何对一个类的方法进行单元测试,该方法又调用另一个类的方法
【发布时间】:2020-08-24 02:29:52
【问题描述】:

嗨,我的班级看起来像这样。

public class Class1 {

    public void method1(Object obj) {

        // Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202
        Class2 class2 = new Class2();
        String result = class2.callRestService();
        System.out.println(result);
    }

}
public class Class2 {

    public String callRestService() {
        String url = fetchUrl(System.getProperty(COnstants.URL);
        String result = callRestServiceAPi(url); // Calling the RestApimethod.
        return result;
    }

}

我想为 class1 编写单元测试,并且我想通过实际不调用 RestAPi 来实现它,这意味着我想模拟 class2.callRestService() 方法以返回“成功”或“失败”。怎么可能。

【问题讨论】:

    标签: unit-testing junit void


    【解决方案1】:

    如果你使用new(然后不使用injection)你总是会遇到一些测试问题。

    你有两种选择:

    1. 使用PowerMockito
    2. new 包装在一个方法中并模拟该方法
    public class Class1 {
    
        protected Class2 getClient(){
             return new Class2();
        }
    
        public void method1(Object obj) {
    
            // Class 2 makes the restApiCall and result as "SUCCESS" if the HTTP response is 202
            Class2 class2 = new Class2();
            String result = class2.callRestService();
            System.out.println(result);
        }
    
    }
    

    然后,在你的 Junit 中

    @Test
    public void test(){
        Class1 class1 = Mockito.spy(new Class1());
        Class2 class2 = Mockito.mock(Class2.class);
        Mockito.doReturn("your result").when(class2).callRestService();
        Mockito.doReturn(class2).when(class1).getClient();
        // assert something
    
    }
    

    更多关于Mockitohere

    【讨论】:

    • 不添加那个额外的方法是不可能的
    • 正如我所写,您可以使用PowerMockito,但这绝不是一个好主意,只是最后一次机会
    猜你喜欢
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多