9

我正在尝试为我的应用程序编写一个测试用例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 秒?

4

3 回答 3

12

The following is working for me:

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)
...
于 2016-09-23T21:36:06.270 回答
6

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

eventually { status shouldBe OK }

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

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

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

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

于 2015-08-17T14:07:12.753 回答
5

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

akka {
  test {
    # factor by which to scale timeouts during tests, e.g. to account for shared
    # build system load
    timefactor =  3.0
  }
}
于 2017-03-01T04:45:40.857 回答