当前位置:网站首页>《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)
}
}
}
边栏推荐
猜你喜欢
随机推荐
C#从入门到精通
帧动画和补间动画的使用
Jetpack中各个组件简介
umi3 权限路由PrivateRoute未执行
php laravel框架生成二维码
Laravel 登录,中间件和路由分组
Laravel 的关联模型 及其 预加载多个关联 with使用方法
研发过程中的文档管理与工具
php中魔术方法详解
管理会计(对内)指引、管理会计要素及其具体内容(可能考,考前记一下,推荐记一下四个大点即可)、
OpenCore 黑苹果安装教程
[Spark]-LSH局部敏感哈希
链动2+1模式开发系统
阿里技术官手码12W字面试小册
TimeSformer视频理解框架:视频理解中的Transformer
Go中的一些优化笔记,简约而不简单
政府会计的概念、政府会计标准体系、政府会计的特点(会形成小考点)、政府会计要素及其确认和计量、政府预算会计要素、政府财务会计要素
[Hello World教程] 使用HBuilder和Uni-app 生成一个简单的微信小程序DEMO
C# 关键字学习手记
Binder机制详解(一)