Akka Http Route Test:请求未在1秒内完成或拒绝

Yad*_*nan 8 scala akka-http akka-testkit

我正在尝试为我的应用程序编写一个测试用例akka-http.其中一个测试用例如下:

import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.{ ScalatestRouteTest}
import com.reactore.common.core.{CommonCoreSystem, CommonActors, BootedCommonCoreSystem}
import scala.concurrent.duration._
import com.reactore.common.feature.referencedata.{DepartmentRepository, DepartmentService, DepartmentController, DepartmentRest}
import org.scalatest.concurrent.AsyncAssertions
import org.scalatest.time.Span
import org.scalatest.{WordSpec, Matchers}
import akka.http.scaladsl.model.StatusCodes._
/**
 * Created by krishna on 18/6/15.
 */


class DepartmentITTest extends WordSpec with Matchers with ScalatestRouteTest with CommonCoreSystem with CommonActors {
//  override val departmentRouter = system.actorOf(Props(classOf[DepartmentService], DepartmentRepository), Constants.DEPARTMENT_ROUTER_NAME)
  val deptRoute = (new DepartmentRest(departmentRouter)(DepartmentController).deptRoutes)
  implicit val timeout = AsyncAssertions.timeout(Span.convertDurationToSpan(5.second))
  val departmentJson = """{"id":13,"name":"ENGP22","shortCode":"ENGP2","parentDepartmentId":null,"mineId":null,"photoName":null,"isRemoved":false,"isPendingForApproval":false,"createdBy":0,"createDate":"2015-03-09 00:00:00","modifiedBy":0,"modifiedDate":"2015-03-09 00:00:00"}"""
  val header = RawHeader("apiKey", "xxxxx")
  "Service" should  {
    "return department by id" in {
      Get("/departments/13").withHeaders(header) ~> deptRoute ~> check {
//        Thread.sleep(500)
        status shouldBe OK
        responseAs[String] shouldBe departmentJson
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它有时会正常工作,有时我会得到错误Request was neither completed nor rejected within 1 second.我添加了一个Thread.sleep来使它现在正常工作.我知道这不是正确的解决方案.谁能告诉我如何使测试等待超过1秒?

小智 10

以下是为我工作:

import akka.actor.ActorSystem
import scala.concurrent.duration._
import spray.testkit.ScalatestRouteTest

class RouteSpec extends ScalatestRouteTest {
  implicit def default(implicit system: ActorSystem) = RouteTestTimeout(2.second)
...
Run Code Online (Sandbox Code Playgroud)

  • 仅定义`implicit val timeout = RouteTestTimeout(2.seconds)`就足够了 (4认同)

Ric*_*ich 6

您可以使用ScalaTest中的"最终"匹配器等待条件成为真:

eventually { status shouldBe OK }
Run Code Online (Sandbox Code Playgroud)

http://www.artima.com/docs-scalatest-2.0.M5/org/scalatest/concurrent/Eventually.html

如果您在上面注释掉的Thread.sleep为您修复了一些内容,那就足够了.

但是,在我看来,实际的错误是RouteTest特征使用的超时时间太短.错误消息"请求未在1秒内完成或拒绝".来自RouteTestResultComponent,来自akka.http.scaladsl.testkit.RouteTest.

我认为Thread.sleep是一个分心.路由测试的默认超时为1秒; 看akka.http.scaladsl.testkit.RouteTestTimeout.default.您在代码中提供了5秒的隐式超时,但我认为它是一种不同的类型.尝试使用更长的超时隐式提供RouteTestTimeout.


小智 5

您可以简单地更新配置以扩大超时时间

akka {
  test {
    # factor by which to scale timeouts during tests, e.g. to account for shared
    # build system load
    timefactor =  3.0
  }
}
Run Code Online (Sandbox Code Playgroud)