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 {}语句可以和其他
- {}语句平行
相关文章推荐
- 【翻译自mos文章】使用dbua升级时,需要手工设置CLUSTER_DATABASE参数么?
- Qt中文支持和文件读写
- Android Studio无法下载sdk问题
- 一个短小的JS函数,用来得到仅仅包含不重复元素的数组
- pkg: cached package *:size mismatch, cannot continue
- 《编程导论(Java)·1.4.1 范式》
- 【翻译自mos文章】使用dbua升级到70%左右时,os hang
- OSChina 周五乱弹 —— 找对象下象棋
- Leetcode NO.231 Power of Two
- 探索MySQL高可用架构之MHA(7)
- Google的算法出过哪些囧事?
- 给程序员第一天工作留下好印象的10个方式
- 关于心理学方面的一点看法
- python的绿色版本
- rebot的使用
- Robot Framework安装指南
- 修改状态栏字体的颜色
- 如何编写Robot Framework测试用例1---(基本格式篇)
- 在Oracle 11.2的数据库中建表时遇到 RESULT_CACHE (MODE DEFAULT) ORA-00922: missing or invalid option
- 自动化测试框架 RobotFramework 用户说明书中文版