当前位置:网站首页>《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)
}
}
}
边栏推荐
猜你喜欢
随机推荐
TimeSformer视频理解框架:视频理解中的Transformer
清理c盘爆满告急,C盘清理
electron-builder打包不成功解决方法
C# 关键字学习手记
Microsoft Office安装全过程记录
[Spark]-RDD详解之变量&操作
自定义view实现半圆弧进度条
win10内存占用很高,关闭所有应用程序依然降不下来(win11)
张量乘积—实验作业
VS2017报错:LNK1120 1 个无法解析的外部命令
ReentrantLock的使用和原理详解
关于我的大创、论文~
考(重点理解哪些属于其他货币资金)、其他货币资金的内容、其他货币资金的账务处理(银行汇票存款、银行本票存款、信用卡存款、信用证保证金存款、存出投资款、外埠存款)
修复APP的BUG,热修复的知识点和大厂的相关资料汇总
RecyclerView使用和原理解析
Laravel 的关联模型 及其 预加载多个关联 with使用方法
强化学习笔记:DDPG
从Attention到Self-Attention和Multi-Head Attention
[Spark]-LSH局部敏感哈希
SGDP(1)——猜数字游戏