Spring环境下Axon集成测试配置及无聚合ID事件校验问题
解决方法
方案1:直接读取InMemory存储引擎的全量事件
你当前使用的InMemoryEventStorageEngine本身提供了读取所有存储事件的接口,只需修改配置暴露该Bean即可:
- 修改
IntegrationTestConfig配置类,将存储引擎单独注册为可注入的Bean:
@TestConfiguration public class IntegrationTestConfig { @Bean public InMemoryEventStorageEngine inMemoryEventStorageEngine() { return new InMemoryEventStorageEngine(); } @Bean @Primary public EventBus createSpyEventBus(InMemoryEventStorageEngine storageEngine) { return new EmbeddedEventStore.Builder().storageEngine(storageEngine).build(); } }
- 在测试类中注入存储引擎,新增全量事件校验方法:
@Autowired private InMemoryEventStorageEngine storageEngine; private void thenAllExpectedEventsRecorded(List<Class<?>> expectedEventTypes) { List<Class<?>> actualEventTypes = StreamSupport.stream( storageEngine.readAllEvents().spliterator(), false ) .map(eventMessage -> eventMessage.getPayloadType()) .toList(); Assert.assertEquals(expectedEventTypes, actualEventTypes); }
- 调整全流程测试逻辑,直接校验所有事件:
@Test public void itShouldStoreCorrectEvents() { var aggregateId = UUID.randomUUID().toString(); var exampleCommand = new ExampleCommand(aggregateId); whenCommandIsDispatched(exampleCommand); // 校验全链路所有事件 thenAllExpectedEventsRecorded(Arrays.asList( Event1.class, Event2.class, Event3.class )); }
方案2:全局事件采集器(更通用)
如果不想依赖存储引擎实现,可注册一个测试专用的全局事件监听器采集所有派发的事件:
- 新增测试事件采集类:
@Component @Profile("test") public class TestEventCollector { private final List<Object> collectedEvents = Collections.synchronizedList(new ArrayList<>()); // 监听所有类型的事件 @EventHandler public void collectAllEvents(Object eventPayload) { collectedEvents.add(eventPayload); } public List<Class<?>> getCollectedEventTypes() { return collectedEvents.stream() .map(Object::getClass) .toList(); } // 每次测试前调用清空,避免数据交叉污染 public void clear() { collectedEvents.clear(); } }
- 测试类中注入采集器使用即可:
@Autowired private TestEventCollector eventCollector; @Before public void setUp() { eventCollector.clear(); } @Test public void itShouldTriggerEvent2WhenDispatchCommand2() { // 第二个测试目标:验证command2触发event2 commandGateway.sendAndWait(new Command2()); Assert.assertTrue(eventCollector.getCollectedEventTypes().contains(Event2.class)); }
注意事项
如果你的项目配置了异步事件处理器,使用采集器方案时需要添加适当的等待逻辑(比如awaitility工具类),确保异步事件处理完成后再做校验。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

