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指定的类型或子类型相同的异常。 其他任何因素都会导致测试失败。 由于它捕获子类型,因此请不要只指定ExceptionRuntimeException 。 尽量精确一些,以便您的测试尽可能有用。

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中的异常处理

kotlin中的异常处理_如何使用assertFailsWith在Kotlin中测试异常相关推荐

  1. kotlin调用类中的方法_一种轻松的方法来测试Kotlin中令人沮丧的静态方法调用

    kotlin调用类中的方法 by Oleksii Fedorov 通过Oleksii Fedorov 一种轻松的方法来测试Kotlin中令人沮丧的静态方法调用 (A stress-free way t ...

  2. java中script类_在Scripting java(javax.script)中导入一个类

    我想将我在项目中创建的类导入到我的脚本中 我这样做但它不起作用: function doFunction(){ //Objectif Mensuel importPackage(java.lang); ...

  3. r中汇率市场_如何在Word 2013表中汇总行和列

    r中汇率市场 If you're working in Word and you need to total values in a table, you can do so without havi ...

  4. spring中的设计模式_面试:设计模式在spring中的应用

    设计模式为我们解决一类问题提供了最佳的解决方案,我们在实际工作其实不太常用到,以至于会经常想不到设计模式.究其原因都是我们只是在使用别人框架的缘故,在这些框架的代码中经常能看到设计模式的影子,我们以s ...

  5. python在工作中怎么用_如何用python在工作中“偷懒”

    原标题:如何用python在工作中"偷懒" "偷懒还能干完活,才是本事 " 有些朋友在工作中会有这样的困惑:明明我从早忙到晚,为什么得到的评价还不高? 要知道, ...

  6. linux中mysql群集_阅读无群集可用性组中的Scale可用性组

    linux中mysql群集 In this article, we will explore configuring Read Scale Availability Group that does n ...

  7. python中数据读写_【循序渐进学Python——文件中数据的读写以及操作】

    [循序渐进学Python--文件中数据的读写以及操作] [循序渐进学Python--文件中数据的读写以及操作] [循序渐进学Python--文件中数据的读写以及操作] 相信大家都想过自己有一天,可以用 ...

  8. python从文件中读取数据_【Python】从文件中读取数据

    从文件中读取数据 1.1 读取整个文件 要读取文件,需要一个包含几行文本的文件(文件PI_DESC.txt与file_reader.py在同一目录下) PI_DESC.txt 3.1415926535 ...

  9. python中timeit函数_一日一技:Python中的timeit方法

    timeit()方法 python中的timeit()方法, 它用于获取代码的执行时间.该库将代码语句运行一百万次,并提供从集合中花费的最短时间.这是一种有用的方法,有助于检查代码的性能. 语法如下: ...

最新文章

  1. oracle11g分区表按时间自动创建
  2. git 拉取gitlab代码
  3. 微服务与单体架构:IT变革中企业及个体如何自处?
  4. ICCV2021多模态视频分析与推理比赛参赛邀请
  5. c语言求员工的平均分数,用C语言编程平均分数
  6. Spring学习总结(27)——Spring常用注解再总结
  7. 基于node.js的express使用mysql语句在插入数据时防重插入
  8. border-radius的8个属性值_画半圆、叶子等
  9. 用rtl8139网卡制作的bios编程器(不用并口)
  10. php正则表达式表情,php正则表达式储存展示表情字符的方法
  11. 双月数据生成及其常见算法(二)
  12. 云南省计算机一级考试题7,计算机(一级B类)云南省计算机一级考试题库.doc
  13. 【WinSock】TCP UDP Boardcast Multicast
  14. 运维工程师使用的运维平台和工具表
  15. slice,splice,split区别和作用
  16. 新课程研究杂志新课程研究杂志社新课程研究编辑部2022年第12期目录
  17. 围棋的分数计算机,围棋比赛积分规则
  18. 安徽大学计算机科学与技术学院施俊,上海大学教授施俊应邀来我院做学术报告...
  19. Visual Studio 2022下载安装
  20. 修改命令提示符和PS1变量

热门文章

  1. 后盾网php多少钱_复合排水网价格多少钱
  2. 电脑温度检测软件哪个好_一般电脑录音软件哪个好?
  3. vconsole 调试 查看LOG VUE在手机上调试 手机查看h5的日志
  4. iOS 根据中文字符串排序出字母索引
  5. Alpha 冲刺 (2/10)
  6. golang strings.Fields 使用
  7. 修改centos7的网卡名
  8. [AVR]使用AVR单片机驱动舵机
  9. Exchange 2013与OWA13集成
  10. 如何优化数据中心虚拟机布局