单元测试 - 模拟域对象
优质
小牛编辑
130浏览
2023-12-01
遇到了另一个常见的问题,同时为Spring Batch编写单元测试和集成测试组件是如何模拟域对象。一个很好的例子是StepExecutionListener,如下所示:
public class NoWorkFoundStepExecutionListener extends StepExecutionListenerSupport {
public ExitStatus afterStep(StepExecution stepExecution) {
if (stepExecution.getReadCount() == 0) {
throw new NoWorkFoundException("Step has not processed any items");
}
return stepExecution.getExitStatus();
}
}
上面的监听是框架提供的,并且它检测到stepExecution的read count是为空的,因此它表示没有工作要做。虽然这个例子相当简单,当试图单元测试类的时候它解释了可能遇到的问题类型,实现接口验证Spring Batch 域对象。考虑到上面的侦听器的单元测试:
private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener();
@Test
public void testAfterStep() {
StepExecution stepExecution = new StepExecution("NoProcessingStep",
new JobExecution(new JobInstance(1L, new JobParameters(),
"NoProcessingJob")));
stepExecution.setReadCount(0);
try {
tested.afterStep(stepExecution);
fail();
} catch (NoWorkFoundException e) {
assertEquals("Step has not processed any items", e.getMessage());
}
}
因为Spring Batch域模型遵循良好的面向对象原则,StepExecution需要一个JobExecution,JobExecution需要一个JobInstance和JobParameters为了创建一个有效的StepExecution。虽然这是很好的可靠的域模型,为了冗长的单元测试创建存根对象。为了解决这个问题,Spring Batch测试模块引入一个工厂来创建域对象:MetaDataInstanceFactory,把这个给到工厂,更新后的单元测试可以更简洁:
private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener();
@Test
public void testAfterStep() {
StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution();
stepExecution.setReadCount(0);
try {
tested.afterStep(stepExecution);
fail();
} catch (NoWorkFoundException e) {
assertEquals("Step has not processed any items", e.getMessage());
}
}
上面的方法为了创建一个简单的StepExecution,它仅仅是便利的方法中可用的工厂。完整的方法清单可以在Javadoc找到