How to mock spring injected classes using JMockit
java, jmockit, junit, mocking, spring
Solution
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).
Problem
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.