scala 单元测试

这篇博客详细介绍了Scala单元测试,包括字符串、整数、浮点数的测试,引用类型的比较,异常处理,以及如何使用FreeSpec进行更灵活的测试。重点讲解了测试工具的使用和测试断言的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 的时候也可以使用此种方法来判断
另外,如果需要组合条件, 可以使用andor 来进行组合语句判断, 也可以通过 ‘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 {} 语句可以和其他 - {} 语句平行

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值