我很难尝试验证侦听器实现的参数。
来自Listener
界面的方法:
public void settingsAdded(List<EditJobSettings> addedSettings);
我想要做的是检查列表中是否存在预期的对象。
测试(遗漏了不相关的代码):
@Test
public void initiallyAddColorAndAlignTile() {
mSettings.add(mColorSetting);
// This method calls the listener method and passes the added settings as argument
mStatusNotifier.notifySettingsUpdates(mSettings);
// Here I get stuck: this does not compile, but I can't find how to work around this. Is there a way to specify a generic list as argument?
ArgumentCaptor<List<EditJobSettingsSet>> argument = (List<EditJobSettingsSet>) ArgumentCaptor.forClass(List.class);
verify(mEditJobListener).settingsAdded(argument.capture());
assertTrue(argument.getValue().contains(mColorSettings));
}
提前致谢。
答案 0 :(得分:3)
您的演员阵容失败了,因为您正在向ArgumentCaptor<stuff>
投射List<stuff>
。
如果您已经在调用MockitoAnnotations.initMocks(this)
,则可以将字段声明为@Captor
,这是减少重复的最简单方法:
public class YourTest {
@Mock SomeClass someMock;
@Captor ArgumentCaptor<List<EditJobSettingsSet>> argument;
@Before public void initializeMocks() {
// This gets called automatically if you @RunWith(MockitoJUnitRunner.class).
MockitoAnnotations.initMocks(this);
}
@Test public void yourTest() {
// [insert setup here]
verify(mEditJobListener).settingsAdded(argument.capture());
// [insert assertions here]
}
}
否则,你将不得不投射一些近似这个(我会尽可能测试):
// Might not work without the cast to (ArgumentCaptor) and some @SuppressWarnings.
ArgumentCaptor<List<EditJobSettingsSet>> argument =
(ArgumentCaptor<List<EditJobSettingsSet>>)
((ArgumentCaptor) ArgumentCaptor.forClass(List.class));
答案 1 :(得分:2)
ArgumentCaptor<List<EditJobSettingsSet>> argument =
(List<EditJobSettingsSet>) ArgumentCaptor.forClass(List.class);
您尝试使用ArgumentCaptor<List<EditJobSettingsSet>>
初始化List<EditJobSettingsSet>
类型的变量,并将ArgumentCaptor.forClass(List.class)
(ArgumentCaptor类型)的结果强制转换为List。这没有意义。你想要的是
ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(mEditJobListener).settingsAdded((List<EditJobSettingsSet>) argument.capture());
List<EditJobSettingsSet> value = argument.getValue();
assertTrue(value.contains(mColorSettings));
我不确定是否有办法避免在这里使用ArgumentCaptor<List<EditJobSettingsSet>>
。