Unit Tests Controllers with Mockito
I am using ScalaTest and Mockito to unit test my application controllers.
My controller and its unit test are written like this
Controller -
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)
}
}
}
Unit test controller -
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!!!")
)
}
}
}
}
But I am getting the following error when running the test
[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] ...
This is resolved if I terminate the test in running(FakeApplication())
, but throws an exception otherwise.
Do I need to run a fake instance of an app whenever I use mocks in a unit test?
+3
source to share
No one has answered this question yet
Check out similar questions: