Axon 框架:聚合自动装配 Bean 在测试中抛出 NullPointerException

Axon Framework: Aggregate Autowired Bean throws NullPointerException in Test

Springboot 和 Axon:基本上,我正在对使用三个不同 ObjectMapper 实例的聚合进行单元测试,每个实例都具有不同的配置。这些在配置中定义 class :

    @Configuration
    public class JacksonConfiguration {

    @Bean(name="flatMapper")
    @Primary
    public ObjectMapper flatMapper(){
        return new ObjectMapper();
    }

    @Bean(name="unknownPropertiesMapper")
    public ObjectMapper unknownPropertiesMapper(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    @Bean(name="nullPropertiesMapper")
    public ObjectMapper nullPropertiesMapper(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }

}

它们在我的聚合中的注入和使用如下:

@Aggregate
@Data
@Component
public class MyAggregate {

    @Autowired
    @Qualifier("flatMapper")
    private ObjectMapper flatMapper;

    @Autowired
    @Qualifier("unknownPropertiesMapper")
    private ObjectMapper unknownPropertiesMapper;

    @Autowired
    @Qualifier("nullPropertiesMapper")
    private ObjectMapper nullPropertiesMapper;


    @AggregateIdentifier
    private String id;

  //Methods and Handlers: a method is using "unknownPropertiesMapper" is "changedKeySet" 

当我 运行 SpringBootApplication 一切都正确实例化并按预期工作时,但是在测试时我在他们的实例上得到 NullPointerException:

@ContextConfiguration(classes = JacksonConfiguration.class)
@SpringBootTest(classes = OccurrenceAggregate.class)
@ComponentScan(basePackageClasses = MyAggregate.class)
public class AggregateTest {
    
    private FixtureConfiguration<MyAggregate> fixture;

    @BeforeEach
    public void setUp() {
        fixture = new AggregateTestFixture<>(MyAggregate.class);
    }

    @Test
    public void myTest() {

       fixture.givenNoPriorActivity().... 

    }

测试控制台:

org.axonframework.test.AxonAssertionError: The command handler threw an unexpected exception

Expected <ANYTHING> but got <exception of type [NullPointerException]>. Stack trace follows:
java.lang.NullPointerException
    at com.example.business.aggregates.MyAggregate.changedKeySet(MyAggregate.java:185)

changedKeySet() 正在抛出 NPE,因为它使用 unknownPropertiesMapper 并且它的值为 null。 正如我提到的,当我 运行 Main class 但在测试(Junit5)中没有时它工作正常。

聚合设置不正确。将 Spring Bean 注入聚合的正确方法是将其添加到 CommandHandler 方法中。

@CommandHandler
    public void handle(ACommand cmd, ObjectMapper flatMapper) {

在测试夹具中你可以这样注入它:

fixture.registerInjectableResource(flatMapper);