Java Can';t在@MicronautTest中注入模拟应用程序EventPublisher
我正在我的应用程序中积极使用ApplicationEventPublisher,一些方法执行的主要结果是使用ApplicationEventPublisher发布事件 我在测试环境中使用一个简单的事件陷阱来收集事件并验证它们:Java Can';t在@MicronautTest中注入模拟应用程序EventPublisher,java,unit-testing,mockito,micronaut,Java,Unit Testing,Mockito,Micronaut,我正在我的应用程序中积极使用ApplicationEventPublisher,一些方法执行的主要结果是使用ApplicationEventPublisher发布事件 我在测试环境中使用一个简单的事件陷阱来收集事件并验证它们: @Singleton public class MessageListenerTestHelper { private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
@Singleton
public class MessageListenerTestHelper {
private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
@Async
@EventListener
public void onEvent(Object event) {
queue.add(event);
}
public Queue getQueue() {
return queue;
}
public <T> Future<T> getEventFromQueue(Class<T> eventClass) {
CompletableFuture<T> future = new CompletableFuture<>();
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
Optional eventOpt = queue.stream()
.filter(eventClass::isInstance)
.findAny();
if (eventOpt.isPresent()) {
future.complete((T) eventOpt.get());
}
}, 100, 100, TimeUnit.MILLISECONDS);
return future;
}
}
@Singleton
公共类MessageListenerTestHelper{
私有ConcurrentLinkedQueue=新ConcurrentLinkedQueue();
@异步的
@事件监听器
public void onEvent(对象事件){
添加(事件);
}
公共队列getQueue(){
返回队列;
}
公共未来getEventFromQueue(类eventClass){
CompletableFuture=新的CompletableFuture();
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()->{
可选eventOpt=queue.stream()
.filter(eventClass::isInstance)
.findAny();
if(eventOpt.isPresent()){
future.complete((T)eventOpt.get());
}
},100100,时间单位为毫秒);
回归未来;
}
}
但我的测试是脆弱的——它通常在github操作中失败,但在我的计算机上工作。所以我想通过mockApplicationEventPublisher
来修复它。但是@替换注释不起作用。我在测试中试过了,在工厂中也只有在测试环境中才可用,但这两种方法都不起作用
我将拒绝使用@MicronautTest
注释,并手动注入模拟。但可能还有另一种选择?“但是@Replaces注释不起作用”-不清楚您如何尝试使用@Replaces
。一般来说,它是有效的。我们一直在使用它。如果你能提供更多的上下文,甚至更好的,一个指向一个简单应用程序的链接,演示你正在尝试做什么,这将使它更容易帮助你。