Akka Http 路由测试:请求在 1 秒内既未完成也未被拒绝

Akka Http Route Test: Request was neither completed nor rejected within 1 second

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

您可以在 ScalaTest 中使用 "eventually" 匹配器来等待条件变为真:

eventually { status shouldBe OK }

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

如果您在上面注释掉的 Thread.sleep 为您解决了问题,那就足够了。

但是,在我看来,真正的错误是 RouteTest 特征使用的超时时间太短。错误消息 "Request was neither completed nor rejected within 1 second." 来自 RouteTestResultComponent via akka.http.scaladsl.testkit.RouteTest。

我认为 Thread.sleep 会让人分心。路由测试默认超时时间为1秒;参见 akka.http.scaladsl.testkit.RouteTestTimeout.default。您在代码中提供了 5 秒的隐式超时,但我认为它属于不同类型。尝试使 RouteTestTimeout 隐式可用,超时时间更长。

以下对我有用:

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

您只需更新配置即可延长超时时间

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