java Mockito - 无法实例化 @InjectMocks

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28084870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:59:07  来源:igfitidea点击:

Mockito - Cannot instantiate @InjectMocks

javajunitmocking

提问by Arpit Aggarwal

I have two private fields in my class which I am testing and these two fields are initialized in constructor.

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

Now when I am trying to call using my class annotated with @InjectMocks, it is throwing exception:

现在,当我尝试使用用@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.

Below is the piece of code.

下面是一段代码。

public class ServiceImpl implements Service {

private OfficeDAO officeDAO ;

private DBDAO dbDAO ;

public ServiceImpl() {
officeDAO = Client.getDaoFactory().getOfficeDAO();
dbDAO = Client.getDaoFactory().getDBDAO();
}

My test class:

我的测试班:

@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);
    }

Please help me how I can resolve it. Any help will be appreciated.

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

回答by bbankowski

You are using @InjectMocksannotation, which creates an instance of ServiceImplclass. Because your constructor is trying to get implementation from factory: Client.getDaoFactory().getOfficeDAO()you have NPE.

您正在使用@InjectMocks注释,它创建ServiceImpl类的实例。因为您的构造函数正试图从工厂获得实现:Client.getDaoFactory().getOfficeDAO()您有 NPE。

Make sure what is returned by Client.getDaoFactory(). I bet it returns null and that's the problem :) Refactor your code, so that DaoFactory is passed via parameter rather than using static.

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



I see you have a different exception right now. But based on the code I cannot really tell more. Please, provide full example of failing test.

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