Informer在ScalaTest中是为了打印日志方便观察,跟debug语句很相似,但它可以放在任何地方来输出一些跟测试相关的信息。使用Informer只要调用info(String)方法即可。如下面的例子:
import org.scalatest.{FunSpec, ShouldMatchers} class AlbumTest extends FunSpec with ShouldMatchers { describe("An Album") { it("can add an Artist object to the album") { val album = new Album("Thriller", 1981, new Artist("Michael", "Jackson")) info("Test firstName should be Michael") album.artist.firstName should be("Thriller") } } }运行测试,得到如下输出结果:
[info] AlbumTest: [info] An Album [info] - can add an Artist object to the album [info] + Test firstName should be Michael [info] Run completed in 231 milliseconds. [info] Total number of tests run: 1 [info] Suites: completed 1, aborted 0 [info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0 [info] All tests passed. [success] Total time: 0 s, completed May 19, 2015 9:19:28 PM可以和简单的例子中的输出结果进行比较,发现在第4行多出了一个+ Test firstName should be Michael,这里就是Informer的输出了,以+开头。
在了解了Informer之后,GivenWhenThen就比较简单了。也是为了打印一些信息,以便观察哪里出问题了,类似于打印日志。
实际上,任何一个过程者可以被描述为Given--When--Then。Given相当于所给的前置条件,When相当于产生了某个动作或处于某种条件下,Then表示前面两个条件产生的结果。如下面的例子:
import core.{Artist, Album} import org.scalatest.{GivenWhenThen, ShouldMatchers, FunSpec} class AlbumSpec extends FunSpec with ShouldMatchers with GivenWhenThen { describe("An Album") { it("can add an Artist to the album at construction time") { Given("The album Thriller by Michael Jackson") val album = new Album("Thriller", 1981, new Artist("Michael", "Jackson")) When("the album\'s artist is obtained") val artist = album.artist Then("the artist obtained should be an instance of Artist") artist.isInstanceOf[Artist] should be(true) and("the artist's first name and last name should be Michael Jackson") artist.firstName should be("Michael") artist.lastName should be("Jackson") } }运行上面的测试,将产生如下的结果:
[info] AlbumSpec: [info] An Album [info] - can add an Artist to the album at construction time [info] + Given The album Thriller by Michael Jackson [info] + When the album's artist is obtained [info] + Then the artist obtained should be an instance of Artist [info] + And the artist's first name and last name should be Michael Jackson [info] Run completed in 216 milliseconds. [info] Total number of tests run: 1 [info] Suites: completed 1, aborted 0 [info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0 [info] All tests passed. [success] Total time: 0 s, completed May 19, 2015 9:31:47 PM可以看到Given、When、Then、and里面的字符串都是以Informer的形式输出的,使用一个and将测试的内容分开了,加强了可读性。而GivenWhenThen是一个特质,可以被混入任何的类。GivenWhenThen使测试变得结构化,使得在测试时可以很好的组织思想。