简体   繁体   中英

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

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("blah@example.com")
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM