I have an issue with mocking in a Play application. I have an Application as follows:
object Application extends Controller {
def login = Action {implicit request =>
val email = ... //Some email from the request
if(EmailChecker.checkEmail(email)) {
Ok("Email is checked and is fine")
} else {
Ok("Email is wrong")
}
}
}
What I want to do is to test a request but mock away the EmailChecker becasue it does some lookup in some database and that is not something I want to do in my test.
I have seen some tutorials on how to mock in Scala but I cannot find anything that covers the case I have.
Any help/pointers/tutorials that show how to do what I want to do would be great.
I am quite new to both Play! and Scala...
One possible solution:
class Application(emailChecker: EmailChecker) extends Controller {
def login = Action {implicit request =>
val email = ... //Some email from the request
if(emailChecker.checkEmail(email)) {
Ok("Email is checked and is fine")
} else {
Ok("Email is wrong")
}
}
}
object Application extends Application(EmailChecker)
And the test would be:
import org.specs2.Specification
import org.specs2.mock.Mockito
class ApplicationUnitSpec extends Specification with Mockito { def is =
"Test Application" ! {
val emailChecker = mock[EmailChecker]
val response = new Application(emailChecker).login(FakeRequest)
there was one(emailChecker).checkEmail("[email protected]")
}
}
I also like to define an object containing the Real and Test implicits that provide the real and stub versions respectively of services like EmailChecker and import them depending on whether it's a test or prod code. In this case you need to make the emailChecker parameter implicit. A crude type of dependency injection.
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