So I understand that in Mockito @InjectMocks will inject anything that it can with the annotation of @Mock, but how to handle this scenario?
@Mock private MockObject1 mockObject1; @Mock private MockObject2 mockObject2; @InjectMocks private SystemUnderTest systemUnderTest = new SystemUnderTest();
Imagine that MockObject2 has an attribute that is of type MockObject1, and SystemUnderTest has an attribute of type MockObject2. I would like to have mockObject1 injected into mockObject2, and mockObject2 injected into systemUnderTest.
Is this possible with annotations?
@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.
Your test class should be: @RunWith(SpringRunner. class) class ServiceLayerTest{ @Mock(name = "typeA") private InterfaceA typeA; @Mock(name = "typeB") private InterfaceA typeB; @InjectMocks ServiceLayer serviceLayer; @Before public void initialiseBeforeTest(){ MockitoAnnotations.
A mock doesn't have any real implementation. @InjectMocks would try to find and call setters for whatever mock objects have already been created and pass them in.
Using the @Mock annotation – allows shorthand creation of objects required for testing. minimizes repetitive mock creation code. makes the test class more readable. makes the verification error easier to read because field name is used to identify the mock.
Since I didn't get any response here I asked on the Mockito forums. Here is a link to the discussion: https://groups.google.com/d/topic/mockito/hWwcI5UHFi0/discussion
To summarize the answers, technically this would kind of defeat the purpose of mocking. You should really only mock the objects needed by the SystemUnderTest class. Mocking things within objects that are themselves mocks is kind of pointless.
If you really wanted to do it, @spy can help
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