Writing functional tests with specs2

Writing functional tests with specs2

通过ScalaTest编写功能性测试

Play提供了一系列的类和简洁的方法来帮助实现功能性测试。大多数可以在play.api.test包或Helpers对象中找到。ScalaTest + Play集成库位ScalaTest构建了这种测试支持。

你可以通过以下的模块导入来访问所有的Play的内建测试支持和ScalaTest + Play:

  1. import org.scalatest._
  2. import play.api.test._
  3. import play.api.test.Helpers._
  4. import org.scalatestplus.play._

FakeApplication

Play经常性需要一个运行的Application作为上下文:其通常通过play.api.Play.current提供。

为了为测试提供一个环境,Play提供了一个FakeApplication类其可以和一个不同的Global对象,附加配置或附加的插件一起被配置。

  1. val fakeApplicationWithGlobal = FakeApplication(withGlobal = Some(new GlobalSettings() {
  2. override def onStart(app: Application) { println("Hello world!") }
  3. }))

如果所有或大多数你的测试类需要一个FakeApplication,并且它们可以共享相同的FakeApplication,与OneAppPerSuite特性混合使用。你可以通过定制FakeApplication来如果这个例子展示的那样重写PP:

  1. class ExampleSpec extends PlaySpec with OneAppPerSuite {
  2. //重写app如果你需要一个不仅有默认参数的FakeApplication。
  3. implicit override lazy val app: FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled")
  6. )
  7. "The OneAppPerSuite trait" must {
  8. "provide a FakeApplication" in {
  9. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  10. }
  11. "start the FakeApplication" in {
  12. Play.maybeApplication mustBe Some(app)
  13. }
  14. }
  15. }

如果你需要每个测试去获取它自己的FakeApplication而不是共享相同的,请使用OneAppPerTest来替代:

  1. class ExampleSpec extends PlaySpec with OneAppPerTest {
  2. //重写app如果你需要一个不仅有默认参数的FakeApplication。
  3. implicit override def newAppForTest(td: TestData): FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled")
  6. )
  7. "The OneAppPerTest trait" must {
  8. "provide a new FakeApplication for each test" in {
  9. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  10. }
  11. "start the FakeApplication" in {
  12. Play.maybeApplication mustBe Some(app)
  13. }
  14. }
  15. },

ScalaTest + Play提供了OneAppPerSuite和OneAppPerTest的原因是来允许你去选择共享性策略来让你的测试最快的运行。如果你想让应用状态在成功的测试之间保持,你将需要使用OneAppPerSuite.如果每个测试需要一个清空的状态,你可以使用OneAppPerTest或使用OneAppPerSuite,但需要在每个测试结束来清理状态。甚至,如果你的测试集将尽可能快的运行多个测试类共享这个相同的应用,你可以定义一个主集合起与OneAppPerSuite混用和内嵌的集合其和ConfiguredApp混用,正如在ConfiguredApp的文档中的例子展示的那样。你可以使用任意策略来实你的测试集最快的运行。

和一个服务器一起测试

有时候你想使用真的HTTP栈来进行测试。如果你的测试类中的所有测试能够重用这个相同的服务器实例,你可以通过与OneServerPerSuite一起混用(其将为这个集合提供一个新的FakeApplication):

  1. class ExampleSpec extends PlaySpec with OneServerPerSuite {
  2. // 重写app如果你需要一个不仅有默认参数的FakeApplication。
  3. implicit override lazy val app: FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/") => Action { Ok("ok") }
  8. }
  9. )
  10. "test server logic" in {
  11. val myPublicAddress = s"localhost:$port"
  12. val testPaymentGatewayURL = s"http://$myPublicAddress"
  13. //这个测试支付网关在它返回一个值之前需要针对这个服务器的一个回调...
  14. val callbackURL = s"http://$myPublicAddress/callback"
  15. // 从play.api.test.FutureAwaits中等待调用
  16. val response = await(WS.url(testPaymentGatewayURL).withQueryString("callbackURL" -> callbackURL).get())
  17. response.status mustBe (OK)
  18. }
  19. }

