我试图为我的演员之一编写单元测试,这是从使用的TestKit派生出来的。我需要用TestActorRef.create创造一个演员(.)因为我需要获得一个underlyingActor,以便将模拟注入到参与者的实现中。
我的(简化)演员
public class MyActor extends AbstractPersistentActorWithAtLeastOnceDelivery {
@Override
public Receive createReceive() {
return receiveBuilder().match(String.class, message -> {
persist(new MessageSent(message), event -> updateState(event));
}).match(ConfirmMessage.class, confirm -> {
persist(new MessageConfirmed(confirm.deliveryId), event ->
updateState(event));
}).matchAny(message -> log.info("Received unexpected message of class {}.
Content: {}", message.getClass().getName(), message.toString())).build();
}
void updateState(Object received) {
if (received instanceof MessageSent) {
final MessageSent messageSent = (MessageSent) received;
ActorRef destinationActor =
findDestinationActor(messageSent.messageData);
deliver(actorSystem.actorSelection(destinationActor.path()),
deliveryId -> new Message(deliveryId, messageSent.messageData));
} else if (received instanceof MessageConfirmed) {
final MessageConfirmed messageConfirmed = (MessageConfirmed) received;
confirmDelivery(messageConfirmed.deliveryId);
}
}单元测试:
@Test
public void actorTest() {
ActorSystem system = ActorSystem.create();
TestKit probe = new TestKit(system);
TestActorRef<myActor> testActor = TestActorRef.create(system, props,
probe.getRef());
MyActor myActor = testActor.underlyingActor();
injectMocks(myActor); // my method
testActor.tell("testMessage", probe.getRef());
List<Object> receivedMessages = probe.receiveN(1, FiniteDuration.create(3,
TimeUnit.SECONDS));
}在调试器中,我看到调用了updateState()中的()方法,但是单元测试失败时出现了错误:
断言失败:超时(3秒),同时等待1条消息(got 0)
我想知道是否可以使用测试通过TestActorRef创建的参与者,以及我的参与者扩展TestActorRef是否与测试失败有关。
发布于 2018-03-21 08:27:00
使用TestActorRef与Akka持久化是不可能的。它有时起作用,但常常以你在问题中描述的方式失败。TestKit的其他特性可以很好地处理Akka持久化。
参见https://doc.akka.io/docs/akka/current/testing.html#synchronous-testing-testactorref下的警告
警告 由于TestActorRef的同步特性,它将无法处理Akka提供的一些支持特性,因为它们需要异步行为才能正常工作。Akka持久性提供的PersistentActor和AtLeastOnceDelivery不能很好地与测试参与者推荐的特性相结合。
https://stackoverflow.com/questions/49391604
复制相似问题