java Mockito无法实例化@InjectMocks
我正在测试的类中有两个私有字段,这两个字段在构造函数中初始化
现在,当我试图使用@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);
}
请帮我解决这个问题。 任何帮助都将不胜感激
# 1 楼答案
您正在使用
@InjectMocks
注释,它创建了ServiceImpl
类的一个实例。因为您的构造函数试图从工厂获得实现:Client.getDaoFactory().getOfficeDAO()
您有NPE确保
Client.getDaoFactory()
返回的内容。我打赌它会返回null,这就是问题所在:)重构代码,以便通过参数而不是使用静态参数传递DaoFactory我看你现在有一个不同的例外。但根据代码,我真的说不出更多。请提供测试失败的完整示例