EasyMock:模拟 Java 中的构造函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7653263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EasyMock: Mock out a constructor call in java
提问by Setzer
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.
我在这个板上看过类似的问题,但没有一个回答我的问题。这听起来很奇怪,但是是否可以模拟对您模拟的对象的构造函数调用。
Example:
例子:
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.
}
}
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.
我怎么能期待构造函数调用?我可以更改 Customer 构造函数调用以使用 newInstance,但我不确定这是否有帮助。我无法控制new Customer(145)
构造函数的主体做什么。
Is this possible?
这可能吗?
回答by betaboy00
you can do so with EasyMock 3.0 and above.
您可以使用 EasyMock 3.0 及更高版本来实现。
Customer cust = createMockBuilder(Customer.class)
.withConstructor(int.class)
.withArgs(145)
.addMockedMethod("someMethod")
.createMock();
回答by Augusto
You can't do this with easymock, as it doesn't support mocking constructors. There's a library called powermockwhich can do that and is the only mocking library, as far as I know, that can stub constructors and static methods in Java.
你不能用 easymock 做到这一点,因为它不支持模拟构造函数。有一个名为powermock的库可以做到这一点,据我所知,它是唯一一个可以在 Java 中存根构造函数和静态方法的模拟库。
回答by Truong Ha
import static org.powermock.api.easymock.PowerMock.expectNew;
instance = new UsesNewToInstantiateClass();
expectNew(AnyOldClass.class).andReturn(anyClass);
回答by Charles Roth
And this is why you want to inject your dependencies (via Guice or similar package) instead of creating them inside your class.
这就是为什么要注入依赖项(通过 Guice 或类似包)而不是在类中创建它们的原因。
Then you don't HAVE TO mock their construction.
那么你就不必嘲笑他们的构造。
This assumes (a) that this is your code that you can change, and (b) that the objects in question are complex enough that you should inject them. Constructing simple objects inside your class are fine, but then you shouldn't need to mock them.
这假设 (a) 这是您可以更改的代码,以及 (b) 有问题的对象足够复杂,您应该注入它们。在你的类中构造简单的对象很好,但是你不需要模拟它们。