Mockito - 无法实例化 @InjectMocks

Arp*_*wal 3 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 instance.
Run Code Online (Sandbox Code Playgroud)

下面是一段代码。

public class ServiceImpl implements Service {

    private OfficeDAO officeDAO;

    private DBDAO dbDAO;

    public ServiceImpl() {
        officeDAO = Client.getDaoFactory().getOfficeDAO();
        dbDAO = Client.getDaoFactory().getDBDAO();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试课:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

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


我发现你现在有一个不同的例外。但根据代码我无法透露更多信息。请提供失败测试的完整示例。