kotlin中的异常处理_如何使用assertFailsWith在Kotlin中测试异常
kotlin中的异常处理
by Daniel Newton
丹尼尔·牛顿
如何使用assertFailsWith在Kotlin中测试异常 (How to test exceptions in Kotlin with assertFailsWith)
I wanted to write this short post to highlight the assertFailsWith
function available to Kotlin. This function makes testing exceptions a bit easier. Testing exceptions isn’t something fancy or new to JVM languages (from now on I will use Java for comparisons). Kotlin comes with the nice extra benefit of providing this functionality as part of its standard library. Comparing this to Java, you are likely to bring AssertJ into the mix to achieve similar results.
我想写这篇简短的文章来强调Kotlin可用的assertFailsWith
函数。 此功能使测试异常更加容易。 测试异常对于JVM语言来说并不是什么新鲜事物(从现在开始,我将使用Java进行比较)。 Kotlin具有将其功能作为其标准库的一部分提供的额外好处。 将其与Java进行比较,您很可能将AssertJ加入到混合中以实现类似的结果。
The main purpose of this post is to make you aware of the assertFailsWith
function. I personally did not know it existed for a while and defaulted to depending on AssertJ. Not that I have anything against AssertJ, that is. There are many other features that the library provides. For this specific instance, it might be possible to remove it (assuming you are not using it for anything else).
这篇文章的主要目的是使您知道assertFailsWith
函数。 我个人不知道它存在了一段时间,并且默认依赖于AssertJ。 并不是说我对AssertJ有什么反对。 该库还提供许多其他功能。 对于此特定实例,可以将其删除(假设您没有将其用于其他任何用途)。
What is good about assertFailsWith
and AssertJ in general? It provides better exception testing than the simple constructs that JUnit provides. More precisely, it allows you to specify which part of your test that you expect an exception to be thrown, instead of declaring that an exception will arise somewhere in the code. This could lead to exceptions being incorrectly swallowed by test at an incorrect point and tricking you into thinking it is working as you think it should.
是什么样的好assertFailsWith
和AssertJ带来什么影响? 它提供了比JUnit提供的简单结构更好的异常测试。 更准确地说,它允许您指定期望在测试的哪一部分抛出异常,而不用声明代码中会出现异常。 这可能导致异常在错误的位置被测试错误地吞没,并诱使您认为它正在按您的方式工作。
Now I have that brief point out of the way, let's get on with the main content of this post. Below is what assertFailsWith
looks like inside a test:
现在,我有一个简短的要点,让我们继续本文的主要内容。 下面是assertFailsWith
外观:
In this example, hereIsAnException
is placed inside the body of assertFailsWith
, who checks that an IllegalArgumentException
is thrown. If one is not raised, then the assertion will fail. If one does occur, then the assertion will pass and the exception is caught.
在这个例子中, hereIsAnException
放置的身体内部assertFailsWith
,谁检查,一个IllegalArgumentException
被抛出。 如果未提出,则断言将失败。 如果确实发生,则断言将通过并捕获异常。
Catching the exception allows the execution of the test code to continue if needed as well as allowing you to make further assertions on the state of the exception.
捕获异常可以使测试代码在需要时继续执行,还可以使您对异常状态进行进一步的断言。
For example, is it a wrapper around another exception (what is the type of its cause
property)?
例如,它是否是另一个异常的包装器(其cause
属性的类型是什么)?
Is the message what you expect (not the most sturdy of checks)?
您所期望的消息(不是最坚固的支票)吗?
Only exceptions that are of the same type or subtype as specified by assertFailsWith
will be caught. Any others will cause the test to fail. Since it catches subtypes, please don’t go around just specifying Exception
or RuntimeException
. Try to be precise so your tests are as useful as possible.
仅捕获与assertFailsWith
指定的类型或子类型相同的异常。 其他任何因素都会导致测试失败。 由于它捕获子类型,因此请不要只指定Exception
或RuntimeException
。 尽量精确一些,以便您的测试尽可能有用。
As touched on earlier, assertFailsWith
will only catch an exception that is thrown within the body of the function. Therefore if this was written instead:
如前所述, assertFailsWith
将仅捕获在函数体内引发的异常。 因此,如果写成这样:
The test would fail. hereIsAnException
has thrown an exception, which has not been caught and leads to the test failing. I believe this is the best part of this sort of function over the previous ways this used to be done (e.g. asserting inside @Test
that an exception would occur).
测试将失败。 hereIsAnException
引发了一个异常,该异常尚未被捕获并导致测试失败。 我相信这是过去完成此功能的最佳方法(例如,在@Test
内部断言将发生异常)。
I personally have never really used the message part of an assertion. Maybe you do, so, I thought I’d at least let you know.
我个人从未真正使用过断言的消息部分。 也许您愿意,所以,我想我至少会让您知道。
Before I wrap up the little amount of content in this post, let's have a quick look at AssertJ so that we can draw a comparison between the two. Again, this is only for the case of catching exceptions which is only a small part of what AssertJ provides.
在结束本文的少量内容之前,让我们快速看一下AssertJ,以便我们可以对两者进行比较。 同样,这仅适用于捕获异常的情况,这只是AssertJ提供的内容的一小部分。
This is slightly more “verbose” than the assertFailsWith
version. But, that is made up for with the plethora of functions that AssertJ provides that makes any further checking of the returned exception much easier. More precisely, when using assertFailsWith
I needed to write another assertion to check the message. In AssertJ this is just a function chained onto the end of the previous call.
这比assertFailsWith
版本稍微“冗长”。 但是,这是由AssertJ提供的大量功能所弥补的,该功能使对返回的异常的任何进一步检查变得更加容易。 更准确地说,当使用assertFailsWith
我需要编写另一个断言来检查消息。 在AssertJ中,这只是链接到上一个调用末尾的函数。
To conclude, assertFailsWith
is a nice little function to use in testing to ensure that a piece of code throws a specific type of exception. It is built into the Kotlin standard library which removes the need to bring in an extra dependency to your project. That being said, it is a relatively simple function and does not bring the sort of functionality that a library like AssertJ would. It is likely to suffice until you want to write tests that contain a wide range or assertions as this is the point where it can get messy.
总而言之, assertFailsWith
是一个很好的小函数,可用于测试以确保一段代码抛出特定类型的异常。 它内置在Kotlin标准库中,从而消除了对项目带来额外依赖的需求。 话虽这么说,它是一个相对简单的函数,并没有像AssertJ这样的库所带来的那种功能。 在您要编写包含广泛范围或断言的测试之前,这可能就足够了,因为这会使其变得混乱。
The official docs for assertFailsWith
can be found here if you are interested Kotlin Docs – assertFailsWith.
如果您有兴趣的Kotlin Docs – assertFailsWith,可以在这里找到assertFailsWith
的官方文档。
If you found this post helpful, you can follow me on Twitter at @LankyDanDev to keep up with my new posts.
如果您发现此帖子有帮助,可以在Twitter上@LankyDanDev关注我,以跟上我的新帖子。
View all posts by Dan Newton
查看丹·牛顿的所有文章
Originally published at lankydanblog.com on January 26, 2019.
最初于2019年1月26日发布在lankydanblog.com上。
翻译自: https://www.freecodecamp.org/news/how-to-test-exceptions-in-kotlin-with-assertfailswith-dd50f929ef8c/
kotlin中的异常处理
相关文章:

