Java 8 和 Akka 2.12:2.5.16 在这里。我正在尝试利用 Akka TestKit 编写我的第一个(有史以来(Akka 单元测试,并且正在努力应用我在网上能够找到的(极少数(示例中看到的原则。
我的演员:
public class Child extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()
.match(Init.class, init -> {
int workUnit = workService.doSomeWork();
log.info("Performed work on {}", workUnit);
}).build();
}
}
public class Master extends AbstractActor {
@Inject @Named("CHILD")
private ActorRef child;
@Override
public Receive createReceive() {
return receiveBuilder()
.match(Init.class, init -> {
child.tell(init, self());
}).build();
}
}
非常非常简单。所以现在我只想编写一个单元测试,用于验证当Master
参与者收到Init
消息时,它会将该消息转发到其Child
参与者。到目前为止,我最好的尝试:
@RunWith(MockitoJUnitRunner.class)
public class MasterTest {
private ActorSystem actorSystem;
@Before
public void setup() {
actorSystem = ActorSystem.create("test-system");
}
@After
public void teardown() {
Duration duration = Duration.create(10L, TimeUnit.SECONDS);
TestKit.shutdownActorSystem(actorSystem, duration, true);
actorSystem = null;
}
@Test
public void onInit_shouldSendFordwardToChild() {
// Given
TestKit testKit = new TestKit(actorSystem);
ActorRef master = actorSystem.actorOf(Props.create(Master.class, testKit));
// When
master.tell(new Init(), ActorRef.noSender());
// Then
testKit.expectMsg(Init.class);
}
}
当我运行这个时,我得到:
java.lang.IllegalArgumentException: no matching constructor found on class com.me.myapp.Master for arguments [class akka.testkit.TestKit]
有人可以帮我把TestKit
实例连接到我的Master
演员中,并帮助我弄清楚如何重构MasterTest
以便它验证我想要完成的任务吗?提前感谢!
我想通了,简直不敢相信让它工作有多困难:-/
在application.conf
:
MyAkkApp {
akka {
remote {
enabled-transports = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "127.0.0.1"
port = 2553
}
}
}
}
然后:
@RunWith(MockitoJUnitRunner.class)
public class MasterTest extends TestKit {
static ActorSystem actorSystem = ActorSystem.create("MyAkkaApp",
ConfigFactory.load().getConfig("MyAkkaApp"));
static TestProbe child; // The mock child
static ActorRef master;
@BeforeClass
public static void setup() {
child = new TestProbe(actorSystem, "Child");
master = actorSystem.actorOf(Props.create(new Creator<Actor>() {
@Override
public Actor create() throws Exception {
return new Master(child.ref());
}
}));
}
public MasterTest() {
super(actorSystem);
}
@Test
public void onInit_shouldSendFordwardToChild() {
// Given
Init init = new Init();
// When
master.tell(init, super.testActor());
// Then
child.expectMsg(init); // Child should have received it
expectNoMessage(); // Master should not be returning to sender
}
}
来吧阿卡伙计们!支持产生采用,采用导致标准化,标准化意味着您可以销售 6 位数的公司支持许可证。