首页 > 解决方案 > 如何对一个类的方法进行单元测试,该方法又调用另一个类的方法

问题描述

嗨,我的课看起来像这样。

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-testingjunitvoid

解决方案


如果您使用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

}

更多关于Mockito 这里


推荐阅读