我有一个名为FooActor
的演员,它会传递Props
来实例化多个BarActor
并向其发送BarMessage
。代码能够正常运行,但我很难为其编写测试。另外,这个应用程序只能使用Java代码,不能使用Scala代码。
经过多次尝试,以下是目前最好的尝试:
@Test
public void testJavaTestKit() {
new JavaTestKit(system) {{
JavaTestKit probe = new JavaTestKit(system);
// pretending that the probe is the receiving Bar, by returning it in the Props
Props barActorProps = Props.create(BarActor.class, new Creator() {
@Override
public Object create() {
return probe.getRef();
}
});
Props props = Props.create(FooActor.class, barActorProps);
ActorRef subject = system.actorOf(props);
Object msg = // basically irrelevant, will trigger Bar instantiation and message sending
subject.tell(msg, probe.getRef());
expectMsgClass(Bar.BarMessage.class);
expectNoMsg();
}};
}
我觉得这些都很有道理,但即使我看到消息被发送到新创建的
Bar
实例,第一个断言还是失败了。我做错了什么?更新:
与Akka文档示例不同的是,我不想传递接收消息的现有actor。相反,我想传递用于创建子actor实例的
Props
。在测试中,我希望我的probe
接收那些新创建的actors的消息。这就是为什么我添加了Props.create
构造函数,它应该始终返回相同的probe actor。刚才我在Creator.create
API中看到了这个注释:“此方法必须在每次调用时返回不同的实例。”
显然,这样不起作用,因为这正是我想要的。所以我的一般问题仍然存在:如何测试发送给新创建的子actor的消息?
probe.expectMsgClass(Bar.BarMessage.class);
。 - nickebbittFooActor.class
的代码可能会帮助您获得所需的解决方案。当我最初开始使用Java测试Akka Actors时,我遵循了这里描述的模式 [github-link](https://gist.github.com/jconwell?direction=asc&sort=created),特别是在您的情况下,ForwarderActor听起来就像是您需要的东西。 - nickebbitt