简体   繁体   English

如何使用minitest测试Ruby捕获/抛出?

[英]How to test Ruby catch/throw using minitest?

I've got some pseudo code like this: 我有一些这样的伪代码:

catch :my_error do
  first_method
  second_method
  third_method
end

def first_method
  if error_condition?
    throw :my_error
  end
end

I'm trying to use Minitest to test that the first method properly throws :my_error. 我正在尝试使用Minitest测试第一种方法是否正确抛出:my_error。 My test looks like this: 我的测试看起来像这样:

assert_throws :my_error do
  some code in here that ensures error_condition? is true
end

When I run this test, Minitest fails the test with: 当我运行此测试时,Minitest失败并显示以下信息:

Minitest::Assertion: Expected :my_error to have been thrown Minitest :: Assertion:预期会抛出:my_error

If I comment out the catch :my_error invocation, the test passes, but of course I need that code to be there in production. 如果我将catch:my_error调用注释掉,则测试通过了,但是我当然需要在生产中使用该代码。 Not sure what the point of "assert_throws" is if it doesn't work with code that has catches in it. 不知道“ assert_throws”的意义是什么,如果它不能与包含陷阱的代码一起使用,那是什么意思。

assert_throws will assert that something has been thrown, so if it is catched by your code, you cannot assert that something has been thrown! assert_throws将断言某些东西已经被抛出,因此如果您的代码捕获了该东西,您将无法断言某些东西已经被抛出!

You can assert that a specific method throws, and then that another one that calls this one does not 您可以断言某个特定的方法会抛出,然后调用该方法的另一个方法不会

Or if you change any data in the catch, you can test for this data 或者,如果您更改了捕获中的任何数据,则可以测试该数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM