我已经使用Akka HTTP实现了Web套接字。我正在使用来自 Kafka 的数据并使用 Web 套接字发送通知。功能运行良好,但我被困在测试用例中。
` private def loginNotificationRoute(): Route = {
cors() {
pathPrefix("notifications" / Segment) { userName =>
get {
handleWebSocketMessages(notificationClientFlow(userName))
}
}
}
}`
通知执行组件从数据库读取通知并将数据发送回客户端。
` def notificationClientFlow(userName: String): Flow[Message, Message, NotUsed] = {
info(s"Connection Request accepted for user $userName")
val notificationActor = actorSystem.actorOf(NotificationActor.props(userName, jsonHelper))
val incomingMessages: Sink[Message, NotUsed] =
Flow[Message].map {
case TextMessage.Strict(text) => NotificationActor.IncomingMessage(text)
}.to(Sink.actorRef(notificationActor, PoisonPill))
val outgoingMessages: Source[Message, NotUsed] =
Source
.actorRef[NotificationActor.ResponseType](BUFFER_SIZE, OverflowStrategy.fail)
.mapMaterializedValue { outgoingActor =>
notificationActor ! NotificationActor.Connected(outgoingActor)
NotUsed
}
.map {
notificationResponse: NotificationActor.ResponseType =>
info(s"sending notification ${notificationResponse.action}")
TextMessage.Strict(jsonHelper.write(notificationResponse))
}
Flow.fromSinkAndSource(incomingMessages, outgoingMessages)
}`
重新设计依赖项
在我看来,你当前设计的最大缺点是对特定actorSystem
的固有依赖;有问题的代码行是
//actorSystem comes from the outside world!!!
val notificationActor = actorSystem.actorOf(NotificationActor.props(userName, jsonHelper))
应重新参数化notificationClientFlow
方法,以便在参数中显式列出所有依赖项。 并且不应该依赖于整个ActorSystem
,而是应该简化为一个ActorRef
:
def notificationClientFlow(userName: String,
notificationActor : ActorRef): Flow[Message, Message, NotUsed] = {
//notificationActor is now passed in
//val notificationActor = actorSystem.actorOf(NotificationActor.props(userName, jsonHelper))
}
这将需要在Route
创建方法中进行类似的显式声明:
private def loginNotificationRoute(notificationActor : ActorRef)() : Route = {
...
handleWebSocketMessages(notificationClientFlow(userName, notificationActor))
}
测试
现在可以使用TestKit
实现测试:
class MySpec() extends TestKit(ActorSystem("MySpec")) {
val userName = "testUser"
val notificationActor =
system.actorOf(NotificationActor.props(userName, jsonHelper))
val testFlow = notificationClientFlow(userName, notificationActor)
}
此外,由于我们已经明确通过了ActorRef
,而不仅仅是ActorSystem
因此我们可以使用其他高级测试功能,例如探针:
val probe = TestProbe()
val testProbeFlow = notificationClientFlow(userName, probe.ref)
上述技术同样适用于使用标准技术测试路由:
val testRoute = loginNotificationRoute(testProbe)
Get() ~> testRoute() ~> check {
//testing assertions here
}