当前位置:网站首页>《scala 编程(第3版)》学习笔记4
《scala 编程(第3版)》学习笔记4
2022-08-02 03:28:00 【Code_LT】
第14章 断言和测试
- Predef的
assert(condition)或assert(condition,explanation),condition如果不满足,则抛出AssertionError。explanation类型为Any,可以传入任何对象,将调用对象的toString打印输出。P258
scala> assert(false,"test error")
java.lang.AssertionError: assertion failed: test error
at scala.Predef$.assert(Predef.scala:170)
... 32 elided
- Predef的
ensuring(condition),这里的condition为结果类型参数并返回Boolean的前提条件函数(即condition为函数)。使用方法为{代码块}ensuring(condition(x)),ensuring将{代码块}的结果x传递给condition(x)函数,如果condition(x)为true,则ensuring返回结果x,否则抛出AssertionError。P259
def func(a:Int):String={
a.toString
}ensuring(_.length>2,"msg: 位数小于3")
scala> func(2)
java.lang.AssertionError: assertion failed: msg: 位数小于3
at scala.Predef$Ensuring$.ensuring$extension3(Predef.scala:261)
at .func(<console>:14)
... 32 elided
- ensuring一般用于内部测试,断言(assert, ensuring)可通过
JVM -ea -da来分别打开或关闭。P260 - 外部测试,ScalaTest框架(官方指导),FunSuite风格。
- scalatest涉及三方jar包导入,idea的三方jar包导入方式(单个,批量),导入后即可正常
org.scalatest.FunSuite(3.2.0版开始已经没有Funsuit了,而是用funsuite.AnyFunSuite(官方指导))。当然,也可以使用构建maven工程+pom.xml方式导入。(todo:有时间单独出一期直接导入和pom导入的教程)
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest-funsuite_2.11</artifactId>
<version>3.2.0</version>
<scope>test</scope>
</dependency>
import org.scalatest.funsuite
class MyTest extends funsuite.AnyFunSuite {
val s = "a b c d"
//assert 一般断言
test("长度大于4"){
assert(s.length > 4)
}
test("长度大于8"){
assert(s.length >8)
}
//assertResult 将预期与实际值区分开来;
val a = 5
val b = 2
assertResult(2) {
a - b
}
//assertThrows 以确保一些代码抛出预期的异常。捕获正确异常,则返回succeeded的Assertion,否则,返回TestFailedException
val s2 = "hi"
assertThrows[IndexOutOfBoundsException] {
// Result type: Assertion
s2.charAt(-1)
}
//intercept和assertThrows 表现一样,但若捕获正常异常的话,则返回IndexOutOfBoundsException。
val caught =
intercept[IndexOutOfBoundsException] {
// Result type: IndexOutOfBoundsException
s2.charAt(-1)
}
assert(caught.getMessage.indexOf("-1") != -1)
//带clue版本
assert(1 + 1 === 3, "this is a clue")
assertResult(3, "this is a clue") {
1 + 1 }
withClue("this is a clue") {
assertThrows[IndexOutOfBoundsException] {
"hi".charAt(-1)
}
}
}
边栏推荐
猜你喜欢
随机推荐
张量乘积—实验作业
分布式消息队列平滑迁移技术实战
广告电商「私域打工人」职业前景:你离月薪6万,还差多远?
pytorch:保存和加载模型
uniapp | Problems with the use of the official map component
gradle脚本中groovy语法讲解
18张图,直观理解神经网络、流形和拓扑
Laravel打印执行的SQL语句
kotlin语法总结(二)
【泰山众筹】模式为什么一直都这么火热?是有原因的
Glide中图片处理
umi3 权限路由PrivateRoute未执行
管理node版本的工具volta
关于我的项目-微信小程序2(uniapp->wx小程序)
Syncthing文件同步方案完全攻略(亲测有效)
英语每日打卡
解决flex布局warp自动换行下最后一行居中问题
Mysql创建索引
政府会计的概念、政府会计标准体系、政府会计的特点(会形成小考点)、政府会计要素及其确认和计量、政府预算会计要素、政府财务会计要素
VS2017报错:LNK1120 1 个无法解析的外部命令









