I want to test my Play application by providing mock objects during a test. Off the top of my head, there are a few ways to go about this.
I am not sure which is more feasible, or how to go about doing them. Any insight would be greatly appreciated.
There is a third way; create your controller as a class or a trait for testing. Here is a simple example.
Your trait + implementation:
package services
trait MyService {
def getUser(id:String):User
}
class ConcreteService extends MyService {
override def getUser(id:String):User = {
//Do real stuff
}
}
In your controller class:
package controllers
import services._
class Users(service: MyService) extends Controller {
def show(id: String) = Action {
val user = service.getUser(id)
Ok(views.html.user(user))
}
}
object Users extends controllers.Users(new ConcreteService()) {}
Now you can run some unit tests..
package test
import controllers.Users
import play.api.test._
import play.api.test.Helpers._
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
class UsersSpec extends Specification with Mockito {
val service = mock[MyService]
"Users controller" should {
"list users" in {
//Insert mocking stuff here
val users = new Users(service)
val result = users.show("somerandomid")(FakeRequest())
status(result) must equalTo(OK)
}
}
}
I had the same question, and experimented some options:
You can see the code on github here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With