我在我們的產品中使用 Akka actor。我們寫了一些代碼: @Singleton public class SingletonObj { private Map<String, Integer> cached = new HashMap(); public void set(String key, Integer value) { cached.put(key, value); } public void delete(String key){ cached.delete(key} } } public class MyActor extends AbstractActor implements InjectedActorSupport { @Inject SingletonObj singletonObj; public static Props props(Injector injector) { return Props.create(MyActor.class, injector); } public MyActor(Injector injector) { this.injector = injector; receive(ReceiveBuilder.create() .match(AddEvent.class, this::addEvent) .match(DeteteEvent.class, this::deleteEvent)) .build()); } private void addEvent(AddEvent addEvent) {singletonObj.set(addEvent.key, addEvent.value);} private void deteleEvent(DeteteEvent event){singletonObj.detele(event.key);} } public class Controller { private Injector injector; private ActorSystem actorSystem; public void handleAdd()... public void handleDelete()... }然后當我junit為這些課程寫一些測試時 @Test public void testMethod(){ sendAddRequest(...); sendDeteleRequest(...) ... ... assertThat(singletonObj.get("someString")).isEqual(42) }那么這個測試是不可靠的,因為當我斷言時,所有事件都沒有被處理。我如何等待 actor 系統中的所有事件完成?
1 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
導入下面的包,然后你可以等待直到你處理完所有事件,否則測試將在超時后失敗。
testCompile 'org.awaitility:awaitility:3.1.0'
import org.awaitility.Awaitility;
在你使用 assertThat 之前
await().pollInterval(5, TimeUnit.MILLISECONDS).until(() -> !isProcessed());
isProcessed 方法如下所示
protected Callable<Boolean> isProcessed() {
return () -> {
return singletonObj.getCacheCount()==2;
};
}
添加回答
舉報
0/150
提交
取消