我不确定如何使用easymock设置此类行为。为了说明我创建了一个简化的例子。 基本上,我有一个返回void的方法,并采取一个地图,我想easymock更改地图,删除我指定的条目。
假设我有以下界面:
public interface Filter{
public void filter(Map<String,String>map);
}
以及以下课程:
public class MyClass {
private Filter filter;
public MyClass(Filter filter) {
this.filter = filter;
}
public Map<String,String> process(Map<String,String>map) {
filter.filter(map);
return map;
}
}
我无法弄清楚如何设置此行为:
public class MyClassTest {
/**
* Test method for {@link easy.MyClass#process(java.util.Map)}.
*/
@Test
public void testProcess() {
Map<String, String> map = new HashMap<String, String>();
map.put("one","AAA");
map.put("remove","BBB");
map.put("three","CCC");
Map<String, String> expectedRet = new HashMap<String, String>();
expectedRet.put("one","AAA");
expectedRet.put("three","CCC");
IMocksControl mockery = EasyMock.createControl();
mockery.resetToStrict();
mockery.checkOrder(true);
Filter mockFilter = mockery.createMock("filter", Filter.class);
MyClass m = new MyClass(mockFilter);
mockFilter.filter(map);
// I would like some behaviour that will remove the entry ("remove","BBB")
// how can I define that?
mockery.replay();
m.process(map);
mockery.verify();
assertEquals(expectedRet,map);
}
}
答案 0 :(得分:0)
您应该设置m.process(map)
在模拟过滤器上调用filter(map)
的期望:
Filter mockFilter = mockery.createMock("filter", Filter.class);
// set expectation
mockFilter.filter(map);
replay(mockFilter);
MyClass m = new MyClass(mockFilter);
m.process(map);
// verify expectation
verify(mockFilter);
您在上面的代码摘录中采用的路径是尝试验证您的模拟过滤器。这不应该是你的考试目标。在您的情况下,受测试的课程为MyClass
,而不是Filter
。
更新:您可以向模拟添加行为:
expect(mockFilter.filter(map)).andDelegateTo(new Filter {
@Override
void filter(Map<String, String> map) {
map.remove("remove");
}
});
但是,在您的特定情况下,Filter
界面非常简单,导致andDelegateTo
首先使用模拟Filter
。使用相同数量的代码,您可以在测试中使用具体的Filter
实例:
class TestFilter implements Filter {
@Override
void filter(Map<String, String> map) {
map.remove("remove");
}
}
MyClass m = new MyClass(new TestFilter());
m.process(map);
assertNull(map.get("remove"));