Implementing Controller using Play 2.x (Scala), ScalaMock
Join the DZone community and get the full member experience.
Join For Freefor people in hurry here is the code and the steps .
in continuation of play 2.x (scala) is it a spring mvc contender? – introduction , in this blog, i will demonstrate how we implement a simple controller implementation using scalatest / scalamock. i will continue from my earlier example of implementing dal in play 2.x (scala), slick, scalatest of the basic crud operations on coffee catalogue.
in our previous example, we have already implemented a dal trait called coffeecomponent with basic crud as below,
trait coffeecomponent { def find(pk: string): query[coffees.type, coffee] def findall(pk: string): query[(coffees.type, suppliers.type), (coffee, supplier)] def list(page: int, pagesize: int, orderby: int, filter: string): query[(coffees.type, suppliers.type), (coffee, supplier)] def delete(pk: string): int }
we are construction injecting coffeecomponent to the coffeecontroller and create a singleton object with the same name, as below,
class coffeescontroller(coffeecomponent: coffeecomponent) extends controller { ... def delete(pk: string) = action { database withsession { println("in db session") home.flashing(coffeecomponent.delete(pk) match { case 0 => "failure" -> "entity has not been deleted" case x => "success" -> s"entity has been deleted (deleted $x row(s))" }) } } } object coffeescontroller extends coffeescontroller(new coffeecomponentimpl)
as seen above, we have a delete method, we will build a scalamock to mock the delete method of coffeecomponent and control the expected behavior to return 1 row effected and assert for http see_other status as below,
class coffeescontrollertest extends funspec with shouldmatchers with mockfactory { describe("coffee controller with mock test") { it("should delete a coffee record with assert on status") { running(fakeapplication(additionalconfiguration = inmemorydatabase())) { val mockcomponent = mock[coffeecomponent] (mockcomponent.delete _).expects("columbian") returning (1) twice val controller = new coffeescontroller(mockcomponent) mockcomponent.delete("columbian") should equal (1) val result = controller.delete("columbian")(fakerequest()) status(result) should equal (see_other) } } } }
if you notice, we are extending funspec of scalatest for bdd . also the http status is see_other , this is because the success is redirected to index page.
now if you run the scalatest you will see the result in sts as below,
i hope this blog helped. in my next blog, i will talk about controller routes testing and frontend testing.
Published at DZone with permission of Krishna Prasad, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments