我依赖于一个以 Map 作为参数的方法。
public interface Service {
void doSomething(Map<String, String> map);
}
我想写一个断言,用适当的 map 内容调用此依赖项。像这样的事情:
@RunWith(JMock.class)
public class MainTest {
private Mockery context = new Mockery();
private Service service = context.mock(Service.class);
private Main main = new Main(service);
@Test
public void test() {
context.checking(new Expectations(){{
oneOf(service).doSomething(with(hasEntry("test", "test")));
}});
main.run();
}
}
不幸的是,这无法编译,因为 hasEntry 在 map 泛型参数中具有通配符:
public static <K, V> org.hamcrest.Matcher<java.util.Map<? extends K, ? extends V>> hasEntry(K key, V value);
有没有办法为 map 内容编写 JMock 期望?
最佳答案
这个问题没有一个好的答案,因为我们已经达到了 Java 泛型的极限。 jMock 所需的泛型与assertThat() 所需的泛型之间存在紧张关系
我倾向于添加一个具有表达性名称的辅助方法来强制类型。
@Test public void test() {
context.checking(new Expectations(){{
oneOf(service).doSomething(with(mapIncluding("test", "test")));
}});
main.run();
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Matcher<Map<String, String>> mapIncluding(String key, String value) {
return (Matcher)Matchers.hasEntry(key, value);
};
是的,这太丑了。我只能道歉,这是我们能做的最好的事情。也就是说,我很少需要关闭类型,我可以给它一个在域中有意义的名称,并且我已将取消检查本地化到辅助方法。
关于dictionary - JMock map 期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10704443/