This is the way of how I use Mockito with Spring.
Lets assume I have a Controller that use a Service and this services inject its own DAO, basically have this code structure.
@Controller
public class MyController{
@Autowired
MyService service;
}
@Service
public class MyService{
@Autowired
MyRepo myRepo;
public MyReturnObject myMethod(Arg1 arg){
myRepo.getData(arg);
}
}
@Repository
public class MyRepo{}
Code below is for the junit test case
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest{
@InjectMocks
private MyService myService;
@Mock
private MyRepo myRepo;
@Test
public void testMyMethod(){
Mockito.when(myRepo.getData(Mockito.anyObject()).thenReturn(new MyReturnObject());
myService.myMethod(new Arg1());
}
}
If you are using standalone applications consider mock as below.
@RunWith(MockitoJUnitRunner.class)
public class PriceChangeRequestThreadFactoryTest {
@Mock
private ApplicationContext context;
@SuppressWarnings("unchecked")
@Test
public void testGetPriceChangeRequestThread() {
final MyClass myClass = Mockito.mock(MyClass.class);
Mockito.when(myClass.myMethod()).thenReturn(new ReturnValue());
Mockito.when(context.getBean(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(myClass);
}
}
I dont really like create mock bean within the application context, but if you do make it only available for your unit testing.