vinzzz
vinzzz

Reputation: 2104

Mocking deep objects in Mockito

I want to achieve the following :

Class A{
List<Class B> list;
}

Class B{
}

@Mock
A a;
when(a.list.isEmpty()).then(true); // this throws an error

By using this :

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
A a;

I have to use a getter :

when(a.getList().isEmpty()).then(true);

But I don't want to change my code to use getters everywhere..

Upvotes: 0

Views: 1772

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

You cannot mock direct access to a member variable. So you have a few options:

  1. Use a getter.

  2. Set the member variable to be a mock instance (a.list = mock(...) or equivalent).

  3. In the case of a trivial class like a list, there's marginal value to using a mock as you can more or less directly set up the behaviour you want. So in this case, a.list = new ArrayList<>(); would suffice.

Upvotes: 2

Related Questions