我有一个带有注入(inject)属性的摘要。这是由子类扩展的,其中注入(inject)是通过构造函数完成的。在单元测试中,@InjectMocks 为抽象类中注入(inject)的属性提供 null。
请参阅下面的代码。
我想了解为什么在这种特定情况下 @InjectMocks 不知道从抽象类注入(inject)属性。 有人能帮我理解吗? 非常感谢!!!
如果子类和父类都使用属性注入(inject),我的单元测试可以正常工作。
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
Constructor injection; the biggest constructor is chosen, then arguments are resolved with mocks declared in the test only. If the object is successfully created with the constructor, then Mockito won't try the other strategies. Mockito has decided to no corrupt an object if it has a parametered constructor.
由于你的构造函数只有 A、B,所以 Mockito C 不关心 D。
(不考虑属性或字段注入(inject))
您可以更改构造函数,使其具有所有 4 个值并将 D 传递给父类(super class)。
关于java - 当我组合构造函数注入(inject)(子类)和属性注入(inject)(父类)时,@InjectMocks 给我 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57091389/