我的代码如下
public process() {
extract();
...
}
private Obj extract() {
Constructor const = new Constructor();
Obj object = const.getOBJMethod("12345","c:/file/a.zip",null);
return object;
}
我正在使用 mockito 测试方法过程。 在我的测试课中,我将代码编写为
Constructor mocckConst = mock(Constructor.class);
Obj mockObject = mock(Obj.class);
when(mocckConst .getOBJMethod("12345","c:/file/a.zip",null).thenReturn(mockObject);
但是当调用 extract 方法时测试用例的执行将转到 getOBJMethod() 的真正实现。
构造函数类有另一个内部类。这会导致任何问题吗? 谁能告诉我这里出了什么问题以及解决方案。
我想改进我的处理方法。
public process(String base) {
if("abc".equals(base)) {
---
}
else if("def".equals(base) {
extract();
---
}
}
只有当 basis 为 def 时,extract() 才会被调用。而且我不想将构造函数对象传递给 process() 方法,那么有什么解决方案吗?
最佳答案
在您要测试的类中,您创建了一个新的 Constructor 对象(通过 Constructor const = new Constructor()
),因此,您始终使用 REAL 实现。如果你想将它替换为用于测试的模拟对象,则必须注入(inject) Constructor
对象。也可以通过用于测试的构造函数进行注入(inject)。
private final Constructor const; // remove final, if required
public <ConstructorOfYourClassHere>(Constructor const) {
assert const != null : "const != null"; // use assertions, if you like
this.const = const;
// other constructor code...
}
// your other code here...
public process(String base) {
if("abc".equals(base)) {
// ---
}
else if("def".equals(base) {
extract();
// ---
}
}
private Obj extract() {
Obj object = const.getOBJMethod("12345","c:/file/a.zip",null);
return object;
}
然后您可以在创建被测对象并调用process()
时注入(inject)mock。然后将使用您的模拟实现。
顺便说一句:
- 如果您是代码的所有者,您可能希望将
extract
方法的可见性更改为protected
,以便您也可以测试该方法。参见 here . - 此外,您可能还想阅读一些有关依赖注入(inject)的一般知识。使用 DI 进行测试通常要容易得多。您不必使用 DI 框架,只需在对象创建时通过方法参数或构造函数注入(inject)您的依赖项。
关于java - 在 Mock 对象上调用方法是调用真实方法而不是模拟实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25113384/