学习dubbo框架的问题
InputStream : 是所有字节输入流的超类,一般使用它的子类:FileInputStream等,它能输出字节流;InputStreamReader : 是字节流与字符流之间的桥梁,能将字节流输出为字符流,并且能为字节…

Android 控件 之 Menu 菜单
http://www.cnblogs.com/Mrs-cc/archive/2012/07/21/2603042.html 1.OptionsMenu (选项菜单)用法总结使用方法:方法一:添加菜单项:onCreateOptionsMenu(Menu menu)中添加menu.add(Menu.NONE,Men…

VUE保存页面的数据,VUE页面显示就执行某个函数,VUE页面隐藏就执行某个函数
用 VUE 默认的 keep-alive 组件实现 保存页面的数据,页面显示就执行某个函数,页面隐藏就执行某个函数实现方式: 1.在路由内设置页面是否需要缓存; 示例代码:(在需要的组件里面添加meta 对象,keepAlive属…

npm i和npm_让您的NPM套件包含Jest和Codecov☂️
npm i和npmby Carl-Johan Kihl卡尔约翰基尔(Carl-Johan Kihl) 让您的NPM套件包含Jest和Codecov☂️ (Get your NPM-package covered with Jest and Codecov ☂️) 介绍 (Introduction) Let’s talk about code coverage, and how you can do coverage reports in Jest and Cod…

分页传页数的方法
<!DOCTYPE html><html> <head> <meta charset"UTF-8"> <title></title> </head> <body> <div> <span id"num">1</span> <button id"prev">上一页</button> <…

VUE input唤起键盘 底部固定的标签被顶上去解决办法
通过输入框的失去焦点事件和点击事件,当出现键盘时把绝对定位的底部文字隐藏,失去焦点(键盘隐藏的时候)显示底部文字 解决代码 <input type"text" class"weui-input" click"input_click" blur…

unity中摄像机的控制---调整摄像机,不让他摔倒
摄像机大部分人都会控制,最明显的就是让他旋转,随着鼠标的左右上下移动而旋转,但是总是会遇到一个问题,就是转着转着就仿佛他自己摔倒了似的,其实就是它本身绕着Z轴旋转了 这样就不是我们想要的结果了 要想解决也简单&…

java正则表达式课程_通过此免费课程学习正则表达式
java正则表达式课程by Beau Carnes通过博卡恩斯 通过此免费课程学习正则表达式 (Learn Regular Expressions with this free course) “Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.” -Jami…

Codeforces Round #370 (Div. 2)
A - Memory and Crow 这题我没看题意,看了样例猜了一下就AC了,题目好像还挺复杂的。 #include<bits/stdc.h> using namespace std; int a[100005]; int main() {int n;cin>>n;for(int i1;i<n;i) scanf("%d",&a[i]);for(int…

pat1004. Counting Leaves (30)
1004. Counting Leaves (30) 时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, YueA family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child. Input Each input file contains…

css 引用字体
最近遇到个问题,页面使用的字体要用PingFangSC字体,引入方法如下: 简单介绍下PingFangSC字体: (1)苹方-简 常规体 font-family: PingFangSC-Regular, sans-serif; (2)苹方…

系统技术方案 系统构架_构架系统时应注意的事项
系统技术方案 系统构架by Ayelet Sachto通过Ayelet Sachto 架构系统时要记住的6件事 (6 Things to keep in mind when architecting a system) Architecture may sound like a “scary ” or overwhelming subject, but actually, applying logic and approaching the problem…

[LeetCode] Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num 38, the process is like: 3 8 11, 1 1 2. Since 2 has only one digit, return it. 分析一:最简单的循环方法 class Solutio…

vue 点击事件执行多次
把 click 改成 click.once 就可以了 示例代码 click.once"down" 这样有一个弊端,就是事件只执行一次就不再执行了, 另一种方式,做一个定时器 //默认设置dddown为 true if(that.dddown){that.dddown falsesetTimeout(function(…

如何以及为什么使用Android Visibility Listeners
The Android UI is built up from Views, and in a regular application, there are usually several of them. To find out which View the user is currently looking at, you need to install Visibility Listeners.Android UI是从Views构建的,在常规应用程序中&…

在vue中使用Element-UI
Element-UI是一套基于Vue2.0的UI组件库,http://element.eleme.io/#/zh-CN/component/carousel 首先npm install element-ui --save 然后在main.js中引入: import Vue from vue import ElementUI from element-ui import element-ui/lib/theme-default/in…
Flex布局教程(来源:阮一峰)
网页布局(layout)是 CSS 的一个重点应用。Flex 布局将成为未来布局的首选方案。本文介绍它的语法,下一篇文章给出常见布局的 Flex 写法。网友 JailBreak 为本文的所有示例制作了 Demo,也可以参考。 以下内容主要参考了下面两篇文…

ibatis的there is no statement named xxx in this SqlMap
报错情况如下:com.ibatis.sqlmap.client.SqlMapException: There is no statement named Control.insert-control in this SqlMap. at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.getMappedStatement(SqlMapExecutorDelegate.java:231)at com.ibatis.sq…

javascript案例_如何在JavaScript中使用增强现实-一个案例研究
javascript案例by Apurav Chauhan通过Apurav Chauhan 如何在JavaScript中使用增强现实-一个案例研究 (How to use Augmented Reality with JavaScript — a case study) In this experiment, I talk about how Augmented Reality with JS can be used to make learning more f…

久未更 ~ 一之 —— 关于ToolBar
很久没更博客了,索性开一个久未更 系列 > > > > > 久未更 系列一:关于ToolBar的使用(后续补充) 1 //让 ToolBar 单独使用深色主题 使得 toolbar 中元素 变为淡色 2 android:theme"style/ThemeOverlay.AppCompat.Dark.ActionBar"…
SQLServer怎样把本地数据导入到远程服务器上(转载)
平常用到mssql时间比较少,总是过一段时间就忘记应该怎么操作了。当要做mssq把本地数据导入到远程服务器的时候,就去网上搜索很久都没有图解的,所以今天自己收集一下免得下次又到处去找。希望对自己,同时对其它需要的人都有一定的帮…

input 默认样式的修改
/* 修改input选中的默认边框样式 */ outline: none; /* 修改input的选中时的光标颜色 */ caret-color:red; /* 修改input的选中时的默认边框 */ border: none; /* 修改input的提示文字的默认样式 */ input::-webkit-input-placeholder{color:#d0d0d0;}

巨石加密_点餐:如何吃一个可怕的巨石
巨石加密by Alan Ridlehoover通过艾伦里德尔霍弗 点餐:如何吃一个可怕的巨石 (Ordering Take Out: How to Eat a Scary Monolith) Martin Fowler said:马丁福勒(Martin Fowler) 说 : Almost all the successful microservice stories have started wit…

Halcon学习之六:获取Image图像中Region区域的特征参数
area_center_gray ( Regions, Image : : : Area, Row, Column ) 计算Image图像中Region区域的面积Area和重心(Row,Column)。 cooc_feature_image ( Regions, Image : : LdGray, Direction : Energy,Correlation, Homogeneity, Contrast ) …

dos下命令行执行程序时候注意程序所使用文件的路径问题
dos下命令行执行程序时候,最好是用cd命令先切换到程序所在目录下,这样就不会出现文件找不到的问题,如果由于特殊原因,不使用cd命令,而只使用路径命令时候程序中访问的资源也只能是改成绝对路径了,这样对有源…

Vant 使用之Toast Vant安装和使用
Vant 是一个VUE 的移动端组件库,里面有很多好用的组件。 第一步,安装和配置 Vant npm i vant -S npm i babel-plugin-import -D 安装完成之后,在项目 .babelrc 文件修改配置 plugins "plugins": [["import", {"…

15-5重构_重构-糟糕,我一直在向后做。
15-5重构by Justin Fuller贾斯汀富勒(Justin Fuller) 重构-糟糕,我一直在向后做。 (Refactoring — oops, I’ve been doing it backwards.) Welcome to my intervention. I’m a refactoring addict and I’m not afraid to admit it, but there’s only one prob…

JPush 使用教程
JPush 使用教程 自己使用的一些经验,为了方便直接从这里复制过去就行。 就当做个笔记,防止长时间忘记之后,还需要去官网看文档。 主要思路: sdk文件 三方依赖系统库 头文件 添加代理 初始化代码 1.版本信息 JPush : 2.2.0 Xco…

浏览器常见兼容性问题汇总
1、随便写几个标签,不加样式控制的情况下,各自的margin 和padding差异较大,解决方案是:*{margin:0;padding:0;} 2、块属性标签float后,又有横行的margin情况下,在IE6显示margin比设置的大,常出现…

VUE 动态绑定class
第一种:通过一个布尔值判断样式类是否生效 //isActive 是在data里面布尔值, rotateRight 是 class 样式类 //isActive 为true时样式类 rotateRight 生效 <div :class"{rotateRight:isActive}">abs</div> 第二种:通…