junit Mockito -无法示例化@InjectMocks

de90aj5v  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(283)

我在我的类中有两个私有字段,我正在测试,这两个字段在构造函数中初始化。
现在,当我尝试使用我的类用@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);
    }
}

请帮助我如何解决它。任何帮助将不胜感激。

vom3gejh

vom3gejh1#

你正在使用@InjectMocks注解,它创建了ServiceImpl类的一个示例。因为你的构造函数试图从工厂获取实现:Client.getDaoFactory().getOfficeDAO()您有NPE。
确保Client.getDaoFactory()返回的是什么。我打赌它返回null,这就是问题所在:)重构你的代码,这样DaoFactory就可以通过参数传递,而不是使用static。
我看到你有一个不同的异常现在。但基于代码,我真的不能告诉更多。请,提供完整的例子失败的测试。

相关问题