22. 测试流
本章介绍如何测试流。
22.1. 扩展AbstractXmlFlowExecutionTests
要测试基于 XML 的流定义的执行情况,必须扩展 ,如下所示:AbstractXmlFlowExecutionTests
public class BookingFlowExecutionTests extends AbstractXmlFlowExecutionTests {
}
22.2. 指定要测试的流的路径
至少,您必须覆盖以返回要测试的流的路径,如下所示:getResource(FlowDefinitionResourceFactory)
@Override
protected FlowDefinitionResource getResource(FlowDefinitionResourceFactory resourceFactory) {
return resourceFactory.createFileResource("src/main/webapp/WEB-INF/hotels/booking/booking.xml");
}
22.3. 注册 Flow 依赖项
如果您的流程依赖于外部托管服务,则还必须覆盖以注册这些服务的存根或模拟,如下所示:configureFlowBuilderContext(MockFlowBuilderContext)
@Override
protected void configureFlowBuilderContext(MockFlowBuilderContext builderContext) {
builderContext.registerBean("bookingService", new StubBookingService());
}
如果您的流从另一个流扩展或具有扩展其他状态的状态,则还必须覆盖以返回父流的路径,如下所示:getModelResources(FlowDefinitionResourceFactory)
@Override
protected FlowDefinitionResource[] getModelResources(FlowDefinitionResourceFactory resourceFactory) {
return new FlowDefinitionResource[] {
resourceFactory.createFileResource("src/main/webapp/WEB-INF/common/common.xml")
};
}
22.4. 测试 Flow 启动
以下示例显示了如何让您的第一个测试在启动流时执行操作:
public void testStartBookingFlow() {
Booking booking = createTestBooking();
MutableAttributeMap input = new LocalAttributeMap();
input.put("hotelId", "1");
MockExternalContext context = new MockExternalContext();
context.setCurrentUser("keith");
startFlow(input, context);
assertCurrentStateEquals("enterBookingDetails");
assertTrue(getRequiredFlowAttribute("booking") instanceof Booking);
}
断言通常会验证流是否处于您期望的状态。
22.5. 测试 Flow 事件处理
您可以定义其他测试来执行流事件处理行为。
您的目标应该是练习 Flow 中的所有路径。
您可以使用便捷的方法跳转到要开始测试的流状态,如下所示:setCurrentState(String)
public void testEnterBookingDetails_Proceed() {
setCurrentState("enterBookingDetails");
getFlowScope().put("booking", createTestBooking());
MockExternalContext context = new MockExternalContext();
context.setEventId("proceed");
resumeFlow(context);
assertCurrentStateEquals("reviewBooking");
}
22.6. 模拟子流
要测试对子流的调用,您可以注册子流的模拟实现,该实现断言输入已正确传入并返回测试场景的正确结果,如下所示:
public void testBookHotel() {
setCurrentState("reviewHotel");
Hotel hotel = new Hotel();
hotel.setId(1L);
hotel.setName("Jameson Inn");
getFlowScope().put("hotel", hotel);
getFlowDefinitionRegistry().registerFlowDefinition(createMockBookingSubflow());
MockExternalContext context = new MockExternalContext();
context.setEventId("book");
resumeFlow(context);
// verify flow ends on 'bookingConfirmed'
assertFlowExecutionEnded();
assertFlowExecutionOutcomeEquals("finish");
}
public Flow createMockBookingSubflow() {
Flow mockBookingFlow = new Flow("booking");
mockBookingFlow.setInputMapper(new Mapper() {
public MappingResults map(Object source, Object target) {
// assert that 1L was passed in as input
assertEquals(1L, ((AttributeMap) source).get("hotelId"));
return null;
}
});
// immediately return the bookingConfirmed outcome so the caller can respond
new EndState(mockBookingFlow, "bookingConfirmed");
return mockBookingFlow;
}