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)
initMocks. Deprecated. Use openMocks(Object) instead. This method is equivalent to openMocks(testClass).
@Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class. Annotated class to be tested dependencies with @Mock annotation.
@InjectMocks is the Mockito Annotation. It allows you to mark a field on which an injection is to be performed. Injection allows you to, Enable shorthand mock and spy injections.
@Spy and @InjectMocks cannot be used well together (see Google Code issue #489 and GitHub issue #169), and for what they do it is not clear or common that they should be used together at all. In well-written Mockito usage, you generally should not even want to apply them to the same object.
There is no public API in Mockito for mock injection. Plus as this annotation is mostly driven on the way things are laid out in a test, it is fairly related to the initialization phase of the test.
Though it might change at some point in the future.
However Mockito annotated fields can be initialized either by the MockitoJUnitRunner
or by MockitoAnnotations.initMocks()
. They both create mock instances and perform injection.
Also I see in your code that you are using @Autowired
- hence spring stuff, probably configured via XML. @InjectMocks
wasn't really developed to work with other dependency injection frameworks, as the development was driven by unit test use cases, not integration tests.
You might want to take a look at springockito, which is another project that tries to ease Mockito mock creation in Spring.
Hope that helps
Why using Autowired
in your junit test? Since you are mocking the dependencies for MyType2
you 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 MyType2
that 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 write myType2 = new MyType2Impl(mock(myType1.class))
but it will really makes your tests simpler, and faster (because no application context to build).
E.g.:
@Before
public void setup() {
myType1 = mock(MyType1.class);
myType2 = new MyType2Impl(myType1);
}
But if you really want to use IoC in your junit tests, use springockito has suggested by Brice, and build your mock MyType1
in your application context.
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