问题描述
我有一个带有注入属性的摘要.这是由一个子类扩展的,其中注入是通过构造函数完成的.在单元测试中,@InjectMocks 为抽象类中注入的属性提供 null.
I have an abstract with an injected property. This is extended by a child class where the injection is done via constructor. In the Unit test, the @InjectMocks gives null for the property injected in the abstract class.
查看下面的代码.
我想了解为什么在这种特定情况下 @InjectMocks 不知道从抽象类中注入属性.有人可以帮我理解吗?非常感谢!!!
I would like to understand why in this specific situation the @InjectMocks does not know to inject the property from the abstract class.Can anybody help me to understand?Thanks a lot!!!
如果子类和父类都使用属性注入,我的单元测试就没有问题.
If both child and parent class uses property injection, my unit test works without problems.
public abstract class AbstractClass
{
@Inject
private D d;
...
}
@RequestScoped
public class ConcreteClass extends AbstractClass
{
private A a;
private B b;
private C c;
@Inject
public ConcreteClass(A a, B b, C c)
{
this.a = a;
this.b = b;
this.c = c;
}
/**
* CDI, no arguments constructor.
*/
public ConcreteClass()
{
// CDI constructor
}
}
@RunWith(Theories.class)
public class ConcreteClassTest
{
@Mock
D d;
@Mock
A a;
@InjectMocks
ConcreteClass concreteClass;
@Before
public void setUp() throws Exception
{
...
MockProvider.setMockForClass(A.class, a);
MockProvider.setMockForClass(D.class, d);
...
}
@Theory
public void testMethod()
{
...
concreteClass.methodXXX();
//here if i inspect the concreteClass i see that the attribute "a" has value and attribute "d" is null.
...
}
}
推荐答案
来自 mockito 文档:
https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/InjectMocks.html
From the mockito documentation:
https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/InjectMocks.html
构造函数注入;选择最大的构造函数,然后使用仅在测试中声明的模拟来解析参数.如果使用构造函数成功创建了对象,则 Mockito 不会尝试其他策略.Mockito 决定不破坏具有参数构造函数的对象.
因为你的构造函数只有 A、B、C,mockito 没有处理 D.
(不考虑属性或字段注入)
As your constructor only has A, B, C mockito does not take care of D.
(Property or Field injection are not considered)
您可以更改构造函数,使其具有全部 4 个值并将 D 传递给超类.
You could change your Constructor so that it has all 4 values and passes on D to the superclass.
这篇关于当我结合构造函数注入(子类)和属性注入(父类)时,@InjectMocks 给我 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!