我正在使用 ScalaTest 和 Mockito 来测试应用程序控制器。
我的控制器及其单元测试编写如下
控制器 -
class UserCRUDController(userCRUDService :UserCRUDService) extends Controller {
def create() = Action.async(parse.anyContent) {
request =>
val result = userCRUDService.create
val timeOut = Promise.timeout("timed out", 2.second)
Future.firstCompletedOf(Seq(result, timeOut)).map {
case "timed out" => InternalServerError(
Json.obj("ok" -> "1", "message" -> "Request Timed Out!!!")
)
case status: JsObject => Ok(status)
}
}
}
控制器单元测试 -
class UserCRUDControllerTest extends FunSpec with Matchers with MockitoSugar {
describe("UserCRUD controller") {
describe("Create") {
it("should be timed out after 2 seconds") {
val mockUserCRUDService = mock[UserCRUDService]
val controller = new UserCRUDController(mockUserCRUDService)
val fakeRequest = FakeRequest("POST", routes.UserCRUDControllerInstance.create().toString)
val timedOutResponse = Future {
Thread.sleep(3000)
Json.obj("test" -> "timed out")
}
when(mockUserCRUDService.create).thenReturn(timedOutResponse)
val result = controller.create()(fakeRequest)
status(result) should be(INTERNAL_SERVER_ERROR)
contentAsJson(result) should be(
Json.obj("ok" -> "1", "message" -> "Request Timed Out!!!")
)
}
}
}
}
但是我在运行测试时遇到以下错误
[info] UserCRUDControllerTest:
[info] UserCRUD controller
[info] Create
[info] - should be timed out after 2 seconds *** FAILED ***
[info] java.lang.RuntimeException: There is no started application
[info] at scala.sys.package$.error(package.scala:27)
[info] at play.api.Play$$anonfun$current$1.apply(Play.scala:71)
[info] at play.api.Play$$anonfun$current$1.apply(Play.scala:71)
[info] at scala.Option.getOrElse(Option.scala:120)
[info] at play.api.Play$.current(Play.scala:71)
[info] at play.api.libs.concurrent.Promise$.timeout(Promise.scala:50)
[info] at play.api.libs.concurrent.Promise$.timeout(Promise.scala:37)
[info] at controllers.UserCRUDController$$anonfun$create$1.apply(UserCRUDController.scala:15)
[info] at controllers.UserCRUDController$$anonfun$create$1.apply(UserCRUDController.scala:13)
[info] at play.api.mvc.Action$.invokeBlock(Action.scala:556)
[info] ...
当我在running(FakeApplication())
内包装测试时,这会得到解决,但是会抛出异常。
我在使用模拟时总是需要运行假的应用程序实例 在单元测试中?