Eri*_* B. 4 java generics jmockit hamcrest mockito
这篇2013 年关于 SO 的帖子询问了如何使用 Hamcrest 匹配器来验证 Mockito 中的列表/集合调用。公认的解决方案是将 Matcher 转换为 (Collection)。
我正在尝试做类似的事情,但遇到了类转换错误。我不确定我是否误用了 Hamcrest 匹配器,或者 Mockito 是否根本不支持这种用法。就我而言,我试图使用匹配器列表作为我的参数:
static class Collaborator
{
void doSomething(Iterable<String> values) {}
}
@Test
public void usingMockito()
{
Collaborator mock = Mockito.mock(Collaborator.class);
mock.doSomething(Arrays.asList("a", "b"));
// legal cast
Mockito.verify(mock).doSomething((Collection<String>)argThat(Matchers.contains("a", "b")));
// legal cast
Mockito.verify(mock).doSomething((Collection<String>)argThat(Matchers.contains(Matchers.equalTo("a"), Matchers.equalTo("b"))));
// illegal cast!!! Cannot cast from Iterable<capture#3-of ? extends List<Matcher<String>>> to Collection<String>
Mockito.verify(mock).doSomething((Collection<String>)argThat(Matchers.contains(Arrays.asList(Matchers.equalTo("a"), Matchers.equalTo("b")))));
}
Run Code Online (Sandbox Code Playgroud)
但我得到了演员错误:
Cannot cast from Iterable<capture#3-of ? extends List<Matcher<String>>> to Collection<String>
Run Code Online (Sandbox Code Playgroud)
我在做一些不受支持的事情吗?
我更喜欢使用 allOf
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
...
Mockito.verify(mock).doSomething(
argThat(
allOf(
hasItems(equalTo("a")),
hasItems(equalTo("b"))
)
)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11299 次 |
| 最近记录: |