如果你的测试类中的所有测试需要不同的服务器实例,请使用OneServerPerTest来代替(其将同时为这个测试集提供一个新的FakeApplication):

  1. class ExampleSpec extends PlaySpec with OneServerPerTest {
  2. //重写newAppForTest如果你需要一个不仅有默认参数的FakeApplication.
  3. override def newAppForTest(testData: TestData): FakeApplication =
  4. new FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/") => Action { Ok("ok") }
  8. }
  9. )
  10. "The OneServerPerTest trait" must {
  11. "test server logic" in {
  12. val myPublicAddress = s"localhost:$port"
  13. val testPaymentGatewayURL = s"http://$myPublicAddress"
  14. //测试支付网关在返回一个结果之前需要针对这个服务器的一个回调...
  15. val callbackURL = s"http://$myPublicAddress/callback"
  16. // await is from play.api.test.FutureAwaits
  17. val response = await(WS.url(testPaymentGatewayURL).withQueryString("callbackURL" -> callbackURL).get())
  18. response.status mustBe (OK)
  19. }
  20. }
  21. }

OneServerPerSuite和OneServerPerTest特性为该服务器运行为port域提供了port号。其默认是19001,甚至你可以通过重写端口或设定系统属性testserver.port来更改。其将非常有用当与持续集成服务器集成在一起,因此端口可以被动态的为每个构建所保留。

你同时可以如之前例子所展示的那样通过重写app来自定义FakeApplication.

最后,如果允许多个测试类来共享这个相同的服务器将会给你比OneServerPerSuite或OneServerPerTest方式更好的性能,正如ConfiguredServer文档中的例子所展示的那样,你可以定义一个主测试集其与OneServePerSuite混用和嵌入式测试集其与ConfiguredServer混用。

和一个网页浏览器一起测试

ScalaTest + Play库构基于Selenium DSL构建以使其简单的从网页浏览器中测试你的Play应用。
混合OneBrowserPerSuite到你的测试类中以便使用一个相同的浏览器来运行你的测试类中所有的测试。你将同时需要与一个BrowserFactory特性其将提供一个Selenium web驱动混用:ChromeFactory, FirefoxFactory, HtmlUnitFactory, InternetExplorerFactory, SafariFactory之一。

更进一步为了混合入一个BrowserFactory,你将需要混合进一个ServerProvider特性其提供了一个TestServer: ChromeFactory, FirefoxFactory, HtmlUnitFactory, InternetExplorerFactory, SafariFactory之一。

比如,以下的测试类混合进OneServerPerSuite和HtmUnitFactory:

  1. class ExampleSpec extends PlaySpec with OneServerPerSuite with OneBrowserPerSuite with HtmlUnitFactory {
  2. //重写app如果你需要一个不仅有默认参数的FakeApplication.
  3. implicit override lazy val app: FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/testing") =>
  8. Action(
  9. Results.Ok(
  10. "<html>" +
  11. "<head><title>Test Page</title></head>" +
  12. "<body>" +
  13. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  14. "</body>" +
  15. "</html>"
  16. ).as("text/html")
  17. )
  18. }
  19. )
  20. "The OneBrowserPerTest trait" must {
  21. "provide a web driver" in {
  22. go to (s"http://localhost:$port/testing")
  23. pageTitle mustBe "Test Page"
  24. click on find(name("b")).value
  25. eventually { pageTitle mustBe "scalatest" }
  26. }
  27. }
  28. }

如果你的每个测试需要一个新的浏览器实例,请使用OneBrowserPerTest来替代。比如OneBrowserPerSuite,你将需要同时与一个ServerProvider和BrowserFactory来混用:

  1. class ExampleSpec extends PlaySpec with OneServerPerTest with OneBrowserPerTest with HtmlUnitFactory {
  2. //重写newAppForTest如果你需要一个不仅有默认参数的FakeApplication.
  3. override def newAppForTest(testData: TestData): FakeApplication =
  4. new FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/testing") =>
  8. Action(
  9. Results.Ok(
  10. "<html>" +
  11. "<head><title>Test Page</title></head>" +
  12. "<body>" +
  13. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  14. "</body>" +
  15. "</html>"
  16. ).as("text/html")
  17. )
  18. }
  19. )
  20. "The OneBrowserPerTest trait" must {
  21. "provide a web driver" in {
  22. go to (s"http://localhost:$port/testing")
  23. pageTitle mustBe "Test Page"
  24. click on find(name("b")).value
  25. eventually { pageTitle mustBe "scalatest" }
  26. }
  27. }
  28. }

