是否可以在与子类具有相同名称和类型的父类(super class)字段中注入(inject)模拟。
在我的情况下,我有一个 Controller 类
abstract class BaseController {
protected AccessManager accessManager;
}
它由如下所示的类扩展:
class ApiController<T> extends BaseController {
}
最后,一个更专业的 Controller 将其扩展如下:
class PersonController extends ApiController<Person> {
private AccessManager accessManager;
}
我正在为 PersonController
编写单元测试,在测试它时,它的一些方法调用 BaseController
的方法,该方法委托(delegate)调用它的protected
成员对象,始终为 null
。
我尝试使用@InjectMocks
并使用ReflectionTestUtils.setField
来设置BaseController
的 protected 字段,但这些方法最终只能结束在 PersonController
类上设置字段,因为它们的名称和类型相同。
我花了很多时间在这上面,但没能解决它。请帮忙。 谢谢
最佳答案
正如 @strelok 提到的,您可以只使用具有以下签名的方法
public static void setField(@Nullable Object targetObject, @Nullable Class<?> targetClass, @Nullable String name, @Nullable Object value, @Nullable Class<?> type)
需要您在字段设置时指定使用哪个类,例如父级
或子级
public class Parent {
private String name;
public String getName() {
return name;
}
}
public class Child extends Parent {
private String name;
public String getName() {
return name;
}
public void printNames() {
System.out.println("I'm " + this.name);
System.out.println("My father is " + super.getName());
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
ReflectionTestUtils.setField(child,Parent.class, "name", "fatah",String.class);
ReflectionTestUtils.setField(child,Child.class, "name", "abdul",String.class);
child.printNames();
}
}
关于java - Mockito - 如果父类(super class)包含与子类具有相同名称和类型的字段,如何注入(inject)模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51602666/