How to simulate classes using constructor injection (inject)…. here is a solution to the problem.
How to simulate classes using constructor injection (inject).
How to get constructor injection in Mockito
I have the following classes:
class A {
private B mB;
A(B b) {
mB = b;
}
void String someMethod() {
mB.execute();
}
}
How to test someMethod
using mock classes
A
and B
B b = Mockito.mock(B.class)
Mockito.when(b.execute()).thenReturn("String")
A a = Mockito.mock(A.class)
somehow inject b into A and make the below statement run
Mockito.when(a.someMethod()).check(equals("String"))
Solution
You need to create a real class A because you want to test it, but you need to simulate the other classes used in class A. In addition, you can find mockito documentation says don’t mock everything.
class ATest {
@Mock
private B b;
private A a;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
a = new A(b);
}
@Test
public String someMethodTest() {
String result = "result";
Mockito.when(b.execute()).thenReturn(result);
String response = a.someMethod();
Mockito.verify(b, Mockito.atLeastOnce()).execute();
assertEquals(response, result);
}
}