如果你需要多个测试类来共享这个相同的浏览器实例,混合OneBrowserPerSuite进一个主测试集和混合ConfiguredBrowser进多个内嵌的测试集。内嵌的测试集将一起共享相同的浏览器。请参考ConfiguredBrowser特性的文档中的例子。

在多浏览器中运行相同的测试

如果你想在多浏览器中运行测试,以保证你的应用可以在所有你支持的浏览器中正常的工作,你可以使用AllBrowserPerSuite或AllBrowsersPerTest特性。这些特性都声明了一个IndexedSeq[BrowserInfo]特性和一个抽象的sharedTests方法其拥有一个BrowerInfo.browsers域指定了那个浏览器你想让你的测试在其中运行。默认的是Chrome, Firefox, Internet Explorer, HtmlUnit和Safari. 你可以重写browsers如果默认的不符合你的需求.你在sharedTests方法中嵌入你想在多浏览器中运行的测试,将浏览器的名字置于每个测试名的后面(浏览器名字是可用的从BrowserInfo传入进sharedTests.)这里有一个使用AllBrowsersPerSuite的例子:

  1. class ExampleSpec extends PlaySpec with OneServerPerSuite with AllBrowsersPerSuite {
  2. //重写App如果你需要一个不仅有默认参数的FakeApplication.
  3. implicit override lazy val app: FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/testing") =>
  8. Action(
  9. Results.Ok(
  10. "<html>" +
  11. "<head><title>Test Page</title></head>" +
  12. "<body>" +
  13. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  14. "</body>" +
  15. "</html>"
  16. ).as("text/html")
  17. )
  18. }
  19. )
  20. def sharedTests(browser: BrowserInfo) = {
  21. "The AllBrowsersPerSuite trait" must {
  22. "provide a web driver " + browser.name in {
  23. go to (s"http://localhost:$port/testing")
  24. pageTitle mustBe "Test Page"
  25. click on find(name("b")).value
  26. eventually { pageTitle mustBe "scalatest" }
  27. }
  28. }
  29. }
  30. }

所有被sharedTests所声明的测试将被在browsers域中提到的所有浏览器一起运行,只要它们在客户端系统中是可用的。为任何浏览器其不存在于客户端系统的测试将会自动被取消。注意你需要手动的为测试名称追加browser.name以保障这个集合内的每个测试都有一个独立的名字(ScalaTest需要它).如果你保留其空白,当你运行你的测试的时候将得到一个重复测试名字的错误。

AllBrowsersPerSuite 将为每种类型的浏览器创建一个单独的实例并为在sharedTests中声明的所有测试中使用。如果你想要每个测试去拥有它自己的,全新品牌的浏览器实例,请使用AllBrowsersPerTest来替代:

  1. class ExampleSpec extends PlaySpec with OneServerPerSuite with AllBrowsersPerTest {
  2. //重写app如果你需要一个不仅有默认参数的FakeApplication.
  3. implicit override lazy val app: FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/testing") =>
  8. Action(
  9. Results.Ok(
  10. "<html>" +
  11. "<head><title>Test Page</title></head>" +
  12. "<body>" +
  13. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  14. "</body>" +
  15. "</html>"
  16. ).as("text/html")
  17. )
  18. }
  19. )
  20. def sharedTests(browser: BrowserInfo) = {
  21. "The AllBrowsersPerTest trait" must {
  22. "provide a web driver" + browser.name in {
  23. go to (s"http://localhost:$port/testing")
  24. pageTitle mustBe "Test Page"
  25. click on find(name("b")).value
  26. eventually { pageTitle mustBe "scalatest" }
  27. }
  28. }
  29. }
  30. }

