AspectJ 和模仿对象的测试灵活性:用“test-only”行为增强单元测试
2010-03-18 00:00:00 来源:WEB开发网 public interface Deletable {
void delete();
}
public class Deleter {
public static void delete(Collection deletables){
for(Iterator it = deletables.iterator(); it.hasNext();){
((Deletable)it.next()).delete();
}
}
}
简单的单元测试就可能创建一个真正的 Deletable ,然后验证它在调用 Deleter.delete() 后将消失。然而,为了使用模仿对象测试 Deleter 类,我们编写了一个实现 Deletable 的模仿对象,如清单 5 所示:
清单 5. 一个模仿对象测试
public class MockDeletable implements Deletable{
private boolean deleteCalled;
public void delete(){
deleteCalled = true;
}
public void verify(){
if(!deleteCalled){
throw new Error("Delete was not called.");
}
}
}
下面,我们将在 Deleter 的单元测试中使用模仿对象,如清单 6 所示:
清单 6. 一个使用模仿对象的测试方法
public void testDelete() {
MockDeletable mock1 = new MockDeletable();
MockDeletable mock2 = new MockDeletable();
ArrayList mocks = new ArrayList();
mocks.add(mock1);
mocks.add(mock2);
Deleter.delete(mocks);
mock1.verify();
mock2.verify();
}
更多精彩
赞助商链接