Mockito无法实例化被测试的类

时间:2013-12-12 10:23:17

标签: java unit-testing mockito

我有三个课程ABC

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

1 个答案:

答案 0 :(得分:4)

这是总是会失败:

public class A {
  private B someB;
  private C someC = someB.getSomeC();
}

您尝试在始终为空的值上调用getSomeC() ...将始终抛出NullPointerException。您需要修复A以更好地处理依赖关系。 (就个人而言,我会将它们作为构造函数参数,但当然还有其他选项......)

相关问题