ScalaTest——日志打印

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--ThenGiven相当于所给的前置条件,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

可以看到GivenWhenThenand里面的字符串都是以Informer的形式输出的,使用一个and将测试的内容分开了,加强了可读性。而GivenWhenThen是一个特质,可以被混入任何的类。GivenWhenThen使测试变得结构化,使得在测试时可以很好的组织思想。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值