Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple levels of @Mock and @InjectMocks

Tags:

java

mockito

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?

like image 469
Collin Peters Avatar asked Jun 09 '11 23:06

Collin Peters


People also ask

What do @mock and @InjectMocks do?

@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.

How do you inject multiple mocks of the same interface?

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.

Can we use mock and InjectMocks together?

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.

What does @mock annotation mean?

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.


1 Answers

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

like image 172
Collin Peters Avatar answered Sep 16 '22 22:09

Collin Peters