tonglin0325的个人主页

Scala学习笔记——断言和单元测试

1.断言

**assert(conditon)**将在条件不成立的时候,抛出assertionError

**assert(conditon,explanation)**讲在条件不成立的时候,抛出explanation作为说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.scala.first

/**
* Created by common on 17-4-19.
*/
object Assert {

def main(args: Array[String]): Unit = {
val a = new Assert()
a.above1(0)

}

}

class Assert {
val value = 1

def above(that: Int): Unit = {
val thatVal = that
val thisVal = this.value
//如果条件不满足,Exception in thread "main" java.lang.AssertionError: assertion failed
assert(thatVal == thisVal)
}

//另一种断言
//如果条件不满足,Exception in thread "main" java.lang.AssertionError: assertion failed
def above1(that: Int): Unit = {
{
val thatVal = that
val thisVal = this.value
} ensuring(that == this.value)

}
}

 

2.单元测试

Scala中提供了多种单元测试的方法,比如ScalaTest

ScalaTest提供了多种单元测试的方法,最简单的就是创建org.scalatest.suite类,并在这些类中定义测试方法

如果cmd+shift+T的快捷键无效的话,在需要测试的类上右键,Go to Test,创建一个测试类