我正在尝试使用 Mockito 框架和 junit5 创建 Junit 测试用例。我正在编写以下代码:
Class ClasstToBeTested {
FirstClass a = new FirstClass();
public String methodToBeTested() {
String str = a.firstMethod();
return str;
}
}
Class FirstClass {
SecondClass b = new SecondClass();
public String firstMethod() {
String str = b.secondMethod();
return str;
}
}
我有一个像上面这样的类结构,我需要模拟第二个方法。
我在 FirstClass 上尝试了 @spy 并模拟了 SecondClass 和 secondaryMethod,但模拟并没有发生。在这种情况下我该如何嘲笑?
注意 - 我无法更改班级的结构。
您有一些选择:
SecondClass
实例,而不是在 FirstClass
内部构建它: class FirstClass {
private final SecondClass b;
// Injecting the SecondClass instance
FistClass(SecondClass b) {
this.b = b;
}
public String firstMethod() {
String str = b.secondMethod();
return str;
}
}
然后你可以在测试中注入模拟。
SecondClass
setter 仅用于测试。 class FirstClass {
SecondClass b = new SecondClass();
// Annotate with a visibility for test annotation if available.
// Here one can inject a mock too, but can cause problems if used inadvertently.
void setSecondClassForTests(SecondClass b) {
this.b = b;
}
public String firstMethod() {
String str = b.secondMethod();
return str;
}
}
然后您在测试中调用 setter 并通过模拟。
final Field declaredField = instanceOfFirstClass.getClass().getDeclaredFields("b");
declaredField.setAccessible(true);
declaredField.set(instanceOfFirstClass, yourMockedInstance);
最新版本的mockito支持模拟构造函数