使用mockito为构造函数进行单元测试 [英] Unit testing with mockito for constructors
问题描述
我有一节课。
Class First {
private Second second;
public First(int num, String str) {
second = new Second(str);
this.num = num;
}
... // some other methods
}
我想为类First的公共方法编写单元测试。我想避免执行第二类的构造函数。
I want to write unit tests for public methods of class First. I want to avoid execution of constructor of class Second.
我这样做了:
Second second = Mockito.mock(Second.class);
Mockito.when(new Second(any(String.class))).thenReturn(null);
First first = new First(null, null);
它仍在调用类Second的构造函数。我该如何避免呢?
It is still calling constructor of class Second. How can i avoid it?
推荐答案
单位测试的问题又来自手动使用 new
运算符创建对象。考虑传递已经创建的第二
而不是:
Once again the problem with unit-testing comes from manually creating objects using new
operator. Consider passing already created Second
instead:
class First {
private Second second;
public First(int num, Second second) {
this.second = second;
this.num = num;
}
// some other methods...
}
我知道这可能意味着重写你的API,但没有别的办法。此类没有任何意义:
I know this might mean major rewrite of your API, but there is no other way. Also this class doesn't have any sense:
Mockito.when(new Second(any(String.class).thenReturn(null)));
首先,Mockito只能模拟方法,而不是构造函数。其次,即使你可以模拟构造函数,你也是在模拟刚刚创建的对象的构造函数,并且从不真正对该对象做任何事情。
First of all Mockito can only mock methods, not constructors. Secondly, even if you could mock constructor, you are mocking constructor of just created object and never really doing anything with that object.
这篇关于使用mockito为构造函数进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!