使用 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 类的公共方法编写单元测试.我想避免执行类 Second 的构造函数.
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
运算符手动创建对象.考虑传递已经创建的 Second
:
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屋!