mercredi 6 janvier 2016

How to inject mocked object into another already mocked object

I have a class that I mocked like this:

@Mock
private MyClass1 mockMyClass1;

Say this class looks like that:

public class MyClass1 {
  @Autowired
  private MyInnerClass myInnerClass;
}

When I mock MyClass1, MyInnerClass will be initialized as null. Is it possible to initialize that private field with another mock objected? I want myInnerClass to be a mock like this one:

@Mock
private MyInnerClass myInnerClass;

If I use the following code:

@InjectMocks
private MyClass1 mockMyClass1;
@Mock
private MyInnerClass myInnerClass

This will initialize the private MyInnerClass inside MyClass1 to be the mocked object, however this way mockMyClass1 is not a mock itself any more, isn't it (I'm only injecting a mocked object inside a real class, just like @Autowired will inject a real object insite it)? Could you correct my logic if I'm wrong in my understanding of @InjectMock and @Mock? Also how could I inject a mocked object inside another mocked object (without using setters/constructors)?

Aucun commentaire:

Enregistrer un commentaire