我刚刚开始测试Akka HTTP Request-Level Client-Side API (Future-Based)。我一直在努力弄清楚的一件事是如何为此编写单元测试。有没有办法模拟响应并完成未来而无需实际执行HTTP请求?
我正在查看API和testkit包,试图了解我如何使用它,只是在文档中找到它实际上说的内容:
akka-http-testkit 用于验证服务器端服务实现的测试工具和实用程序集
我正在考虑NSMutableArray
(有点像Akka Streams的TestServer
)并使用服务器端路由DSL创建预期的响应并以某种方式将其挂钩TestSource
对象
以下是我想要测试的函数的简化示例:
Http
答案 0 :(得分:4)
我认为总的来说,你已经意识到最好的方法是嘲笑回应。在Scala中,这可以使用Scala Mock http://scalamock.org/
来完成如果您安排代码以便将akka.http.scaladsl.HttpExt
的实例依赖注入到使用它的代码中(例如作为构造函数参数),那么在测试期间您可以注入mock[HttpExt]
的实例而不是使用Http
apply方法构建的。
编辑:我猜这是因为不够具体而被否决。这是我如何构建你的场景的模拟。所有的阴道炎使它变得更加复杂。
main
中的代码:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{Uri, HttpResponse, HttpRequest}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import scala.concurrent.{ExecutionContext, Future}
trait S3BucketTrait {
type HttpResponder = HttpRequest => Future[HttpResponse]
def responder: HttpResponder
implicit def actorSystem: ActorSystem
implicit def actorMaterializer: ActorMaterializer
implicit def ec: ExecutionContext
def sampleTextFile(uri: Uri): Future[String] = {
val responseF = responder(HttpRequest(uri = uri))
responseF.flatMap { response => Unmarshal(response.entity).to[String] }
}
}
class S3Bucket(implicit val actorSystem: ActorSystem, val actorMaterializer: ActorMaterializer) extends S3BucketTrait {
override val ec: ExecutionContext = actorSystem.dispatcher
override def responder = Http().singleRequest(_)
}
test
中的代码:
import akka.actor.ActorSystem
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.testkit.TestKit
import org.scalatest.{BeforeAndAfterAll, WordSpecLike, Matchers}
import org.scalamock.scalatest.MockFactory
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.Future
class S3BucketSpec extends TestKit(ActorSystem("S3BucketSpec"))
with WordSpecLike with Matchers with MockFactory with BeforeAndAfterAll {
class MockS3Bucket(reqRespPairs: Seq[(Uri, String)]) extends S3BucketTrait{
override implicit val actorSystem = system
override implicit val ec = actorSystem.dispatcher
override implicit val actorMaterializer = ActorMaterializer()(system)
val mock = mockFunction[HttpRequest, Future[HttpResponse]]
override val responder: HttpResponder = mock
reqRespPairs.foreach{
case (uri, respString) =>
val req = HttpRequest(HttpMethods.GET, uri)
val resp = HttpResponse(status = StatusCodes.OK, entity = respString)
mock.expects(req).returning(Future.successful(resp))
}
}
"S3Bucket" should {
"Marshall responses to Strings" in {
val mock = new MockS3Bucket(Seq((Uri("http://example.com/1"), "Response 1"), (Uri("http://example.com/2"), "Response 2")))
Await.result(mock.sampleTextFile("http://example.com/1"), 1 second) should be ("Response 1")
Await.result(mock.sampleTextFile("http://example.com/2"), 1 second) should be ("Response 2")
}
}
override def afterAll(): Unit = {
val termination = system.terminate()
Await.ready(termination, Duration.Inf)
}
}
build.sbt
个依赖项:
libraryDependencies += "com.typesafe.akka" % "akka-http-experimental_2.11" % "2.0.1"
libraryDependencies += "org.scalamock" %% "scalamock-scalatest-support" % "3.2" % "test"
libraryDependencies += "org.scalatest" % "scalatest_2.11" % "2.2.6"
libraryDependencies += "com.typesafe.akka" % "akka-testkit_2.11" % "2.4.1"
答案 1 :(得分:4)
考虑到您确实要为HTTP客户端编写单元测试,您应该假装没有真正的服务器而不跨越网络边界,否则您显然会进行集成测试。在您的情况下强制执行单元可测试分离的一个众所周知的方法是拆分接口和实现。只需定义一个界面,抽象访问外部HTTP服务器及其真实和假实现,如下面的草图
import akka.actor.Actor
import akka.pattern.pipe
import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import scala.concurrent.Future
trait HTTPServer {
def sendRequest: Future[HttpResponse]
}
class FakeServer extends HTTPServer {
override def sendRequest: Future[HttpResponse] =
Future.successful(HttpResponse(StatusCodes.OK))
}
class RealServer extends HTTPServer {
def http: HttpExt = ??? //can be passed as a constructor parameter for example
override def sendRequest: Future[HttpResponse] =
http.singleRequest(HttpRequest(???))
}
class HTTPClientActor(httpServer: HTTPServer) extends Actor {
override def preStart(): Unit = {
import context.dispatcher
httpServer.sendRequest pipeTo self
}
override def receive: Receive = ???
}
并与HTTPClientActor
一起测试您的FakeServer
。
答案 2 :(得分:2)
我希望有一种方法可以利用某种类型的测试演员系统,但如果没有(或其他一些惯用的方式),我可能会做这样的事情:
object S3Bucket {
type HttpResponder = HttpRequest => Future[HttpResponse]
def defaultResponder = Http().singleRequest(_)
def sampleTextFile(uri: Uri)(
implicit akkaSystem: ActorSystem,
akkaMaterializer: ActorMaterializer,
responder: HttpResponder = defaultResponder
): Future[String] = {
val request = responder(HttpRequest(uri = uri))
request.map { response => Unmarshal(response.entity).to[String] }
}
}
然后在我的测试中我可以提供一个模拟HttpResponder
。