I’m working on Scala and the Play Framework project, and we are trying to write test cases using PlaySpec
with GuiceOneAppPerTest
, MockitoSugar
, and BeforeAndAfterAll
.
Here’s the function we are testing:
def getRole(id: Long): Action[AnyContent] = Action.async {
roles.get(id).map(response => {
Ok(Json.obj("name" -> response.map(_.name)))
})
}
And here is our test case:
"get Roles by Id" in {
val roleId = 11L
val fakeRequest = FakeRequest(GET, s"/role/id/$roleId")
when(mockRoles.get(roleId)).thenReturn(Future.successful(Some(Role("admin"))))
val result = controller.getRole(roleId).apply(fakeRequest)
status(result) mustBe OK
contentAsJson(result) mustBe Json.obj("name" -> "admin")
}
The test case is not working.
However, if we modify the function to remove async and handle the future synchronously, it works fine:
def getRole(id: Long): Action[AnyContent] = Action {
roles.get(id).toJava.toCompletableFuture.get() match {
case Some(value) => Ok(Json.obj("name" -> value.name))
case None => BadRequest(Json.obj("error" -> "Data not found"))
}
}
Could someone please help us understand why the Action.async
version is failing and how we can fix the test case for it?
2