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

标签 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);
}

最佳答案

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

@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关于如何抑制构造函数而不调用它们,您需要在模拟/测试下准备两个类。

关于java - 如何在模拟时抑制内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48108162/

相关文章:

javascript - 为什么 Jest 仍然需要模拟模块?

c# - 在单元测试中模拟 Automapper 是一种好习惯吗?

java - 映射过程数据在hadoop中可能为空

java - Solrcloud性能问题

java - 使用 JSoup 从 Amazon 检索评论

c++ - 如何实现编译时的功能单元测试?

ruby - RSpec:如何测试哈希数组中键的存在?

c++ - 提交后选择智能单元测试

java - 元素的 ArrayList 链接并获取 IndexOutOfBoundsException

python - 从类方法中模拟/修补计算属性的值