如何在模拟时抑制内部方法

时间:2018-01-05 06:13:31

标签: java unit-testing mocking powermock

我想在MyClient中模拟 create 方法。但是当我运行测试用例时,它正在调用 MyClientImpl 构造函数并导致问题,因为我只想 create 来返回我的模拟客户端。我试图模拟/压缩 MyClientImpl 构造函数失败了。这是我到目前为止所做的事情

public interface MyClient {       
    public static MyClient create(Configuration conf) {
    return new MyClientImpl(conf);
}

public class MyClientImpl {
    MyClientImpl(Configuration conf) {
         //calls to create bunch of other objects
    }
}


@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClient.class})
public class TestClassA {
    MyClient client = PowerMockito.mock(MyClient.class);
    PowerMockito.mockStatic(MyClient.class, new Class[] {MyClient.class});
    //following line causes invocation of create method
    when(MyClient.create(any(Configuration.class))).thenReturn(client);
}

2 个答案:

答案 0 :(得分:0)

只需创建一个默认的虚拟构造函数,并使用静态方法上的mock返回它:

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyClient.class})
public class TestClassA {

  PowerMockito.mockStatic(MyClient.class);
  //following line causes invocation of create method
  when(MyClient.create(any(Configuration.class))).thenReturn(new MyClientImpl());
}

    public interface MyClient {       
        public static MyClient create(Configuration conf) {
        return new MyClientImpl(conf);
    }

    public class MyClientImpl {
        MyClientImpl(){}
        MyClientImpl(Configuration conf) {
             //calls to create bunch of other objects
        }
    }

或者你可以只压缩MyClientImpl的构造函数:

 /** Suppressing the constructor of MyClientImpl class
          which takes one Argument of Configuration type */
   suppress(constructor(MyClientImpl.class, Configuration.class));

您可以查看更多示例和详细信息in this articlehere,了解如何在不调用构造函数的情况下抑制构造函数,并且需要在mock / test下准备这两个类。

答案 1 :(得分:0)

您可以模拟MyClientImpl的构造函数以返回模拟对象:

PowerMockito.whenNew(MyClientImpl.class)
     .withAnyArguments()
     .thenReturn(mock(MyClientImpl.class))