Clojure单元测试。如何测试函数是否抛出异常? [英] Clojure unit-testing. How do I test if a function throws an exception?

查看:153
本文介绍了Clojure单元测试。如何测试函数是否抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有一种方法来测试一个函数是否抛出类C的异常。但是有一种方法来测试函数是否抛出任何异常。或者断言它不应该抛出异常?

I see there's a way to test if a function throws an exception of class C. But is there a way to test whether a function throws any exception. Or to assert that it should NOT throw an exception?

推荐答案

对于不期望异常的测试, 。任何抛出的异常都会导致测试失败。

For tests that don't expect exceptions, write your test as normal. Any exceptions thrown will fail the test.

对于可能引发任何异常的测试,请使用异常 Throwable (Exception的超类)。

For tests that could throw any exception, then use Exception or Throwable (Exception's superclass).

例如:

(deftest mytest 
  (is (thrown? Exception (/ 1 0))))

(/ 1 0)会抛出一个 java.lang.ArithmeticException ,但也会匹配它的父类 java.lang.Exception

(/ 1 0) will throw a java.lang.ArithmeticException but will also be matched by it's parent class java.lang.Exception.

你也可以写一个 not-thrown? code>宏执行

You could also write a not-thrown? macro to do the opposite of the thrown? macro in clojure.test.

另一方面,你一般都是在你的电子邮件地址栏中输入nofollow> 想要在单元测试时捕获更具体的错误,因为您的代码可能会引发新的意外错误,但您的测试将很快通过。

As a side note, you generally want to catch more specific errors when you're unit testing, as your code may throw a new unexpected error but your tests will happily pass.

这篇关于Clojure单元测试。如何测试函数是否抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