2015-01-26 12 views
0

테스트하는 동안 Play 2.3에서 play.api.libs.mailer.MailerPlugin을 위조하여 전송할 이메일을 확보 할 수 있습니다. 어떻게해야합니까?테스트 중에 MailerPlugin.send를 위조하여 보낸 이메일을받을 수 있습니까?

가장 쉬운 어쩌면 최고의 하나 : 부작용 분리 기능, 작성을 분리

응용 프로그램 코드

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 <[email protected]>", 
     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("[email protected]", "Test", "Testing...") 
    } 
} 

답변

0

당신은 선택의 여지가 로직을 별도의 메소드에 넣고 테스트를 작성하면 부작용에서 호출 할 수 있습니다. sendUserNotification

def createUserNotification(...): Email = ... 

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

서비스를 이미 사용하는 많은 컨트롤러 등을 작성한 경우 전자 메일을 보내는 지 확인하는 테스트를 작성하려면 비활성화 할 플러그인 클래스 이름 집합과 사용할 수있는 플러그인 클래스 이름 집합이 있어야합니다. FakeApplication을 재생 테스트 유틸리티에서 가져온 것이므로 EmailPlugin의 가짜 구현을 테스트에 제공 할 수 있습니다.이 테스트는 보낸 전자 메일을 수집합니다. play.api.test.WithApplication은 테스트를 실행할 때 사용되는 FakeApplication을 생성자에 허용합니다.

전자 메일 플러그인을 생성자 매개 변수 또는 추상 메소드 또는 값 또는 전송 메소드로 전달하는 함수로 사용되는 위치에 삽입하는 전자 메일 플러그인을 만들면 종속성이 실제 메일 작업을 주입 할 수 있습니다 . 예를 들어 :

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

또는

trait EmailService { 
    def actuallySend(email: Email): Unit 
} 

object Emails extends EmailService { 
    def actuallySend(email: Email) = MailerPlugin.send(email) 
} 
+0

당신은 가짜 의미는'MailerPlugin' 당신은하지 않습니다? 필자가 언급 한 기술을 통해 가짜'MailerPlugin'을'FakeApplication'에 주입하는 결과를 낳았습니다. 이것이 내가 원하는 것입니다. 왜냐하면 테스트에서 가능한 한 많이 스텁을 피하기 때문입니다. – aknuds1

+0

정확히 무엇을 의미합니까! :) – johanandren