如何在单元测试中等待actor处理所有消息?

时间:2019-06-06 13:33:09

标签: java playframework akka

我在我们的产品中使用Akka演员。我们写了一些代码:

   @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)
    }

然后该测试不可靠,因为当我进行断言时,尚未处理所有事件。

我该如何等待演员系统中所有事件的使用?

1 个答案:

答案 0 :(得分:0)

导入以下软件包,然后您可以等待直到处理所有事件,否则超时后测试将失败。

testCompile 'org.awaitility:awaitility:3.1.0'

import org.awaitility.Awaitility;

在您使用assert之前

await().pollInterval(5, TimeUnit.MILLISECONDS).until(() -> !isProcessed());

isProcessed方法将如下所示

protected Callable<Boolean> isProcessed() {
        return () -> {
            return singletonObj.getCacheCount()==2;
        };
    }

此致

Vinoth

相关问题