Hi
Lets say I have a service which should be able to create different strings depending on selected language. For example an email service:
import play.api.i18n.Messages
class EmailService {
def createEmail()(implicit messages: Messages): String = {
s"""Subject: ${messages("email.subject")}. Message: ${messages("email.message")}"""
}
}
If I want to unit test this class I would do the following:
import org.specs2.mutable.Specification
import play.api.Logger
import play.api.i18n.Messages
import service.EmailService
import org.specs2.mock._
class EmailServiceTest extends Specification with Mockito {
"EmailService" should {
"be able to create an email with a mocked Messages" in {
implicit val messagesMock = mock[Messages]
messagesMock.apply(===("email.subject"), anyVarArg) returns "Mocked subject"
messagesMock.apply(===("email.message"), anyVarArg) returns "Mocked message"
val email = new EmailService().createEmail()
email mustEqual s"""Subject: Mocked subject. Message: Mocked message"""
}
}
}
But what If I want to test it with a running application, like this:
import org.specs2.mutable.Specification
import play.api.Logger
import play.api.i18n.Messages
import scaldi.play.ScaldiApplicationBuilder._
import service.EmailService
class EmailServiceTest extends Specification {
"EmailService" should {
"be able to create an email with an application running" in {
withScaldiApp() {
val email = new EmailService().createEmail()
Logger.error(email)
email mustEqual s"""Subject: Welcome. Message: Welcome to the future"""
}
}
}
}
My messages.en file:
email.subject=Welcome
email.message=Welcome to the future
If I try to run this test I get:
[play-i18n] $ test
[info] Compiling 1 Scala source to /source/tmp/play-i18n/target/scala-2.11/test-classes...
[error] /source/tmp/play-i18n/test/EmailServiceTest.scala:24: could not find implicit value for parameter messages: play.api.i18n.Messages
[error] val email = new EmailService().createEmail()
[error] ^
[error] one error found
[error] (test:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Jun 30, 2015 8:04:03 PM
So, how do I get hold of the "real" Messages/MessagesApi class in this case?
cheers,
Ulrik