2015-06-22 22 views
10

我正在嘗試爲我的應用程序編寫一個測試用例akka-http。下面的一個測試用例的給定:Akka Http路由測試:請求在1秒內既未完成也未被拒絕

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秒?

回答

5

以下是爲我工作:

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

只需定義'implicit val timeout = RouteTestTimeout(2.seconds)'就足夠了' –

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以更長的超時時間隱式提供。

+1

我把這個在我的規範類,它並更改超時:'私人隱含的val超時= RouteTestTimeout(10秒跨度)'。 – Lachlan

2

,你可以簡單地更新配置,以擴張超時

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