class FirstTest extends WordSpec with MustMatchers { "A Stack" should { "pop values in last-in-first-out order" in { val stack = mutable.Stack.empty[Int] stack.push(1) stack.push(2) stack.pop() mustBe 2 stack.pop() mustBe 1 } "throw NoSuchElementException if an empty stack is popped" in { val emptyStack = mutable.Stack.empty[Int] assertThrows[NoSuchElementException] { emptyStack.pop() } } } }
运行测试有两种方式:
使用test命令运行所有测试
使用testOnly命令运行单个测试。
在sbt中输入testOnly firstFirstTest运行刚写好的第一个测试,结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
[IJ]scalatest > testOnly first.FirstTest [info] Compiling 1 Scala source to /opt/workspace/scala-applications/scalatest/target/scala-2.12/test-classes ... [info] Done compiling. [info] FirstTest: [info] A Stack [info] - should pop values in last-in-first-out order [info] - should throw NoSuchElementException if an empty stack is popped [info] Run completed in 344 milliseconds. [info] Total number of tests run: 2 [info] Suites: completed 1, aborted 0 [info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0 [info] All tests passed. [success] Total time: 2 s, completed 2018-8-2 18:29:14
OptionValues特质提供了一个隐式转换,将一个 value 方法添加到 Option[T] 类型上。若 Option 是有定义的,则 value 方法将返回值,就和调用 .get 一样;若没有,则抛出 TestFailedException 异常,而不是调用 get 方法时抛出的 NoSuchElementException 异常。同时,ScalaTest会输出更友好的错误显示:**The Option on which value was invoked was not defined.**,而不是输出一大堆的错误异常栈而打乱正常的测试输出。
使用.value
1 2 3 4 5 6 7 8 9 10 11 12
[info] FirstTest: [info] option [info] - should value *** FAILED *** [info] The Option on which value was invoked was not defined. (FirstTest.scala:30) [info] Run completed in 418 milliseconds. [info] Total number of tests run: 3 [info] Suites: completed 1, aborted 0 [info] Tests: succeeded 2, failed 1, canceled 0, ignored 0, pending 0 [info] *** 1 TEST FAILED *** [error] Failed tests: [error] first.FirstTest [error] (Test / testOnly) sbt.TestsFailedException: Tests unsuccessful
"future" should { "await result === 3" in { import scala.concurrent.ExecutionContext.Implicits.global val f = Future{ Thread.sleep(1000) 3 } val result = f.futureValue result mustBe 3 } }
上面代码的运行效果如下:
1 2 3 4 5 6 7 8
[info] FirstTest: [info] future [info] - should await result === 3 [info] Run completed in 1 second, 169 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.