我有三个课程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
答案 0 :(得分:4)
这是总是会失败:
public class A {
private B someB;
private C someC = someB.getSomeC();
}
您尝试在始终为空的值上调用getSomeC()
...将始终抛出NullPointerException
。您需要修复A
以更好地处理依赖关系。 (就个人而言,我会将它们作为构造函数参数,但当然还有其他选项......)