Reputation: 3321
I have a task, which I need to test. This task takes some actors as parameters, so I created a test with a TestActor
as follows:
Few questions:
1. Is it a normal practice to create ActorSystem
for test purposes?
2. The code doesn't end. I have tried to
val system = ActorSystem("TestRoutingSystem")
val actorRef = system.actorOf(Props(new TestActor), name = "testActor")
var poisonReceived = false
var workReceived = 0
class TestActor extends Actor with Logging {
def receive = {
case msg: WorkerMessage =>
workReceived += 1
case x: Boolean => {
poisonReceived = true
}
}
}
val t = new java.util.Timer()
val task = new TestTask(...)
task.run()
t.schedule(task, 10, 10)
system.shutdown()
Thread.sleep(150)
println(poisonReceived )
println(workReceived)
Upvotes: 0
Views: 261
Reputation: 4685
As @nafr said, it's better to use akka-testkit
I'm not familiar with scalatest, so I write example in junit style. For example we should test some class, that send two messages to actor:
class TimerTask(actorRef: ActorRef) {
def run(): Unit = {
actorRef ! "some msg"
actorRef ! "some other msg"
}
}
Complete test will look like this:
import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{TestKit, TestProbe}
import org.junit.{After, Before, Test}
class TestExample {
protected implicit var system: ActorSystem = _
@Before
def setup(): Unit = {
system = ActorSystem.create("test")
}
@After
def tearDown(): Unit = {
TestKit.shutdownActorSystem(system)
}
@Test
def example(): Unit = {
val testProbe = TestProbe()
val source = new TimerTask(testProbe.ref)
source.run()
testProbe.expectMsg("some msg")
testProbe.expectMsg("some other msg")
}
}
So answers on your question:
1) It's the only true way to test something, where actors participate
2) Use TestKit.shutdownActorSystem(system)
Upvotes: 1