My code:
class A extends X {
@Autowired
B b;
@Override
method() {
//do something
b.callMethodInB;
//do something
}
}
class B extends X {
@Autowired
C c;
@Override
method() {
//do something
c.callMethodInC;
//do something
}
}
I need to test method()
in A
. So how to mock B
. I'm using Junit4 and Jmockit.
Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.
JMockit will be the chosen option for its fixed-always-the-same structure. Mockito is more or less THE most known so that the community will be bigger. Having to call replay every time you want to use a mock is a clear no-go, so we'll put a minus one for EasyMock. Consistency/simplicity is also important for me.
We can use the @MockBean to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. If no bean of the same type is defined, a new one will be added.
Try something like this:
import org.junit.*;
import mockit.*;
public class ATest
{
@Tested A a;
@Injectable B b;
@Test
public void testMethod()
{
a.method();
new Verifications() {{ b.callMethodInB(); }};
}
}
JMockit automatically instantiates A
with an injected B
instance (from the mock field b
), setting it to the a
field in the test class. This is independent of the DI framework used (Spring).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With