您的位置:首页 > 其它

scala 单元测试

2015-07-10 07:34 531 查看

scala 单元测试

字符串测试

ScalaTest
提供了很方便的测试字符串的工具, 这些工具可以进行正则表达式的测试,常用方法有:

val string = "test string"
string should startWith("test")
string should endWith("string")
string should not endWith("the end")
string should not include("down down")
string should include("st")

string should startWith regex("I.fel+")
string should endWith regex ("h.{4}r")
string should not endWith regex("\\d{5}")
string should include regex ("flames?")

string should fullyMatch regex ("""I(.|\n|\S)*higher""")


整数测试

比较数值的时候可以使用:

val answerToLife = 42
answerToLife should be < (50)
answerToLife should not be > (50)
answerToLife should be > (3)
answerToLife should be <= (100)
answerToLife should be >= (0)
answerToLife should be === (42)
answerToLife should not be === (400)


三等号
===
是用来测试左右是否相等, 而
==
是用来检查是否相同, 在测试环境中用于昂不假设(assert) 相等。 所以最好的方法是用=== 或者是使用
equal
方法

浮点数测试

测试浮点数时,主要是判断精准度,这时可以使用
plusOrMinus
方法来规定范围, 比如:

(0.9 - 0.8) should be (0.1 plusOrMinus .01)
(0.4 + 0.1) should not be (40.00 plusOrMinus .30)


比较引用类型

在scala中,如果需要测试两个引用类型可以使用
theSameInstanceAs
来比较,例如

val garthBrooks = new Artist("Garth", "Brooks")
val chrisGaines = garthBrooks

garthBrooks should be theSameInstanceAs (chrisGaines)

val debbieHarry = new Artist("Debbie", "Harry")
garthBrooks should not be theSameInstanceAs(debbieHarry)


如果在测试
collection
的时候,可以使用如下方法:

list() should be(' empty')
8::6::7::5::Nil should contain(7)
(1 to 9) should have length(9)
(20 to 60 by 2) should have size(21)


ScalaTest 可以对Map使用特别的匹配符, 通过此种方法可以判断一个map的key和value。

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("Brian May")


在使用
java.util.collection
的时候也可以使用此种方法来判断

另外,如果需要组合条件, 可以使用
and
or
来进行组合语句判断, 也可以通过 ‘not’ 进行取反。

异常处理

先看代码:

"An album" should {
"throw an IllegalArgumentException if there are no acts when created" in {
intercept[IllegalArgumentException] {
new Album("The Joy of Listening to Nothing", 1980, List())
}
}
}


当创建
Album
对象时,我们可以用
{}
来捕获错误的信息,如果没有获得所设计的行为, 这个测试就会失败, 我们可以在这里控制是否期待一个异常。

FreeSpec in Scala

公司在使用FreeSpec, 这个spec方法比GivenWhenThen方法更整洁也更灵活。 这个方法允许测试方法测试多个测试过程,比如

"given something" - {

"when something" - {
"then something "  in {
}
}
}


- {}
中,不允许使用 比较或者 assert语句, 但是在
in {}
中是可以使用assert 语句, 而且
in {}
语句可以和其他
- {}
语句平行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: