我要实现以下目标:
Class A{
List<Class B> list;
}
Class B{
}
@Mock
A a;
when(a.list.isEmpty()).then(true); // this throws an error
通过使用这个:
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
A a;
我必须使用吸气剂:
when(a.getList().isEmpty()).then(true);
但是我不想更改我的代码以在任何地方使用吸气剂。
最佳答案
您不能模拟直接访问成员变量。因此,您有几种选择:
使用吸气剂。
将成员变量设置为模拟实例(a.list = mock(...)
或等效对象)。
对于像列表这样的琐碎类,使用模拟具有边际价值,因为您可以或多或少地直接设置所需的行为。因此,在这种情况下,a.list = new ArrayList<>();
就足够了。