EasyMock:在java中模拟一个构造函数调用 [英] EasyMock: Mock out a constructor call in java

查看:328
本文介绍了EasyMock:在java中模拟一个构造函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个板上看过类似的问题,但没有人回答我的问题。这听起来很奇怪,但是可以在你正在嘲笑的对象上模拟一个构造函数调用。

I have a looked at similar questions on this board, but none of them answer my question. This sound strange, but is it possible to mock out a constructor call on the object you're mocking.

示例:

class RealGuy {

   ....
   public void someMethod(Customer customer) {
     Customer customer = new Customer(145);
   }
}
class MyUnitTest() {
  public Customer customerMock = createMock(Customer.class)
  public void test1() {
    //i can inject the mock object, but it's still calling the constuctor
    realGuyobj.someMethod(customerMock);
    //the constructor call for constructor makes database connections, and such.
  }
}

我如何期待构造函数调用?我可以更改Customer构造函数调用以使用newInstance,但我不确定这是否有帮助。我无法控制新客户(145)构造函数的主体是什么。

How can I expect a constructor call? I can change the Customer constructor call to use newInstance, but im not sure if that will help. I have no control over what the body of the new Customer(145) constructor does.

这可能吗?

推荐答案

您可以使用EasyMock 3.0及以上版本。

you can do so with EasyMock 3.0 and above.

Customer cust = createMockBuilder(Customer.class)
     .withConstructor(int.class)
     .withArgs(145)
     .addMockedMethod("someMethod")
     .createMock();

这篇关于EasyMock:在java中模拟一个构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