在测试期间,我如何伪造MailerPlugin.send以便我可以收到发送的电子邮件?

时间:2015-01-26 13:44:50

标签: scala testing playframework stub playframework-2.3

在测试期间,我希望在Play 2.3中伪造play.api.libs.mailer.MailerPlugin,以便我可以获取正在发送的电子邮件。我该怎么做?

应用代码

package services
import play.api.libs.mailer._
import play.api.Play.current

object EmailService {
  def sendUserNotification(to: String, subject: String, content: String): Unit = {
    val email = Email(
      "subject",
      "Admin <admin@test.com>",
      Seq(to),
      bodyHtml = Some(s"""<html>
      | <body>
      |   $content
      | </body>
      | </html>
      | """.stripMargin)
    )
    // Should like to fake this from tests, but how?
    MailerPlugin.send(email)
  }
}

测试代码

object Test {
  def testEmail(): Unit = {
    // How do I get hold of the sent email?
    EmailService.sendUserNotification("user@user.com", "Test", "Testing...")
  }
}

1 个答案:

答案 0 :(得分:0)

你有很多选择:

最简单也许最好的一个:从副作用中分离出函数,将创建逻辑分离为一个单独的方法并为其编写测试,然后可以从影响sendUserNotification

的一侧调用它
def createUserNotification(...): Email = ...

def sendUserNotification(...): Unit = 
  MailerPlugin.send(createUserNotification(...))

如果您已经编写了许多使用您的服务的控制器等,并且您想编写测试,检查那些发送电子邮件是否有一组要禁用的插件类名和一组要在{{上启用的插件类名。 1}来自play test utils,所以你可以在你的测试中提供FakeApplication的假实现,它只收集已发送的电子邮件。 EmailPlugin接受play.api.test.WithApplication到其运行测试时将使用的构造函数。

您可以依赖注入实际的邮件操作,方法是将电子邮件插件注入您使用它的位置,作为构造函数参数或作为抽象方法或值,甚至是传递给send方法的函数。例如:

FakeApplication

sendUserNotification(...)(send: Email => Unit)