简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM