Java Mockito-无法实例化@InjectMocks

Java Mockito-无法实例化@InjectMocks,java,junit,mocking,Java,Junit,Mocking,我正在测试的类中有两个私有字段,这两个字段在构造函数中初始化 现在,当我试图使用@InjectMocks注释的类调用时,它抛出异常: Cannot instantiate @InjectMocks field named 'ServiceImpl' of type 'class com.test.ServiceImpl'. You haven't provided the instance at field declaration so I tried to construct the ins

我正在测试的类中有两个私有字段,这两个字段在构造函数中初始化

现在,当我试图使用@InjectMocks注释的类调用时,它抛出异常:

 Cannot instantiate @InjectMocks field named 'ServiceImpl' of type 'class com.test.ServiceImpl'. You haven't provided the instance at field declaration so I tried to construct the instance.
下面是一段代码

public class ServiceImpl implements Service {

private OfficeDAO officeDAO ;

private DBDAO dbDAO ;

public ServiceImpl() {
officeDAO = Client.getDaoFactory().getOfficeDAO();
dbDAO = Client.getDaoFactory().getDBDAO();
}
我的测试班:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest {

    @Mock
    private OfficeDAO officeDAO;

    @Mock
    private DBDAO dbDAO;

    @Mock
    Client client;

    @InjectMocks
    private ServiceImpl serviceImpl;

    @Mock
    private Logger log;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }
请帮助我如何解决它。
任何帮助都将不胜感激。

您正在使用
@InjectMocks
注释,该注释将创建
serviceinpl
类的实例。因为您的构造函数正在尝试从工厂获取实现:
Client.getDaoFactory().getOfficeDAO()
您拥有NPE

确保
Client.getDaoFactory()
返回的内容。我打赌它会返回null,这就是问题所在:)重构代码,使DaoFactory通过参数传递,而不是使用静态



我看你现在有一个不同的例外。但根据代码,我真的不能说更多。请提供测试失败的完整示例。

无需调用
MockitoAnnotations.initMocks(this)
如果您声明
MockitoJUnitRunner
为junit测试运行程序。您使用的是哪个版本的mockito为什么构造函数名称ShiftManagerServiceImpl在ServiceImpl类中?实际上,假设构造函数名称只是一个复制粘贴问题,我使用mockito版本1.9.5和一些虚拟测试用例尝试了这段代码,但是没有遇到任何错误。您是否可以尝试通过简单的serviceinpl=newserviceinpl()实例化;在initMocks()调用而不是使用@InjectMocks之后,我有了另一个我模拟的依赖项。在我的测试类中,我可以看到它被模拟了,但当控件要进入服务类时,它将显示为null。@test public void TestGetOfficePropertor()抛出异常{当(asignmentDao.GetOfficePropertor(Mockito.anyString())。然后返回(ServiceImpletTestData.getAssignmentList());serviceImpl.GetOfficePropertor(“ABC”,new Date()),新日期());}