尽管AllBrowserPerSuite和AllBrowsersPerTest都会针对不提供的浏览器类型而取消测试,这些测试
仍将在输出中显示为被取消。为了清理这些不必要的输出,你可以如下例子所示来通过重写browsers来排除那些永远不会被支持的网页浏览器:

  1. class ExampleOverrideBrowsersSpec extends PlaySpec with OneServerPerSuite with AllBrowsersPerSuite {
  2. override lazy val browsers =
  3. Vector(
  4. FirefoxInfo(firefoxProfile),
  5. ChromeInfo
  6. )
  7. //重写app如果你需要一个不仅有默认参数的FakeApplication.
  8. implicit override lazy val app: FakeApplication =
  9. FakeApplication(
  10. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  11. withRoutes = {
  12. case ("GET", "/testing") =>
  13. Action(
  14. Results.Ok(
  15. "<html>" +
  16. "<head><title>Test Page</title></head>" +
  17. "<body>" +
  18. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  19. "</body>" +
  20. "</html>"
  21. ).as("text/html")
  22. )
  23. }
  24. )
  25. def sharedTests(browser: BrowserInfo) = {
  26. "The AllBrowsersPerSuite trait" must {
  27. "provide a web driver" + browser.name in {
  28. go to (s"http://localhost:$port/testing")
  29. pageTitle mustBe "Test Page"
  30. click on find(name("b")).value
  31. eventually { pageTitle mustBe "scalatest" }
  32. }
  33. }
  34. }
  35. }

之前的测试类仅将尝试和Firefox,chrome一起运行共享的测试(并自动化的取消测试如果一个浏览器是不可用的)。

PlaySpec

PlaySpec为Play测试提供了一个便捷的“超集”ScalaTest基础类,你可以通过扩展
PlaySpec来自动得到WordSpec, MustMatchers, OptionValues, 和 WsScalaTestClient:

  1. class ExampleSpec extends PlaySpec with OneServerPerSuite with ScalaFutures with IntegrationPatience {
  2. //重写app如果你需要一个不仅有默认参数的FakeApplication.
  3. implicit override lazy val app: FakeApplication =
  4. FakeApplication(
  5. additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
  6. withRoutes = {
  7. case ("GET", "/testing") =>
  8. Action(
  9. Results.Ok(
  10. "<html>" +
  11. "<head><title>Test Page</title></head>" +
  12. "<body>" +
  13. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  14. "</body>" +
  15. "</html>"
  16. ).as("text/html")
  17. )
  18. }
  19. )
  20. "WsScalaTestClient's" must {
  21. "wsUrl works correctly" in {
  22. val futureResult = wsUrl("/testing").get
  23. val body = futureResult.futureValue.body
  24. val expectedBody =
  25. "<html>" +
  26. "<head><title>Test Page</title></head>" +
  27. "<body>" +
  28. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  29. "</body>" +
  30. "</html>"
  31. assert(body == expectedBody)
  32. }
  33. "wsCall works correctly" in {
  34. val futureResult = wsCall(Call("get", "/testing")).get
  35. val body = futureResult.futureValue.body
  36. val expectedBody =
  37. "<html>" +
  38. "<head><title>Test Page</title></head>" +
  39. "<body>" +
  40. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  41. "</body>" +
  42. "</html>"
  43. assert(body == expectedBody)
  44. }
  45. }
  46. }

