【问题标题】:How to test for an error and specific error message using testthat in R如何使用 R 中的 testthat 测试错误和特定错误消息
【发布时间】:2019-04-14 00:57:02
【问题描述】:

我正在尝试编写一个测试,以确保在给定特定输入的情况下,一个函数

  1. 错误
  2. 提供特定的错误消息

我正在使用testthat::expect_error()

示例

作为一个非常简单、可重现的例子,假设我们有一个乘法函数

test_funct <- function(x) { x * 2 } 

还有一个非常简单的测试来测试它在提供类字符输入时是否出错:

test_that(
  "function errors when it receives a character object", 
  { test_funct("a") %>% expect_error("non-numeric argument to binary operator") } 
  )

问题

我期待这个测试通过,因为"a" 是类字符,并且确实会产生提供给expect_error()(即"non-numeric argument to binary operator")的错误消息。

但是,测试没有通过,而是返回:

Error: Test failed: 'function errors when it receives a character object'
* non-numeric argument to binary operator
1: test_funct("a") %>% expect_error("non-numeric argument to binary operator")
2: eval(lhs, parent, parent)
3: eval(lhs, parent, parent)
4: test_funct("a")

如何创建一个测试来检查函数是否出错并提供特定的错误消息?

【问题讨论】:

    标签: r testthat


    【解决方案1】:

    不要使用管道运算符。它应该可以工作,但它会抛出你得到的错误。至少使用 testthat 2.0.1 版。如果我使用下面的无管道代码,则测试通过。

    test_that(
      "function errors when it receives a character object", 
      { expect_error(test_funct("a"), "non-numeric argument to binary operator") } 
    )
    

    【讨论】:

    • 您的解决方案完美运行。我想知道为什么管道运算符不起作用(它适用于expect_equal()
    • 我希望它能够工作。你可以开一个github票,因为这个错误还没有报告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 2020-02-02
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2014-10-06
    相关资源
    最近更新 更多