Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking in Play! and Scala

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...

like image 565
Jakob Avatar asked Sep 25 '12 14:09

Jakob


1 Answers

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.

like image 108
Ratan Sebastian Avatar answered Nov 16 '22 23:11

Ratan Sebastian