我们如何为akka UntypedProcessor编写单元测试

时间:2014-06-17 01:02:34

标签: java unit-testing akka akka-persistence

我创建了一个扩展UnTypedProcessor的actor。我打算用这个actor将它的一些消息保存到磁盘上。演员看起来像这样,

public class Shard extends UntypedProcessor {

  LoggingAdapter log = Logging.getLogger(getContext().system(), this);

  @Override
  public void onReceive(Object message) throws Exception {
    if(message instanceof CreateTransactionChain) {
      System.out.println("Received a CreateTransactionChain message");
      ActorRef transactionChain = getContext().actorOf(Props.create(TransactionChain.class), "transactionChain");
      Address address = transactionChain.path().address();
      getSender().tell(new CreateTransactionReply(address), getSelf());
    }
  }
}

我为此编写了一个单元测试,

public class ShardTest extends AbstractActorTest{
  @Test
  public void testOnReceiveCreateTransaction() throws Exception {
System.out.println("running tests");

new JavaTestKit(getSystem()) {{
  final Props props = Props.create(Shard.class);
  final TestActorRef<Shard> subject = TestActorRef.create(getSystem(), props, "test");

  // can also use JavaTestKit “from the outside”
  final JavaTestKit probe = new JavaTestKit(getSystem());

  // the run() method needs to finish within 3 seconds
  new Within(duration("3 seconds")) {
    protected void run() {

      subject.tell(new CreateTransactionChain(), getRef());

      final String out = new ExpectMsg<String>("match hint") {
        // do not put code outside this method, will run afterwards
        protected String match(Object in) {
          if (in instanceof CreateTransactionReply) {
            return "match";
          } else {
            throw noMatch();
          }
        }
      }.get(); // this extracts the received message

      assertEquals("match", out);

      // Will wait for the rest of the 3 seconds
      expectNoMsg();
    }


      };
    }};
  }
}

当我运行此测试时,不会调用UntypeProcessor的onReceive方法。如果我从UntypedActor扩展我的类而不是工作正常。任何扩展UntypedProcessor的想法都不起作用?是否需要添加一些配置才能使其正常工作?有什么需要被嘲笑的吗?

1 个答案:

答案 0 :(得分:1)

akka-persistence不能与TestActorRef提供的相同线程调度程序一起使用。我们需要切换到使用简单的ActorRef,以便可以使用多线程调度程序进行测试。

这个github问题讨论了同样的问题: - https://github.com/akka/akka/issues/15293