这里的答案可能部分取决于 CUT(被测代码)如何使用 List<VO>。例如,如果您的代码是 RESTful 服务,仅充当代理并将此 List<VO> 返回给用户,而不检查内容或任何内容,那么这就足够了:
@Tested CUT cut;
@Injectable DummyDAO dao;
@Injectable List<VO> res;
@Test
public void testSomething() throws Exception {
new Expectations() {{
dao.getSearchCriteria(anyString, anyInt); result = res;
}};
List<VO> output = cut.methodBeingTested();
// assertions go here, like that output and res are the same
// you can also put Verifications here
}
如果您希望对 VOs 进行分析,那么事情可能会变得更加复杂,例如:
@Tested CUT cut;
@Injectable DummyDAO dao;
@Mocked VO vo;
@Test
public void testSomething() throws Exception {
final List<VO> res = new ArrayList<VO>();
Collections.addAll(res, vo, vo, vo, vo);
new Expectations() {{
dao.getSearchCriteria(anyString, anyInt); result = res;
}};
new Expectations(4) {{
vo.getFoo(); returns(5, 47, 13, -7);
}};
cut.methodBeingTested();
// assertions go here, like that you handled the negative number properly
// you can also put Verifications here
}
注意这里我没有模拟List——如果您正在执行更复杂的操作,最好坚持使用真正的List,而不必模拟它的所有操作。我模拟了一个 VO 并将其多次添加到列表中——这没关系,因为每次检查它时它的行为都会有所不同,因此似乎是不同的 VO。
检查,因为它发生了 4 次,所以我搬到了另一个 Expectations 块,因为您预计它会发生 4 次。我这样做只是为了展示期望块,因为在这种情况下,它可以通过在原始块中添加 vo.getFoobar(); times=4; returns(5, 47, 13, -7); 来轻松完成......或者,第二个块可能看起来像
new StrictExpectations(4) {{
vo.getFoo(); returns(5, 47, 13, -7);
vo.getBar(); returns("foo", "bar", "baz", "quux");
}};
在这种情况下,times 字段将不起作用,您必须将它放在单独的块中 - 该块表示它希望 getFoo() 和 getBar() 交替调用,恰好 4 次-- 就像遍历一个列表并每次都查看这两个属性时所做的那样。
我希望我已经让你深思了;在不了解您的具体用例的情况下,我自己无法更具体。