ScalaTest学习笔记(二)

为了每个测试用例单独使用自己的数据,避免各个test case互相影响,ScalaTest提供了四种方式:Anonymous Object,Trait,OneInstancePerTest,Before and After,其中前两种是利用Scala语言的特性,后两种是ScalaTest提供的接口。代码如下:

package com.oreilly.testingscala

import org.scalatest.FunSpec
import org.scalatest.matchers.ShouldMatchers

class FixtureAnonymousObjectTest extends FunSpec with ShouldMatchers {
  def fixture = new {
    import scala.collection.mutable._

    val list = new ListBuffer[Int]()
    list += 5
  }

  describe("fixture with Anonymous Objects.......") {
    it("add 1, size should be 2") {
      val list = fixture.list
      list += 6

      info(list.mkString("[", ",", "]"))

      list should have size(2)

    }

    it("add 1, size should be 3") {
      val list = fixture.list
      list += 6
      list += 7

      info(list.mkString("[", ",", "]"))

      list should have size(3)

    }
  }

}
package com.oreilly.testingscala

import org.scalatest.FunSpec
import org.scalatest.matchers.ShouldMatchers

class FixtureTraitTest extends FunSpec with ShouldMatchers {
  trait FixtureTrait {
    import scala.collection.mutable._

    val list = new ListBuffer[Int]()
    list += 5
  }

  describe("fixture with Trait.......") {
    it("add 1, size should be 2") {
      new FixtureTrait {
        list += 6

        info(list.mkString)

        list should have size(2)
      }

    }

    it("add 1, size should be 3") {
      new FixtureTrait {
        list += 6
        list += 7

        info(list.mkString)

        list should have size(3)
      }

    }
  }

}
package com.oreilly.testingscala

import org.scalatest.{FunSpec, OneInstancePerTest}
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable._

class FixtureOneInstancePerTestTest extends FunSpec with ShouldMatchers with OneInstancePerTest {
  val list = new ListBuffer[Int]()
  list += 1

  describe("fixture.......") {
    it("add 1, size should be 2") {
      list += 6

      info(list.mkString("[", ",", "]"))

      list should have size(2)

    }

    it("add 1, size should be 3") {
      list += 6
      list += 7

      info(list.mkString("[", ",", "]"))

      list should have size(3)

    }
  }

}
package com.oreilly.testingscala

import org.scalatest._
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable._

class FixtureBeforeAndAfterTest extends FunSpec with ShouldMatchers with BeforeAndAfter {
  val list = new ListBuffer[Int]()

  before {
    info("starting add 5 to list")
    list += 5
  }

  after {
    info("clearing list")
    list.clear
  }
  describe("fixture.......") {
    it("add 1, size should be 2") {
      list += 6

      info(list.mkString("[", ",", "]"))

      list should have size(2)

    }

    it("add 1, size should be 3") {
      list += 6
      list += 7

      info(list.mkString("[", ",", "]"))

      list should have size(3)

    }
  }

}

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