Mockito - Cannot instantiate @InjectMocks
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.
Comments
-
Arpit Aggarwal about 2 years
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.
-
Arpit Aggarwal over 9 yearsI am having another dependency which i mocked. In my test class I can see it's mocked but when control is going to service class it is coming as null.
-
Arpit Aggarwal over 9 years@Test public void testGetOfficeForOperator() throws Exception { when(asignmentDao.getOfficeForOperator(Mockito.anyString())).thenReturn( serviceImplTestData.getAssignmentList()); serviceImpl.getOfficeForOperator("ABC", new Date(), new Date());}