根据该文件,进行单元测试控制器,我需要让我的控制器的特点,然后覆盖的方法如何发挥框架的单元测试控制器方法
http://www.playframework.com/documentation/2.2.0/ScalaTest
但是,如果我重写我的方法,我实际上没有测试我的逻辑。我可能没有抓住一些东西,但我不明白这个单元如何测试我的控制器的方法?
根据该文件,进行单元测试控制器,我需要让我的控制器的特点,然后覆盖的方法如何发挥框架的单元测试控制器方法
http://www.playframework.com/documentation/2.2.0/ScalaTest
但是,如果我重写我的方法,我实际上没有测试我的逻辑。我可能没有抓住一些东西,但我不明白这个单元如何测试我的控制器的方法?
正如链接中提到的,控制器在使用时是scala对象而不是类,所以不能像类那样实例化。通过把它变成一个特质,你可以创建一个你可以在你的测试中实例化的测试类。不需要重写方法。
要使用链接中的示例,我们在这里创建一个TestController类,该类具有与ExampleController对象相同的行为。我们不需要重写我们的索引方法,因为我们继承了特质的行为。
主文件
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"
}
}
}
这里是我的,你如何检查是否一些网址可
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")}
}
}
与本例中的问题简单的例子您提供的链接是,它并没有真正显示让您的控制器执行的好处特质内的ntation。换句话说,通过直接测试控制器伴侣对象,可以在不使用特征的情况下完成相同的示例。
将控制器逻辑放在特征中的好处是,它允许您覆盖控制器可能与模拟实现/值有关的依赖关系。
例如,你可以定义一个控制器:
trait MyController extends Controller {
lazy val someService : SomeService = SomeServiceImpl
}
object MyController extends MyController
并在测试,您可以覆盖服务依存关系:
val controller = new MyController {
override lazy val someService = mockService
}