ScalaTest学习笔记(一)

最近在看ScalaTest,整理一下笔记,将常用的代码贴出来。说明一下,ScalaTest可以选择多种风格(不同的Spechttp://www.scalatest.org/user_guide/selecting_a_style),我参考书里面用的FunSpec,大家可以自己选择。如果不知道如何选择的话

If you would rather be told which approach to take rather than pick one yourself, we recommend you use FunSpec for unit testing andFeatureSpec for integration or acceptance testing.

参考资料

  1. 《TestingInScala》http://ishare.iask.sina.com.cn/f/36122035.html
  2. http://www.scalatest.org/,顺便说一下官网的Manual永远是最权威最好的学习资料,很多书籍都比较旧,很多差异的
package com.oreilly.testingscala

import org.scalatest.{FunSpec, GivenWhenThen, Tag}
import org.scalatest.matchers.ShouldMatchers

class Point (val x:Int, val y:Int) {
  require(x > 0, "x should > 0")
}

class TestingInScala extends FunSpec with ShouldMatchers with GivenWhenThen {
  describe("Testing in Scala example") {
    it ("Different Matchers") {
    }
    it("simple matchers") {
      val list = 2::4::5::Nil
      list.size should be (3)//必须在()中,否则compile error
      list.size should equal (3)// 跟be一样,不能用==或者!=,3 == 5会执行得到false,但是不会导致test failed
    }

    it("String matchers") {
      val string = """I fell into a burning ring of fire.
      I went down, down, down and the flames went higher"""

      string should startWith ("I fell")
      string should not endWith ("I fell")
      string should include ("down, down, down")
      string should startWith regex "I.fel+"
      string should not endWith regex ("\\d{5}")
      string should fullyMatch regex ("""I(.|\n|\s)*higher""")//.不包括所有字符?
    }


    it("Ralational operator matchers") {
      val num = 20
      num should be < (30)
      num should not be > (30)
      num should be === (20)// 不能用==
      num should not equal(21)
      num should be >(0)
    }
    it("Floating matchers") {
      (0.9 - 0.8) should be (0.1 plusOrMinus 0.01)
    }

    it("Reference matchers") {
      val list_1 = List(5)
      val list_2 = list_1
      val list_3 = List(5)// 都用List()不行,因为都是'empty,是同一个对象
      list_1 should be theSameInstanceAs (list_2)
      list_1 should not be theSameInstanceAs (list_3)
    }

    it("Iterable matchers") {
      List() should be ('empty)// scala.Symbol
      8::7::6::5::Nil should contain (7)
    }

    it("Seq and traversable matchers") {
      (1 to 9) should have length (9)
      (20 to 60 by 2) should have size (21)
    }

    it("Map matchers") {
      val map = Map("Jimmy Page" -> "Led Zeppelin", "Sting" -> "The Police", "Aimee Mann" -> "Til\' Tuesday")
      map should contain key ("Sting")
      map should contain value ("Led Zeppelin")
      map should not contain key ("magic")
    }


    it("Compound matchers") {
      val redHotChiliPeppers = List("Anthony Kiedis", "Flea", "Chad Smith", "Josh Klinghoffer")
      redHotChiliPeppers should (contain("Anthony Kiedis") and (not contain ("John Frusciante") or contain("Dave Navarro")))
      redHotChiliPeppers should not (contain ("The Edge") or contain ("Kenny G"))//and和or以及右边的断言必须被()包住
      info("and/or不像&&或者||不会短路")
      val numT = 20
      var total = 3
      numT should (equal(20) or equal {total += 6})
      total should be(9)
    }

    it("null test") {
      var nullList:List[Int] = null
      //nullList should (not be (null) and contain (5))// 会有NullPointerException,用如下写法则是test failed
      //nullList should not be (null)
      //nullList should contain (5)
    }
    
    it("Property matchers") {
      val point = new Point(1, 2)
      point should have ('x(1), 'y(2))
    }

    it("java.util.Collection matchers") {//java的collection和scala里面的collection测试方式一样
      import java.util.{List => JList, ArrayList => JArrayList, Map => JMap, HashMap => JHashMap}

      val jList:JList[Int] = new JArrayList[Int](20)
      jList.add(1)
      jList.add(2)
      jList.add(3)
      jList should have size (3)
      jList should have length (3)// size和length一样,看自己喜欢用哪一个,并且初始化的20并不表示size
      jList should contain (1)
      jList should not contain (4)

      val emptyJList:JList[Int] = new JArrayList[Int]
      emptyJList should be ('empty)

      val jMap:JMap[String, Int] = new JHashMap
      jMap.put("one", 1)
      jMap.put("two", 2)
      jMap.put("three", 3)
      jMap should contain key ("one")
      jMap should contain value (1)
      jMap should not contain key ("four")
    }

    info("Must matchers跟should一样,只是用must关键字,同时应该with MustMatchers")

    it("Exception Handling") {
      info("use intercept...")
      val thrown = intercept[IllegalArgumentException] {// http://www.scalatest.org/user_guide/using_assertions
        val point = new Point(-1, 2)
      }
      thrown.getMessage should be ("requirement failed: x should > 0")

      info("use evaluating...")
      val thrownException = evaluating {new Point(-1, 2)} should produce[IllegalArgumentException]
      thrownException.getMessage should be ("requirement failed: x should > 0")
    }

    it("GivenWhenThen实际上是informer,可用于组织测试结构") {
      given("create a Point")
      val point = new Point(1, 2)

      when("point.x get")
      val x = point.x

      then("x isInstanceOf[Int]")
      x.isInstanceOf[Int] should be (true)

      and("x == 1")
      x should equal (1)
    }

    it("pending......") {// 貌似现在是pending之后的不会执行,之前的会执行,如果info下面的true改为false,会test failed,但是pending之后的不会
      info("下面的测试不会执行,但是info会输出")
      1 == 1 should be (true)
      pending
      1 == 1 should be (false)
    }
    
    ignore("ignore...") {// 要执行,将ignore改为it即可
      info("ignore的info不会输出...")
    }

    it("tag...", Tag("point")) {
      info("可以用-- -n point只执行有point的Tag,用-l则不执行point Tag,sbt目前只能用它testOnly来运行tag")
    }

  }
}

你可能感兴趣的:(scala,单元测试,unittest,ScalaTest,TestingInScala)