我有三个类A
、B
和C
:
public class A {
@Autowired
private B someB;
private C someC = someB.getSomeC();
}
@Service
public class B {
C getSomeC() {
return new C();
}
}
public class C { }
现在,如果我为A
编写一个单元测试,它看起来像:
@RunWith(MockitoJUnitRunner.class)
public class ATest {
@InjectMocks
private A classUnderTest;
@Mock
private B someB;
@Mock
private C someC;
@Test
public void testSomething() {
}
}
Mockito对此并不满意:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'classUnderTest' of type 'class my.package.A'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
如果我删除类A
中的调用,那么类A
看起来如下:
public class A {
private B someB;
private C someC;
}
,Mockito能够实例化classUnderTest,并且测试贯穿始终。
为什么会出现这种情况?
编辑:使用Mockito 1.9.5
这是总是会失败:
public class A {
private B someB;
private C someC = someB.getSomeC();
}
您正试图对始终为null的值调用getSomeC()
。。。将总是抛出CCD_ 8。您需要修复A
以更好地处理依赖关系。(就我个人而言,我会将它们作为构造函数参数,但当然还有其他选项…)