你可以将任何之前提到的特性混合进PlaySpec.
在之前例子中所展示的那些测试类中,测试类中的所有或大多数测试需要相同的样式。这个很常见但不总是这样。如果相同的测试类中不同的测试需要不同的样式,与特性MixedFixtures混用。然后使用这些无参功能: App, Server, Chrome, Firefox, HtmlUnit, InternetExplorer, 或 Safari之一来给予每个测试器需要的样式.
你不可以混合MixedFixtures进PlaySpec。因为MixedFixtures需要一个ScalaTest fixture.Suite但PlaySpec仅仅是一个不同的集合。如果你需要针对混合样式的一个简洁的基础类。通过扩展MixedPlaySpec来替代。这里是一个例子:

  1. // MixedPlaySpec 已经混合进MixedFixtures
  2. class ExampleSpec extends MixedPlaySpec {
  3. // 一些帮助器方法
  4. def fakeApp[A](elems: (String, String)*) = FakeApplication(additionalConfiguration = Map(elems:_*),
  5. withRoutes = {
  6. case ("GET", "/testing") =>
  7. Action(
  8. Results.Ok(
  9. "<html>" +
  10. "<head><title>Test Page</title></head>" +
  11. "<body>" +
  12. "<input type='button' name='b' value='Click Me' onclick='document.title=\"scalatest\"' />" +
  13. "</body>" +
  14. "</html>"
  15. ).as("text/html")
  16. )
  17. })
  18. def getConfig(key: String)(implicit app: Application) = app.configuration.getString(key)
  19. // 如果一个测试进需要一个FakeApplication,使用"new APP":
  20. "The App function" must {
  21. "provide a FakeApplication" in new App(fakeApp("ehcacheplugin" -> "disabled")) {
  22. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  23. }
  24. "make the FakeApplication available implicitly" in new App(fakeApp("ehcacheplugin" -> "disabled")) {
  25. getConfig("ehcacheplugin") mustBe Some("disabled")
  26. }
  27. "start the FakeApplication" in new App(fakeApp("ehcacheplugin" -> "disabled")) {
  28. Play.maybeApplication mustBe Some(app)
  29. }
  30. }
  31. // 如果一个测试需要一个FakeApplicaiton并运行TestServer,请使用"new Server":
  32. "The Server function" must {
  33. "provide a FakeApplication" in new Server(fakeApp("ehcacheplugin" -> "disabled")) {
  34. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  35. }
  36. "make the FakeApplication available implicitly" in new Server(fakeApp("ehcacheplugin" -> "disabled")) {
  37. getConfig("ehcacheplugin") mustBe Some("disabled")
  38. }
  39. "start the FakeApplication" in new Server(fakeApp("ehcacheplugin" -> "disabled")) {
  40. Play.maybeApplication mustBe Some(app)
  41. }
  42. import Helpers._
  43. "send 404 on a bad request" in new Server {
  44. import java.net._
  45. val url = new URL("http://localhost:" + port + "/boom")
  46. val con = url.openConnection().asInstanceOf[HttpURLConnection]
  47. try con.getResponseCode mustBe 404
  48. finally con.disconnect()
  49. }
  50. }
  51. // 如果一个测试需要一个FakeApplication,运行TestServer,和Selenium HtmlUnit驱动请使用"new HtmlUnit":
  52. "The HtmlUnit function" must {
  53. "provide a FakeApplication" in new HtmlUnit(fakeApp("ehcacheplugin" -> "disabled")) {
  54. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  55. }
  56. "make the FakeApplication available implicitly" in new HtmlUnit(fakeApp("ehcacheplugin" -> "disabled")) {
  57. getConfig("ehcacheplugin") mustBe Some("disabled")
  58. }
  59. "start the FakeApplication" in new HtmlUnit(fakeApp("ehcacheplugin" -> "disabled")) {
  60. Play.maybeApplication mustBe Some(app)
  61. }
  62. import Helpers._
  63. "send 404 on a bad request" in new HtmlUnit {
  64. import java.net._
  65. val url = new URL("http://localhost:" + port + "/boom")
  66. val con = url.openConnection().asInstanceOf[HttpURLConnection]
  67. try con.getResponseCode mustBe 404
  68. finally con.disconnect()
  69. }
  70. "provide a web driver" in new HtmlUnit(fakeApp()) {
  71. go to ("http://localhost:" + port + "/testing")
  72. pageTitle mustBe "Test Page"
  73. click on find(name("b")).value
  74. eventually { pageTitle mustBe "scalatest" }
  75. }
  76. }
  77. // 如果一个测试需要一个FakeApplication,运行TestServer,和Selenium Firefox驱动请使用"new Firefox":
  78. "The Firefox function" must {
  79. "provide a FakeApplication" in new Firefox(fakeApp("ehcacheplugin" -> "disabled")) {
  80. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  81. }
  82. "make the FakeApplication available implicitly" in new Firefox(fakeApp("ehcacheplugin" -> "disabled")) {
  83. getConfig("ehcacheplugin") mustBe Some("disabled")
  84. }
  85. "start the FakeApplication" in new Firefox(fakeApp("ehcacheplugin" -> "disabled")) {
  86. Play.maybeApplication mustBe Some(app)
  87. }
  88. import Helpers._
  89. "send 404 on a bad request" in new Firefox {
  90. import java.net._
  91. val url = new URL("http://localhost:" + port + "/boom")
  92. val con = url.openConnection().asInstanceOf[HttpURLConnection]
  93. try con.getResponseCode mustBe 404
  94. finally con.disconnect()
  95. }
  96. "provide a web driver" in new Firefox(fakeApp()) {
  97. go to ("http://localhost:" + port + "/testing")
  98. pageTitle mustBe "Test Page"
  99. click on find(name("b")).value
  100. eventually { pageTitle mustBe "scalatest" }
  101. }
  102. }
  103. // // 如果一个测试需要一个FakeApplication,运行TestServer,和Selenium Safari驱动请使用"new Safari":
  104. "The Safari function" must {
  105. "provide a FakeApplication" in new Safari(fakeApp("ehcacheplugin" -> "disabled")) {
  106. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  107. }
  108. "make the FakeApplication available implicitly" in new Safari(fakeApp("ehcacheplugin" -> "disabled")) {
  109. getConfig("ehcacheplugin") mustBe Some("disabled")
  110. }
  111. "start the FakeApplication" in new Safari(fakeApp("ehcacheplugin" -> "disabled")) {
  112. Play.maybeApplication mustBe Some(app)
  113. }
  114. import Helpers._
  115. "send 404 on a bad request" in new Safari {
  116. import java.net._
  117. val url = new URL("http://localhost:" + port + "/boom")
  118. val con = url.openConnection().asInstanceOf[HttpURLConnection]
  119. try con.getResponseCode mustBe 404
  120. finally con.disconnect()
  121. }
  122. "provide a web driver" in new Safari(fakeApp()) {
  123. go to ("http://localhost:" + port + "/testing")
  124. pageTitle mustBe "Test Page"
  125. click on find(name("b")).value
  126. eventually { pageTitle mustBe "scalatest" }
  127. }
  128. }
  129. // 如果一个测试需要一个FakeApplication,运行TestServer,和Selenium Chrome驱动请使用"new Chrome":
  130. "The Chrome function" must {
  131. "provide a FakeApplication" in new Chrome(fakeApp("ehcacheplugin" -> "disabled")) {
  132. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  133. }
  134. "make the FakeApplication available implicitly" in new Chrome(fakeApp("ehcacheplugin" -> "disabled")) {
  135. getConfig("ehcacheplugin") mustBe Some("disabled")
  136. }
  137. "start the FakeApplication" in new Chrome(fakeApp("ehcacheplugin" -> "disabled")) {
  138. Play.maybeApplication mustBe Some(app)
  139. }
  140. import Helpers._
  141. "send 404 on a bad request" in new Chrome {
  142. import java.net._
  143. val url = new URL("http://localhost:" + port + "/boom")
  144. val con = url.openConnection().asInstanceOf[HttpURLConnection]
  145. try con.getResponseCode mustBe 404
  146. finally con.disconnect()
  147. }
  148. "provide a web driver" in new Chrome(fakeApp()) {
  149. go to ("http://localhost:" + port + "/testing")
  150. pageTitle mustBe "Test Page"
  151. click on find(name("b")).value
  152. eventually { pageTitle mustBe "scalatest" }
  153. }
  154. }
  155. // 如果一个测试需要一个FakeApplication,运行TestServer,和Selenium InternetExplorer驱动请使用"new InternetExplorer":
  156. "The InternetExplorer function" must {
  157. "provide a FakeApplication" in new InternetExplorer(fakeApp("ehcacheplugin" -> "disabled")) {
  158. app.configuration.getString("ehcacheplugin") mustBe Some("disabled")
  159. }
  160. "make the FakeApplication available implicitly" in new InternetExplorer(fakeApp("ehcacheplugin" -> "disabled")) {
  161. getConfig("ehcacheplugin") mustBe Some("disabled")
  162. }
  163. "start the FakeApplication" in new InternetExplorer(fakeApp("ehcacheplugin" -> "disabled")) {
  164. Play.maybeApplication mustBe Some(app)
  165. }
  166. import Helpers._
  167. "send 404 on a bad request" in new InternetExplorer {
  168. import java.net._
  169. val url = new URL("http://localhost:" + port + "/boom")
  170. val con = url.openConnection().asInstanceOf[HttpURLConnection]
  171. try con.getResponseCode mustBe 404
  172. finally con.disconnect()
  173. }
  174. "provide a web driver" in new InternetExplorer(fakeApp()) {
  175. go to ("http://localhost:" + port + "/testing")
  176. pageTitle mustBe "Test Page"
  177. click on find(name("b")).value
  178. eventually { pageTitle mustBe "scalatest" }
  179. }
  180. }
  181. // 如果一个测试不需要任何的特殊样式,仅需要写成"in { () => ... "
  182. "Any old thing" must {
  183. "be doable without much boilerplate" in { () =>
  184. 1 + 1 mustEqual 2
  185. }
  186. }
  187. }

