ScalaTest——日志打印 布满荆棘的人生 2022-05-12 15:10 261阅读 0赞 ##### 5.1 Informers日志 ##### 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的输出了,以`+`开头。 ##### 5.2 GivenWhenThen日志 ##### 在了解了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`使测试变得结构化,使得在测试时可以很好的组织思想。
还没有评论,来说两句吧...