1

我被困在试图验证侦听器实现的参数。

来自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));
}

提前致谢。

4

2 回答 2

3

您的演员表失败了,因为您将 anArgumentCaptor<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));
于 2013-08-02T09:06:22.247 回答
2
ArgumentCaptor<List<EditJobSettingsSet>> argument = 
    (List<EditJobSettingsSet>) ArgumentCaptor.forClass(List.class);

您正在尝试使用 a 初始化类型变量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>>这里使用 a 。

于 2013-08-02T07:25:51.280 回答