ScalaTest——Assertion断言

ScalaTest默认在任何样式特征中都提供三个断言。您可以使用:

  • assert 一般断言;
  • assertResult 区分预期值和实际值;
  • assertThrows 确保一些代码抛出预期的异常。

ScalaTest的断言在特征中被定义,特征AssertionsSuite超级特征扩展到所有风格特征。特质Assertions还提供:

  • assume有条件地取消测试;
  • fail 无条件地测试失败;
  • cancel 无条件取消测试;
  • succeed 无条件地测试成功;
  • intercept 确保一些代码抛出预期的异常,然后对异常进行断言;
  • assertDoesNotCompile 确保一些代码无法编译;
  • assertCompiles 确保编译一些代码;
  • assertTypeError 确保一些代码由于类型(非解析)错误而无法编译;
  • withClue 添加有关失败的更多信息。
3.1 assert断言

如果传递的表达式是trueassert将正常返回。如果false,Scala assert将生成AssertionError

class test extends FunSpec {
    describe("value"){
        it("assert equals"){
            val left = 2
			val right = 1
			assert(left == right)
        }
    }
}

此行为由assertobject中定义的方法提供Predef,其成员被隐式导入到每个Scala源文件中。这个Assertions特性定义了另assert一种隐藏其中的方法Predef。它的行为相同,除了if false被传递它抛出TestFailedException而不是AssertionError。为什么?因为不同AssertionError,TestFailedException它携带有关堆栈跟踪中哪个项目确切代表失败的测试代码行的信息,这可以帮助用户在失败的测试中更快地找到有问题的代码行。另外,ScalaTest的assert提供比Scala更好的错误消息assert。
where a is 1, b is 2, c is 3, d is 4, xs is List(a, b, c), and num is 1.0:

assert(a == b || c >= d)
// Error message: 1 did not equal 2, and 3 was not greater than or equal to 4
assert(xs.exists(_ == 4))
// Error message: List(1, 2, 3) did not contain 4
assert("hello".startsWith("h") && "goodbye".endsWith("y"))
// Error message: "hello" started with "h", but "goodbye" did not end with "y"
assert(num.isInstanceOf[Int])
// Error message: 1.0 was not instance of scala.Int
assert(Some(2).isEmpty)
// Error message: Some(2) was not empty
import org.scalatest.FunSuite
class SetFuncSuite extends FunSuite {
  //差集
  test("Test difference") {
    val a = Set("a", "b", "a", "c")
    val b = Set("b", "d")
    assert(a -- b === Set("a", "c"))
  }
  //交集
  test("Test intersection") {
    val a = Set("a", "b", "a", "c")
    val b = Set("b", "d")
    assert(a.intersect(b) === Set("b"))
  }
  //并集
  test("Test union") {
    val a = Set("a", "b", "a", "c")
    val b = Set("b", "d")
    assert(a ++ b === Set("a", "b", "c", "d"))
  }
}
import java.util.NoSuchElementException
import org.scalatest.FunSpec
import scala.collection.mutable

class StackSpec extends FunSpec {
  describe("A Stack"){
    it(" should pop values in last-in-first-out order"){
      val stack = new mutable.Stack[Int]
      stack.push(1)
      stack.push(2)
      assert(stack.pop()===2)
      assert(stack.pop()===1)
    }
    it("throw NoSuchElementException if an empty stack is popped" ){
      val emptyStack = new mutable.Stack[String]
      assertThrows[NoSuchElementException]{
        emptyStack.pop()
      }
    }
  }
}
3.2 assertResult断言

使用assertResult时将期望值放在assertResult的括号后面,然后将应该产生预期值的代码填入花括号中。

class StackSpec extends FunSpec {
  describe("result"){
    it("number"){
      val a = 5
      val b = 2
      assertResult(2) {
        a - b
      }
    }
  }
}
3.3 assertThrows异常捕获
val s = "hello"
assertThrows [ IndexOutOfBoundsException ] { //结果类型:断言 
  s.charAt(-1)
}

如果charAt抛出一个实例IndexOutOfBoundsException, assertThrows将返回Succeeded。
但是如果charAt正常完成没有发生异常,或抛出其他的异常,assertThrows将发生TestFailedException。
3.4 intercept异常捕获

intercept方法的行为与assertThrows相同,如果代码块没有抛出异常,则测试失败。除了返回捕获的异常而不是返回Succeededintercept以便您可以根据需要进一步检查它。例如可能需要确保异常中包含的数据具有预期值。这是一个例子:

class AlbumTest extends FunSpec with Matchers with GivenWhenThen{
  describe("An Album"){
      it("throw an IllegalArgumentException if there are no acts when created") {
        val s = "hi"
        val caught = intercept[IndexOutOfBoundsException] { 
            s.charAt(-1)
        }
        assert(caught.getMessage.indexOf("-1") != -1)
      }
  }
}

你可能感兴趣的:(ScalaTest)