测试一个模板

因为一个模板是一个标准的Scala功能,你可以从你的测试中执行它,并检测结果:

  1. "render index template" in new App {
  2. val html = views.html.index("Coco")
  3. contentAsString(html) must include ("Hello Coco")
  4. }

测试一个控制器

You can call any Action code by providing a FakeRequest:
你可以通过提供一个FakRequest来调用任何Action代码:

  1. import scala.concurrent.Future
  2. import org.scalatest._
  3. import org.scalatestplus.play._
  4. import play.api.mvc._
  5. import play.api.test._
  6. import play.api.test.Helpers._
  7. class ExampleControllerSpec extends PlaySpec with Results {
  8. class TestController() extends Controller with ExampleController
  9. "Example Page#index" should {
  10. "should be valid" in {
  11. val controller = new TestController()
  12. val result: Future[SimpleResult] = controller.index().apply(FakeRequest())
  13. val bodyText: String = contentAsString(result)
  14. bodyText mustBe "ok"
  15. }
  16. }
  17. }

技术上讲,在这里你不需要WithApption,尽管使用它并不会产生任何不利影响。

测试一个路由

你可以通过让Router来做而不是你自己来调用Action:

  1. "respond to the index Action" in new App(fakeApplication) {
  2. val Some(result) = route(FakeRequest(GET, "/Bob"))
  3. status(result) mustEqual OK
  4. contentType(result) mustEqual Some("text/html")
  5. charset(result) mustEqual Some("utf-8")
  6. contentAsString(result) must include ("Hello Bob")
  7. }

测试一个模块

如果你使用一个SQL数据库,你可以通过使用inMemoryDatabase来用一个H2数据库的内存实例替换数据库连接。

val appWithMemoryDatabase = FakeApplication(additionalConfiguration = inMemoryDatabase("test"))
"run an application" in new App(appWithMemoryDatabase) {

      val Some(macintosh) = Computer.findById(21)

      macintosh.name mustEqual "Macintosh"
      macintosh.introduced.value mustEqual "1984-01-24"
}

测试WS调用

如果你正在调用一个网页服务,你可以使用WSTestClinet.这里两个调用可用,wsCall和wsUrl其将分别执行一个调用或字符串。注意他们期望在WithApplication的上下文里被调用。

wsCall(controllers.routes.Application.index()).get()

wsUrl("http://localhost:9000").get()