Scala-Akka框架集成测试



我正试图为使用AKKA框架的scala应用程序编写一个简单的集成测试。

我想

  1. 在本地主机上启动应用程序
  2. 编写直接命中应用程序的测试用例

我使用springboottest做过类似的事情,但我似乎找不到任何类似的东西。我一直在尝试了解testkit路线,但它似乎更像是一个单元测试,而不是一个完整的应用程序集成测试。

任何关于我正在寻找的东西的建议都会很棒。

谢谢!

首次导入

val akkaVersion = "2.6.10"
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor" % akkaVersion,
"com.typesafe.akka" %% "akka-testkit" % akkaVersion)

创建参与者

import akka.actor.{Actor, ActorSystem, Props}
object ActorsIntro extends App {
run()
def run() = {
val actorSystem = ActorSystem("ActorsIntro")
println(actorSystem.name)
val worldCounter = actorSystem.actorOf(Props[WordCountActor], "WordCounter")
val anotherWorldCounter = actorSystem.actorOf(Props[WordCountActor], "AnotherWordCounter")
worldCounter ! "I am reviewing Akka using Scala and it is pretty damn awesome !"
worldCounter ! "asynchronous message Akka Scala"
anotherWorldCounter ! "asynchronous message Akka Scala"
val person = actorSystem.actorOf(Person.props("Bob"))
person ! "hi"
}
class WordCountActor extends Actor {
var totalWords = 0
override def receive: PartialFunction[Any, Unit] = {
case message: String =>
println(s"Message received[ $message ]")
totalWords += message.split(" ").length
println(s"Total words counted: $totalWords")
case msg => println(s"word count. I cannot understand ${msg.toString}")
}
}
object Person {
def props(name: String) = Props(new Person(name))
val propsPersonActor = {
Props(new Person(""))
}
}
class Person(name: String) extends Actor {
override def receive: Receive = {
case "hi" =>
val reply = s"Hi, my name is $name"
println(reply)
sender() ! reply
case message => sender() ! message
}
}
}

及其测试用例

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestKit}
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
class ActorsIntroTest extends TestKit(ActorSystem("ActorsIntroSpec"))
with ImplicitSender
with AnyWordSpecLike
with Matchers
with BeforeAndAfterAll {
override def afterAll(): Unit = {
TestKit.shutdownActorSystem(system)
}
"The ActorsIntro actor" should {
"send back hi replay" in {
val name = "Bob"
val actorPerson = system.actorOf(ActorsIntro.Person.props(name))
val hi = "hi"
val hiReply = s"Hi, my name is $name"
actorPerson ! hi
expectMsg(hiReply)
}
"or send back the same message" in {
val name = "Bob"
val actorPerson = system.actorOf(ActorsIntro.Person.props(name))
val message = "hello, test"
actorPerson ! message
expectMsg(message)
}
}
}

如果您希望应用程序在localhost上运行,我建议您考虑使用akka-http,这样您就可以绑定localhost服务器并测试您的应用程序。

最新更新