gpt4 book ai didi

axon - 有没有一种方法可以不使用 expectEvents 直接从测试夹具测试事件?

转载 作者:行者123 更新时间:2023-12-02 02:33:23 32 4
gpt4 key购买 nike

我正在尝试测试聚合并想断言夹具之外的事件,甚至可能使用 Hamcrest 进行评估?

使用时间戳的例子

        fixture.given()
.when(new UserCreateCommand("1","test@bob.com"))
.expectEvents(new UserCreatedEvent("1","test@bob.com");

夹具让我可以轻松地测试相等性,例如该命令准确地产生了这个事件,如果我想说引入一个事件创建时间的时间戳,这并不容易

        fixture.given()
.when(new UserCreateCommand("1","test@bob.com"))
.expectEvents(new UserCreatedEvent("1","test@bob.com", LocalDateTime.now());

这种期望永远不会起作用,因为 LocalDateTime.now() 永远不会精确等于聚合中生成的时间戳。

我可以简单地将时间戳包含在命令有效负载中,但我更喜欢在聚合内部处理以确保以一致的方式生成此时间戳。

有没有办法从夹具中检索事件以独立于夹具进行断言,例如

   UserCreatedEvent uce = fixture.given()
.when(new UserCreateCommand("1","test@bob.com"))
.extractEvent(UserCreatedEvent.class)

这将允许我使用其他断言库,例如 hamcrest:

例如

   assertThat(uce.getCreatedAt(), is(greaterThanOrEqualto(LocalDateTime.now().minusSeconds(1);

最佳答案

合理的问题@vcetinick!

您实际上应该能够将匹配器与 Axon 的聚合测试装置结合使用。 AggregateTestFixture 的结果验证部分提供 expectEventsMatching(Matcher<? extends List<? super EventMessage<?>>> matcher)方法。您可以找到此 here 的代码顺便说一下。

在此 Axon 框架之上提供了一组合理的匹配器,您可以将其用于一般的消息,分组在实用程序类 Matchers 下。 (你可以找到 here )。

有了这一切,你应该能够做这样的事情:

@Test
void sampleTest() {
FixtureConfiguration<SampleAggregate> fixture =
new AggregateTestFixture<>(SampleAggregate.class);
fixture.givenNoPriorActivity()
.when(new UserCreateCommand("1","test@bob.com"))
.expectEventsMatching(
Matchers.exactSequenceOf(
Matchers.messageWithPayload(
Matchers.matches(payload -> {
// Your UserCreatedEvent validation
// disregarding the time stamp here
})
)
)
);
}

您基本上可以配对任意数量的 Matchers如果您愿意,可以使用它们中的方法。

希望这能回答您@vcetinick 的问题!

关于axon - 有没有一种方法可以不使用 expectEvents 直接从测试夹具测试事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64715974/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com