سؤال

I am stuck trying to verify an argument of a listener implementation.

The method from the Listener interface:

public void settingsAdded(List<EditJobSettings> addedSettings);

What I want to do is check if the expected objects are present in the list.

The test (left out irrelevant code):

@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));
}

Thanks in advance.

هل كانت مفيدة؟

المحلول

Your cast is failing because you're casting an ArgumentCaptor<stuff> to a List<stuff>.

If you are already calling MockitoAnnotations.initMocks(this), you can just declare a field as a @Captor, which is the easiest way to reduce the repetition:

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]
  }
}

Otherwise, you're going to have to cast something approximating this (which I will test when I can):

// Might not work without the cast to (ArgumentCaptor) and some @SuppressWarnings.
ArgumentCaptor<List<EditJobSettingsSet>> argument = 
    (ArgumentCaptor<List<EditJobSettingsSet>>)
    ((ArgumentCaptor) ArgumentCaptor.forClass(List.class));

نصائح أخرى

ArgumentCaptor<List<EditJobSettingsSet>> argument = 
    (List<EditJobSettingsSet>) ArgumentCaptor.forClass(List.class);

You're trying to initialize a variable of type ArgumentCaptor<List<EditJobSettingsSet>> with a List<EditJobSettingsSet>, and to cast the result of ArgumentCaptor.forClass(List.class) (which is of type ArgumentCaptor) to a List. That doesn't make sense. What you want is

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(mEditJobListener).settingsAdded((List<EditJobSettingsSet>) argument.capture());
List<EditJobSettingsSet> value = argument.getValue();
assertTrue(value.contains(mColorSettings));

I'm not sure there is a way to avoid using a ArgumentCaptor<List<EditJobSettingsSet>> here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top