riccardo.cardin riccardo.cardin - 6 months ago 30
Scala Question

Test the message returned by an akka actor containing a Try[T]

I am developing an Akka actor that respond with a message of type

. The problem is not how to develop the actor itself, but the unit tests.

Given that the following actor code

private def put(store: Map[String, Array[Byte]], key: String, value: Array[Byte]) = {
try {
val newStore = store + (Objects.requireNonNull(key) -> value)
sender ! PutAck(Success(key))
} catch {
case ex: Exception =>
sender ! PutAck(Failure(ex))

I wish to test it with the following test

"A Storekeeper actor" must {
"receive an error message for a couple (null, value)" in {
val sk = TestActorRef[Storekeeper]
sk ! Put(null, SerializationUtils.serialize(42))
expectMsg(PutAck(Failure(new NullPointerException())))

Unfortunately, the test fails with message

assertion failed: expected PutAck(Failure(java.lang.NullPointerException)), found PutAck(Failure(java.lang.NullPointerException))

I supposed that the failure is due to the different
that the two exception have.

How can I test this case?


The reason why it does match is that instances of NullPointerExceptions are only equal to themselves, not other seemingly identical instances.

What you can do instead is to expect the message on type, catch the response as a value and then assert whatever you want about it, something like this:

val ack = expectMsgType[PutAck[Try[String]]]
ack.value.isFailure should === (true)
ack.value.failed.get shouldBe a[NullPointerException]