How to mock classes with constructor injection
Another way of injecting a mock to real object (as A should be a real object) is to use annotations, they will create objects you want:
@Mock
B mockOfB;
@InjectMocks
A realObjectA;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
Then, like they said, run the method you want to test without mockito (because you want to test it, so call it on real instance) and check the result according to your expectations.
Behaviour of object B can be mocked in any way, to satisfy your needs.
You want to test someMethod()
of class A
. Testing the execute()
of class B
should take place in the other test, because instance of B
is a dependency in your case. Test for execute()
should be made in different test.
You don't need to test how B object will behave, so you need to mock it and afterwards, check that execute()
was invoked.
So in your case your test will look something like this:
B b = Mockito.mock(B.class);
A a = new A( b );
a.someMethod();
Mockito.verify( b, Mockito.times( 1 ) ).execute();
You need create real A class because you want to test it but you need to mock other classes used in A class. Also, you can find mockito documentation says that 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);
}
}
In my opinion, you're mixing up two ways of testing.
If you want to write a test using Mockito, you just create a mock of some class and use it. This mock doesn't have anything related to a real object as you can (should) mock every method that is called in the test. That's why it doesn't make any sense to mock class B
- it is simply not used by class A
.
Otherwise, if you want to test a real behavior of class A
then why do you want to mock it? Create a real instance of class A
with a mocked instance of class B
.
That's it! Don't mix it up.