Java 轴突测试:缺少上下文
在Axon SpringBoot应用程序中,我有一个聚合,它在一些命令处理程序中使用注入的DAO 例如:Java 轴突测试:缺少上下文,java,testing,spring-boot,axon,Java,Testing,Spring Boot,Axon,在Axon SpringBoot应用程序中,我有一个聚合,它在一些命令处理程序中使用注入的DAO 例如: @Aggregate class MyAggregate { @CommandHandler public MyAggregate (CreateMyAggregateCommand command, @Autowired MyAggregateDao dao) { final SomeProperty = command.getSomePoprter
@Aggregate
class MyAggregate {
@CommandHandler
public MyAggregate (CreateMyAggregateCommand command, @Autowired MyAggregateDao dao) {
final SomeProperty = command.getSomePoprtery();
if (dao.findBySomeProperty(someProperty) == null) {
AggregateLifeCycle.apply(
new MyAggregateCreatedEvent(command.getIdentifier(),
someProperty);
} else {
// Don't create, already exits with some property
// report ...
}
}
}
一个标准的测试,比如
@Test
void creationSucceeds () {
aggregateTestFixture = new AggregateTestFixture<>(MyAggregate.class);
final CreateMyAggregateCommand command = new CreateMyAggregateCommand(...);
final MyAggregateCreatedEvent = new MyAggregateCreatedEvent(...);
aggregateTestFixture
.givenNoPriorActivity()
.when(command)
.expectEvents(event);
}
如何提供测试实现?解决方案1:模拟
因为这是关于单元测试的,我的问题涉及数据库调用(外部服务),所以只要测试只是关于孤立的聚合行为,模拟就似乎是适用的
@Test
void creationSucceeds () {
aggregateTestFixture = new AggregateTestFixture<>(MyAggregate.class);
aggregateTestFixture.registerInjectableResource(
Mockito.mock(MyAggregateDao.class));
}
@EnableAutoConfiguration
public class SpringTestConfig {
// Set up whatever you need
@Bean
@Autowired
MyAggregateDao myDao (DataSource dataSource) {
// ...
}
@Bean
@Autowired
EventStorageEngine eventStorageEngine () {
return new InMemoryEventStorageEngine();
}
}
AggregateTestFixture
private AggregateTestFixture<MyAggregate> aggregateTestFixture;
@Autowired
private MyAggregateDao myDao;
@BeforeEach
void beforeEach () {
aggregateTestFixture = new AggregateTestFixture<>(MyAggregate.class);
// We still need to register resources manually
aggregateTestFixture.registerInjectableResource(myDao);
}
private AggregateTestFixture AggregateTestFixture;
@自动连线
私用myDao myDao;
@之前
在每个()之前无效{
aggregateTestFixture=新的aggregateTestFixture(MyAggregate.class);
//我们仍然需要手动注册资源
aggregateTestFixture.registerInjectableResource(myDao);
}
@EnableAutoConfiguration
public class SpringTestConfig {
// Set up whatever you need
@Bean
@Autowired
MyAggregateDao myDao (DataSource dataSource) {
// ...
}
@Bean
@Autowired
EventStorageEngine eventStorageEngine () {
return new InMemoryEventStorageEngine();
}
}
private AggregateTestFixture<MyAggregate> aggregateTestFixture;
@Autowired
private MyAggregateDao myDao;
@BeforeEach
void beforeEach () {
aggregateTestFixture = new AggregateTestFixture<>(MyAggregate.class);
// We still need to register resources manually
aggregateTestFixture.registerInjectableResource(myDao);
}