12.8 FunSuite的函数式风格

我们还可以用ScalaTest提供的FunSuite编写函数式风格的测试,在命名测试的时候也会更加灵活。我们不再是写测试方法,而是调用一个名叫test()的方法,给它提供一个有意义的测试名字和一个闭包——闭包中是测试的主体。让我们用FunSuite重写一下12.7节“用闭包共享代码”中的代码。

UnitTestingWithScala/UsingFunSuite.scala

  1. class UsingFunSuite extends org.scalatest.FunSuite {
  2. def withList(testFunction : (java.util.ArrayList[Integer]) => Unit) {
  3. val list = new java.util.ArrayList[Integer]
  4. try {
  5. testFunction(list)
  6. }
  7. finally {
  8. // perform any necessary cleanup here after return
  9. }
  10. }
  11. test("Check if the list is Empty On Creation"){
  12. withList { list => expect(0, "Expected size to be 0") { list.size() } }
  13. }
  14. test("Get must throw exception when called on an empty list"){
  15. withList {
  16. list => intercept[IndexOutOfBoundsException] { list.get(0) }
  17. }
  18. }
  19. }
  20. (new UsingFunSuite).execute()

输出如下:

  1. Test Starting - Main$$anon$1$UsingFunSuite: Check if the list is Empty
  2. On Creation
  3. Test Succeeded - Main$$anon$1$UsingFunSuite: Check if the list is Empty
  4. On Creation
  5. Test Starting - Main$$anon$1$UsingFunSuite: Get must throw exception
  6. when called on an empty list
  7. Test Succeeded - Main$$anon$1$UsingFunSuite: Get must throw exception
  8. when called on an empty list

这里没有用传统的测试方法,而是调用了FunSuitetest()方法,给了它一段描述性消息。实际的测试代码位于闭包之中,调用test()方法时,会把这个闭包附在后面。你会发现这种测试形式远比传统测试更加轻量级,也许很快,它就会成为你用Scala编写测试的最爱。