riccardo.cardin
riccardo.cardin

Reputation: 8353

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 PutAck[Try[String]]. 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))
    context.become(nonEmptyMap(newStore))
  } 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 differenthashCode that the two exception have.

How can I test this case?

Upvotes: 0

Views: 506

Answers (1)

johanandren
johanandren

Reputation: 11479

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]

Upvotes: 1

Related Questions