如何玩框架单元测试控制器方法

时间:2013-12-19 14:57:34

标签: unit-testing scala playframework-2.0

根据文档,对于单元测试控制器,我需要使我的控制器成为特征,然后覆盖方法

http://www.playframework.com/documentation/2.2.0/ScalaTest

但是,如果我覆盖我的方法,我实际上没有测试我的逻辑。我可能没有掌握一些东西,但我不知道这个单元如何测试我的控制器的方法?

3 个答案:

答案 0 :(得分:2)

您提供的链接中的示例问题在于它并没有真正显示将控制器实现在特征中的好处。换句话说,通过直接测试控制器伴随对象,可以在不使用特征的情况下完成相同的示例。

让控制器逻辑处于特征之内的好处是,它允许您覆盖控制器可能具有模拟实现/值的依赖关系。

例如,您可以将控制器定义为:

trait MyController extends Controller {
   lazy val someService : SomeService = SomeServiceImpl
}
object MyController extends MyController

在测试中,您可以覆盖服务依赖项:

val controller = new MyController {
  override lazy val someService = mockService
} 

答案 1 :(得分:0)

正如链接中所提到的,游戏中的控制器是scala对象而不是类,因此不能像类一样实例化。通过使其成为特征,您可以创建一个可以在测试中实例化的测试类。不需要覆盖方法。

要使用链接中的示例,我们在这里创建一个与ExampleController对象具有相同行为的TestController类。我们不需要覆盖索引方法,因为我们从特征继承了行为。

主档

trait ExampleController {
  this: Controller =>

  def index() = Action {
    Ok("ok")
  }
}

object ExampleController extends Controller with ExampleController

测试文件

object ExampleControllerSpec extends PlaySpecification with Results {

  class TestController() extends Controller with ExampleController

  "Example Page#index" should {
    "should be valid" in {
      val controller = new TestController()
      val result: Future[SimpleResult] = controller.index().apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      bodyText must be equalTo "ok"
    }
  }
}

答案 2 :(得分:0)

以下是我如何检查某个网址是否可用的简单示例

import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._

import play.api.test._
import play.api.test.Helpers._

/**
 * Set of tests which are just hitting urls and check
 * if response code 200 returned
 */
@RunWith(classOf[JUnitRunner])
class ActionsSanityCheck extends Specification {

  def checkIfUrlAccessible(url: String): Unit = {
    val appRoute = route(FakeRequest(GET, url)).get

    status(appRoute) must equalTo(OK)
    contentType(appRoute) must beSome.which(_ == "text/html")
  }

  "Application" should {

    "send 404 on a bad request" in new WithApplication {
      route(FakeRequest(GET, "/nowhere")) must beNone
    }

    "render the index page" in new WithApplication {checkIfUrlAccessible("/")}
    "render team page" in new WithApplication {checkIfUrlAccessible("/team")}
  }
}