ScalaTest PlayFramework

ScalaTest PlayFramework

在学习游戏框架的同时尝试做一些 TDD:

class ContentFetching extends PlaySpec with BeforeAndAfter with MockFactory
{
  private val service = ContentService

  private val languages = List(Language(Some(1), "en", "English", "Placeholder"),
                               Language(Some(2), "de", "Deutsch", "Platzhalter")
                              )

  "find" must
  {
    "fail if languageCode is invalid" in
    {
      val fakeRepository = mock[LanguageRepositoryTrait]
      (fakeRepository.get _).expects().returning(languages)

      fakeRepository.get must have length 3

      service.find("fr") must be Result.NotFound

    }
  }
}

ContentService 会调用:

def fourOhFour() = NotFound(s"Oops, content could not be found")

但断言 service.find("fr") must be Result.NotFound 无法编译。为什么会这样以及如何测试呢? 这是整个 contentService(根据要求)可悲的是,它目前扩展了 Controller,因为我没有找到 return 一个 Action 的其他方法。其实我用的是MVC,还有一个Service + repository-layer:

class ContentServiceComponent(languageRepository: LanguageRepositoryTrait, nodeRepository: NodeRepositoryTrait) extends Controller
{
  def find(language: String) = Action
  {
    languageRepository.get().map(l => l.code).contains(language) match
    {
      case true => Ok(s"Homepage for $language")
      case false => fourOhFour()
    }
  }

  def fourOhFour() = NotFound(s"Oops, content could not be found")
}

object ContentService extends ContentServiceComponent(LanguageRepository, NodeRepository)

find 而不是 returns Action 可以 return Option

def find(language: String): Option[String] =
  {
    languageRepository.get().map(l => l.code).contains(language) match
    {
      case true => Some(s"Homepage for $language")
      case _ => None
    }
  }

所以您可以在 Controller 中按如下方式处理它:

def index(language:String) = Action{

ContentService.find(language) match{
  case Some(content) => Ok(content)
  case _ => NotFound(s"Oops, content could not be found")
}

}

你可以像这样做测试用例:

class ContentFetching extends PlaySpec with BeforeAndAfter with MockFactory
{


  val languages = List(Language(Some(1), "en", "English",Placeholder"),Language(Some(2), "de", "Deutsch", "Platzhalter")
                              )

val languagesRepositoryMockHere = new LanguageRepositoryTrait{ 
    override def get =  languages  //I don't  know the implementations
}

  "find" must
  {
    "fail if languageCode is invalid" in
    {
       private val service = new ContentServiceComponent(languagesRepositoryMockHere,nodeRepositoryMockHere)


      service.find("fr") shouldBe None

    }
  }
}

未经测试,但可以提供参考。

干杯。

service.find("fr") 来自 Play 控制器 returns 结果

也许您正在比较 Result.Status 类型的结果?

你可以使用 play.api.helper 吗?

status(of: Future[Result]) = Await.result(of, timeout.duration).header.status

而不是

service.find("fr") must be Result.NotFound

试试这样的东西?

status(service.find("fr")) must be NOT_FOUND

NOT_FOUND 是一个 play.api.http.Status 值,仅映射到标准 HTTP 状态代码 404