spring boot + junit + 覆盖的组件实例
spring boot + junit + overriden component instance
我有示例项目 here。我想用 class com.github.bilak.axonframework.poc.command.user.UserTest
设置 som junit 测试
当我 运行 测试时,我可以在日志中看到
Skipping bean definition for [BeanMethod:name=userCommandHandler,declaringClass=com.github.bilak.axonframework.poc.command.config.CommandConfiguration]: a definition for bean 'userCommandHandler' already exists. This top-level bean definition is considered as an override.
然后我可以看到,当 UserRepository 被注入到 UserCommandHandler 时,它是 UserTest class 中使用的另一个实例。为什么要这样做,我该如何避免?
谢谢
这是因为名称为 userCommandHandler 的 bean 在上下文中定义了两次。首先作为注解组件 com.github.bilak.axonframework.poc.command.user.UserCommandHandler
注册组件扫描,其次作为在 CommandConfiguration(第 75 行)中定义的 bean。
And then I can see that when UserRepository is injected to UserCommandHandler that's another instance as that which is used in UserTest class.
查看 GivenWhenThenTestFixture 实现,我可以看到它实际上将传递的实例包装到某个适配器中。此外,因为您传递的实际上是一个 spring 代理,它具有 userRepository 直接引用 null(我相信这是正确的),有效的注册处理程序也将其设置为 null,因此您可能因此遇到空指针异常。如果我为您的测试更改设置:
@Before
public void setup() throws Exception {
fixture = Fixtures.newGivenWhenThenFixture(User.class);
UserCommandHandler target = (UserCommandHandler) ((Advised) userCommandHandler).getTargetSource().getTarget();
fixture.registerAnnotatedCommandHandler(target);
}
有帮助。
我有示例项目 here。我想用 class com.github.bilak.axonframework.poc.command.user.UserTest
设置 som junit 测试
当我 运行 测试时,我可以在日志中看到
Skipping bean definition for [BeanMethod:name=userCommandHandler,declaringClass=com.github.bilak.axonframework.poc.command.config.CommandConfiguration]: a definition for bean 'userCommandHandler' already exists. This top-level bean definition is considered as an override.
然后我可以看到,当 UserRepository 被注入到 UserCommandHandler 时,它是 UserTest class 中使用的另一个实例。为什么要这样做,我该如何避免?
谢谢
这是因为名称为 userCommandHandler 的 bean 在上下文中定义了两次。首先作为注解组件 com.github.bilak.axonframework.poc.command.user.UserCommandHandler
注册组件扫描,其次作为在 CommandConfiguration(第 75 行)中定义的 bean。
And then I can see that when UserRepository is injected to UserCommandHandler that's another instance as that which is used in UserTest class.
查看 GivenWhenThenTestFixture 实现,我可以看到它实际上将传递的实例包装到某个适配器中。此外,因为您传递的实际上是一个 spring 代理,它具有 userRepository 直接引用 null(我相信这是正确的),有效的注册处理程序也将其设置为 null,因此您可能因此遇到空指针异常。如果我为您的测试更改设置:
@Before
public void setup() throws Exception {
fixture = Fixtures.newGivenWhenThenFixture(User.class);
UserCommandHandler target = (UserCommandHandler) ((Advised) userCommandHandler).getTargetSource().getTarget();
fixture.registerAnnotatedCommandHandler(target);
}
有帮助。