You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring环境下Axon集成测试配置及无聚合ID事件校验问题

解决方法

方案1:直接读取InMemory存储引擎的全量事件

你当前使用的InMemoryEventStorageEngine本身提供了读取所有存储事件的接口,只需修改配置暴露该Bean即可:

  1. 修改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();
    }
}
  1. 在测试类中注入存储引擎,新增全量事件校验方法:
@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);
}
  1. 调整全流程测试逻辑,直接校验所有事件:
@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:全局事件采集器(更通用)

如果不想依赖存储引擎实现,可注册一个测试专用的全局事件监听器采集所有派发的事件:

  1. 新增测试事件采集类:
@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();
    }
}
  1. 测试类中注入采集器使用即可:
@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:33:02