FooService
中有这么一个方法
public void doSomething(){
ArrayList<Foo> fooList = ...;
barService.batchAddFoos(fooList); // 批量插入
List<String> codeList = new ArrayList<>();
for (Foo foo : fooList) {
codeList.add(foo.getCode());
}
String key = "foo_codes";
redisService.sadd(key,codeList.toArray(new String[]{})); // 将生成的code保存到redis中
// ...
}
BarService.batchAddFoos
中会动态为code
属性赋值
for (Foo foo : foos) {
foo.setCode(UUID.randomUUID().toString()); // dynamically generate the code value
}
有一个单元测试测试doSomething
方法
@Test
public void doSomething() throws Exception {
fooService.doSomething();
ArgumentCaptor<List<Foo>> fooListCaptor = ArgumentCaptor.forClass(List.class);
verify(barService).batchAddFoos(fooListCaptor.capture());
List<Foo> fooList = fooListCaptor.getValue();
Assert.assertNotNull(fooList.get(0).getCode()); // 测试code是否有值
List<String> codeList = new ArrayList<>();
for (Foo foo : fooList) {
codeList.add(foo.getCode());
}
verify(redisService).sadd("foo_codes",codeList.toArray(new String[]{}));
}
实际执行失败 因为压根就没执行batchAddFoos
中的方法, 导致code属性值为空。
尝试了在测试方法中显式赋值
fooList.get(0).setCode("aaa");
fooList.get(1).setCode("bbb");
依然测试失败
Argument(s) are different! Wanted:
redisService.sadd("foo_codes", "aaa", "bbb");
Actual invocation has different arguments:
redisService.sadd("foo_codes", null, null);
像这种问题该怎么测试呢?