在单元测试中,演员如何处理所有消息?

我在我们的产品中使用 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 系统中的所有事件完成?


呼如林
浏览 142回答 1
1回答

神不在的星期二

导入下面的包,然后你可以等待直到你处理完所有事件,否则测试将在超时后失败。testCompile 'org.awaitility:awaitility:3.1.0'import org.awaitility.Awaitility;在你使用 assertThat 之前await().pollInterval(5, TimeUnit.MILLISECONDS).until(() -> !isProcessed());isProcessed 方法如下所示protected Callable<Boolean> isProcessed() {&nbsp; &nbsp; &nbsp; &nbsp; return () -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return singletonObj.getCacheCount()==2;&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java