小编odd*_*sis的帖子

R tryCatch与testthat期望

我有以下功能:

fun = function(expr) {
  mc = match.call()

  env = as.environment(within(
    list(),
    expr = eval(mc$expr)
  ))

  return(env)
}
Run Code Online (Sandbox Code Playgroud)

在一个内部调用,tryCatch()以便expr优雅地处理任何错误条件.

它在标准错误条件下工作正常:

tryCatch({
  fun({
    stop('error')
  })
}, error = function(e) {
  message('error happened')
})

# error happened
Run Code Online (Sandbox Code Playgroud)

但是,它不会捕获testthat期望错误(这是我特定用例的首选):

library(testthat)

tryCatch({
  fun({
    expect_true(FALSE)
  })
}, error = function(e) {
  message('expectation not met')
})

# Error: FALSE isn't true.
Run Code Online (Sandbox Code Playgroud)

或更简单地说:

library(testthat)

tryCatch({
  expect_true(FALSE)
}, error = function(e) {
  message('expectation not met')
})

# Error: FALSE isn't true.
Run Code Online (Sandbox Code Playgroud)

期望错误未被捕获. …

r testthat

5
推荐指数
1
解决办法
355
查看次数

标签 统计

r ×1

testthat ×1