Reputation: 2710
I've got three classes A
, B
and C
:
public class A {
@Autowired
private B someB;
private C someC = someB.getSomeC();
}
@Service
public class B {
C getSomeC() {
return new C();
}
}
public class C { }
Now if I write a unit test for A
which looks like:
@RunWith(MockitoJUnitRunner.class)
public class ATest {
@InjectMocks
private A classUnderTest;
@Mock
private B someB;
@Mock
private C someC;
@Test
public void testSomething() {
}
}
Mockito is not happy with this:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'classUnderTest' of type 'class my.package.A'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
If I remove the call in class A
, such that class A
looks like the following:
public class A {
private B someB;
private C someC;
}
, Mockito is able to instantiate the classUnderTest and the test runs through.
Why is this the case?
edit: Using Mockito 1.9.5
Upvotes: 1
Views: 9165
Reputation: 1499770
Well this is always going to fail:
public class A {
private B someB;
private C someC = someB.getSomeC();
}
You're trying to call getSomeC()
on a value which will always be null... that will always thrown NullPointerException
. You need to fix A
to handle the dependencies better. (Personally I'd take them as constructor parameters, but there are other options of course...)
Upvotes: 4