0
Class A {
    B b;  
    C c;  
}

Class C {
    D d;  
    E e;  
}

I want to write unit test for A but I do not want to mock methods of C. However, I do want to mock D and E in C.

I have tried these options: Option 1:

@Mock B b;  
@Mock D d;  
@Mock E e;  
@Spy @InjectMocks C c;  
@InjectMocks A a;

Option 2:

@Mock B b;  
@Mock D d;  
@Mock E e;   
@Spy C c = Mockito.spy(new C(d,e));  
@InjectMocks A a;

Option 3: suggestions in Mockito Inject mock into Spy object

None of the options are working for me. Will appreciate any help.

  • `new A(new B(), new C(mock(D.class, E.class))` – how do you inject the dependencies into your classes? – knittl Dec 16 '22 at 10:20
  • Currently, I am doing field injection by using InjectMocks – deepak gupta Dec 16 '22 at 17:44
  • Mock injection runs after initialization of the class. When a field is assigned in the field initializer, the mocks don't exist yet. Read up on "pass-by-value vs pass-by-reference" and probably also [Why is my class not calling my mocked methods in unit test?](https://stackoverflow.com/q/74027324/112968), which could be applied here (but not an exact dupe) – knittl Dec 17 '22 at 09:01
  • Does this answer your question? [Why is my class not calling my mocked methods in unit test?](https://stackoverflow.com/questions/74027324/why-is-my-class-not-calling-my-mocked-methods-in-unit-test) (it's a dupe now) – knittl Dec 18 '22 at 20:11

0 Answers0