6
我想窺視我的演員實例,但不能簡單地用新關鍵字創建。我想通過下面的解決方案:在Akka男主角上跟蹤mockito
val testActorSpy = spy(TestActorRef(new TestActor).underlyingActor)
val testActorRef = TestActorRef(testActorSpy)
但這樣我創建一個不必要的演員。有沒有更清潔的解決方案?
我想窺視我的演員實例,但不能簡單地用新關鍵字創建。我想通過下面的解決方案:在Akka男主角上跟蹤mockito
val testActorSpy = spy(TestActorRef(new TestActor).underlyingActor)
val testActorRef = TestActorRef(testActorSpy)
但這樣我創建一個不必要的演員。有沒有更清潔的解決方案?
因此,我對Akka Actor系統的理解是,你應該通過屬性來做到這一點,然後呢?
因此,通過道具創建演員,並在測試時只是返回間諜的演員。
因此這應該給你一個結果:
val testActorRef = TestActorRef(spy(new TestActor))
val testActorSpy = testActorRef.underlyingActor
注意,重新啓動的演員當underlyingActor被摧毀。所以嘲笑這可能不是最好的選擇。
如果直接使用actor而不是通過系統,則可能也可以測試並繞過線程基礎系統。
請參閱this(下面的代碼粘貼爲java)。
static class MyActor extends UntypedActor {
public void onReceive(Object o) throws Exception {
if (o.equals("say42")) {
getSender().tell(42, getSelf());
} else if (o instanceof Exception) {
throw (Exception) o;
}
}
public boolean testMe() { return true; }
}
@Test
public void demonstrateTestActorRef() {
final Props props = Props.create(MyActor.class);
final TestActorRef<MyActor> ref = TestActorRef.create(system, props, "testA");
final MyActor actor = ref.underlyingActor();
assertTrue(actor.testMe());
}
演員的唯一公開方法應該是'onReceive'。否則,不變性處於危險之中。在這種情況下,如果'testMe'方法修改了actor的狀態,那麼違反了這個原則。 'testMe'應該是私人的。要訪問使用Spring的JUnit測試的私有方法,請使用'ReflectionTestUtils'。 – 2017-12-13 03:02:55
然後把它封裝成私人的。有很多方法來修改可見性。每個在我們的代碼庫上工作的人都知道可變共享狀態是不好的。而ActorRef不公開公共職能。所以它不是一個問題。我們的比賽狀況來自私人狀態結束.. – Alex 2017-12-13 07:51:23
你說得對。演員內部的公共方法不公開。我只是覺得它是一種代碼味道。但從功能角度來看,你是對的。 無論如何,如果有人想保持他們的方法私人,記住他們可以用'ReflectionTestUtils'調用 – 2017-12-13 15:33:48