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

时间:2015-06-22 10:40:20

标签: scala akka-testkit akka-http

我正在尝试使用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
      }
    }
  }
}

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

3 个答案:

答案 0 :(得分:8)

以下内容对我有用:

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)
...

答案 1 :(得分:6)

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

eventually { status shouldBe OK }

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。

答案 2 :(得分:4)

您只需更新配置即可扩展超时

akka {
  test {
    # factor by which to scale timeouts during tests, e.g. to account for shared
    # build system load
    timefactor =  3.0
  }
}