What is method equivalent for the following:
@Mock
MyType1 myType1;
@Autowired
@InjectMocks
MyType2 myType2;
I can replace @Mock with mock(MyType1.class).
But how can I replace @InjectMocks with a method call? Something like this:
injectMocks(MyType2.class)
Why using
Autowiredin your junit test? Since you are mocking the dependencies forMyType2you must know its concreate implementation when you write your test.Then you don’t need and shouldn’t use Spring or any injection framework to create the instance of
MyType2that you want to test. Create it directly in your test initialization! I know that after some years of using IoC frameworks, it’s difficult to writemyType2 = new MyType2Impl(mock(myType1.class))but it will really makes your tests simpler, and faster (because no application context to build).E.g.:
But if you really want to use IoC in your junit tests, use springockito has suggested by Brice, and build your mock
MyType1in your application context.