测试包含 Try[T] 的 akka actor 返回的消息
Test the message returned by an akka actor containing a Try[T]
我正在开发一个 Akka actor 来响应 PutAck[Try[String]]
类型的消息。问题不在于如何开发actor本身,而在于单元测试。
鉴于以下演员代码
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))
}
}
我想用下面的测试来测试它
"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())))
}
}
不幸的是,测试失败并显示消息
assertion failed: expected PutAck(Failure(java.lang.NullPointerException)), found PutAck(Failure(java.lang.NullPointerException))
我以为失败是由于两个异常hashCode
不同
我该如何测试这个案例?
之所以匹配,是因为NullPointerException
的实例只等于自己,而不是其他看似相同的实例。
你可以做的是期待消息类型,捕捉响应作为一个值,然后断言你想要的任何东西,像这样:
val ack = expectMsgType[PutAck[Try[String]]]
ack.value.isFailure should === (true)
ack.value.failed.get shouldBe a[NullPointerException]
我正在开发一个 Akka actor 来响应 PutAck[Try[String]]
类型的消息。问题不在于如何开发actor本身,而在于单元测试。
鉴于以下演员代码
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))
}
}
我想用下面的测试来测试它
"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())))
}
}
不幸的是,测试失败并显示消息
assertion failed: expected PutAck(Failure(java.lang.NullPointerException)), found PutAck(Failure(java.lang.NullPointerException))
我以为失败是由于两个异常hashCode
不同
我该如何测试这个案例?
之所以匹配,是因为NullPointerException
的实例只等于自己,而不是其他看似相同的实例。
你可以做的是期待消息类型,捕捉响应作为一个值,然后断言你想要的任何东西,像这样:
val ack = expectMsgType[PutAck[Try[String]]]
ack.value.isFailure should === (true)
ack.value.failed.get shouldBe a[NullPointerException]