gpt4 book ai didi

java - Mockito - 无法实例化@InjectMocks

转载 作者:行者123 更新时间:2023-11-29 05:12:03 27 4
gpt4 key购买 nike

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

现在,当我尝试使用带有 @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 注释,它创建了 ServiceImpl 类的实例。因为您的构造函数试图从工厂获取实现:Client.getDaoFactory().getOfficeDAO() 您有 NPE。

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


我看到你现在有一个不同的异常(exception)。但是根据代码,我真的不能说得更多。请提供失败测试的完整示例。

关于java - Mockito - 无法实例化@InjectMocks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28084870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com