占位符,方便记下一个想法,但是还没有实现或者还没准备好。
待测试(Pending Test)这个思想我觉得在实际中会用的比较多。pending是一个占位符,可以将尚未实现或定义的测试以pending来填充。Pending Test实际上就是利用pending来将测试标记为TODO的。如下面的例子:
class AlbumSpec extends FunSpec with Matchers with GivenWhenThen { describe("An Album") { it("can add an Artist to the album at construction time") {pending} it("can add opt to not have any artists at construction time") {pending} } }运行测试,得到如下结果:
[info]AlbumSpec: [info]An Album [info]- can add an Artist to the album at construction time (pending) [info]- can add opt to not have any artists at construction time (pending)可以看到,测试都被标记为了pending。
我们可以将pending关键字一直放在测试的最下面,直到一个测试完全的写完。如下面的例子:
class AlbumSpec extends FunSpec with ShouldMatchers { describe("An Album") { it("can add an Artist to the album at construction time") { val album = new Album("Thriller", 1981, new Artist("Michael", "Jackson")) info("Making sure that Michael Jackson is indeed the artist of Thriller") pending } it("can add opt to not have any artists at construction time") {pending} } }运行测试,如我们所料,将输出下面的结果:
[info]AlbumSpec: [info]An Album [info]- can add an Artist to the album at construction time (pending) [info] + Making sure that Michael Jackson is indeed the artist of Thriller [info]- can add opt to not have any artists at construction time (pending)开发人员不确定测试的有效性,或者生产代码已经淘汰了,抑或生产代码太复杂,所以暂时需要忽略这些测试代码。
可能有这么一种情境:某个测试案例,可能由于生产代码被修改而处于一种可有可无的状态。如果留着,在进行测试的时候浪费执行时间,如果删除又怕在后期还要使用到。此时可以使用ignore来标记该测试,这样在执行test指令时将不会运行它,但同时又将它保存下来了。如下面的例子:
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")) album.artist.firstName should be("Michael") } ignore("can add a Producer to an album at construction time") { new Album("Breezin\'", 1976, new Artist("George", "Benson")) //TODO: Figure out the implementation of an album producer } } }运行测试,将得到如下的输出:
[info]AlbumSpec: [info]An Album [info]- can add an Artist to the album at construction time [info]- can add a Producer to an album at construction time !!! IGNORED !!!这是因为第二个测试can add a Producer to an album at construction time中的it被ignore给替代了,在运行测试时,它将被忽略。在上面的输出结果中的反映就是在测试名后面加上了!!! IGNORED !!!。如果要恢复这个测试,只需要将ignore替换成it就好了。
标记(Tagging)功能给测试加上标签,这样就可以分组运行测试了。标记可以在下面这些场景中运用:
你想跳过某些很费时的测试某些测试是检查一些相关的功能需要在一起执行你想给测试分成单元测试、综合测试、验收测试等分类时不同的测试接口对标记都有自己的实现,但都是使用字符串来进行分类标记。如下面的例子:
it("can add an Artist to the album at construction time", Tag("construction")) { // 其它代码 }上面的例子是在FunSpec接口中的实现,给can add an Artist to the album at construction time这个测试添加了construction的标记。
在SBT中运行特定标记的测试也有一些需要注意的地方:
SBT的test命令暂时还不能支持运行指定标签的测试 SBT支持多种测试框架,要使test命令能够按指定标签执行测试,则需要所有SBT支持的测试框架都支持标签功能,现在ScalaTest、Specs2都支持了标签,但ScalaCheck目前并不支持标签功能。
SBT的test-only命令是支持执行指定标签的测试的 可以用下例中的方式使用test-only命令来运行指定的测试: test-only AlbumTest – -n construction
在待测试类名的后面加上–再加上n再加上标签,来指行指定的测试(有多个标签 则需要用双引号"将标签包围起来)。如果要排除某个标签,将前面说的n换成l即可。