Springboot and Axon: Basically I am unit testing an aggregate that uses three different ObjectMapper instances, each with a different configuration. These are defined in config 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;
}
}
They are injected and used in my aggregate as follow:
@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"
when I run SpringBootApplication everything is properly instanciated and working as expected, but when testing I get NullPointerException over thier instances:
@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()....
}
test console:
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()
is throwing NPE because its using unknownPropertiesMapper
and it is value is null.
as I mentionned it works fine when I run the Main class but not in tests (Junit5).
The Aggregate is not set up correctly. The correct way to inject a Spring Bean into the Aggregate is to add it to the CommandHandler method.
@CommandHandler
public void handle(ACommand cmd, ObjectMapper flatMapper) {
In the test fixture you can inject it this way:
fixture.registerInjectableResource(flatMapper);