Search code examples
javajunitmocking

Mockito - Cannot instantiate @InjectMocks


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:

 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.


Solution

  • You are using @InjectMocks annotation, which creates an instance of ServiceImpl class. Because your constructor is trying to get implementation from factory: Client.getDaoFactory().getOfficeDAO() you have 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.


    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.