我正在为 R 函数编写一个测试用例,用于测试函数中的某个点是否抛出错误并正确捕获错误,当在 withCallingHandlers 执行期间抛出错误时,我在继续测试时遇到了一些问题(...)。我正在使用这种方法:
counter <- 0
withCallingHandlers({
testingFunction(df0, df1)
testingFunction(df2, df3)
testingFunction(df4, df5)
}, warning=function(war){
print(paste(war$message))
}, error=function(err){
print(paste(err$message))
if(err$message == paste("The function should throw this error message",
"at the right time.")){
counter <<- counter + 1
}
})
stopifnot(counter == 2)
我遇到的问题是,脚本在(成功)捕获第一个错误后退出,并且我不确定如何处理该错误,以便在捕获错误后, withCallingHandlers 只是继续执行其下一部分。我知道它与重新启动对象有关,但我不确定如何正确使用它们。有谁知道我如何操作上面的代码,以便即使捕获错误也可以继续执行 withCallingHandlers(...) ?
对于测试功能
fun1 = function() stop("something specific went wrong")
习语
obs = tryCatch(fun1(), error=conditionMessage)
exp = "something specific went wrong"
stopifnot(identical(exp, obs))
可能是 Ryan 的一个更简洁的版本,并且像他一样避免了由于错误原因而抛出错误的不幸情况。相同的范例适用于警告
fun2 = function(x) as.integer(x)
obs = tryCatch(fun2(c("1", "two")), warning=conditionMessage)
stopifnot(identical("NAs introduced by coercion", obs))
并检查“干净”评估
obs = tryCatch(fun2(c("1", "2")), warning=conditionMessage,
error=conditionMessage)
stopifnot(identical(1:2, obs))
这没问题,只要提供Sys.getlocale()
是“C”或其他不会更改条件消息翻译的编码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)