[英]How to use PowerMockito to mock new class instance inside a static method
[英]Mock method on a new instance
我正在尝试使用 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;
}
}
我有一个像上面一样的 class 结构,我需要模拟 secondMethod。
我在 FirstClass 上尝试了@spy 并模拟了 SecondClass 和 secondMethod,但是 mocking 没有发生。 在这种情况下我该如何模拟?
注意 - 我不在 position 中更改 class 的结构。
你有一些选择:
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
设置器仅用于测试。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.