如果`testthat`测试在`R中失败,则打印自定义诊断信息`

如果`testthat`测试在`R中失败,则打印自定义诊断信息`,r,unit-testing,testthat,R,Unit Testing,Testthat,我使用testthat单元测试来检查函数返回的data.frame是否与我期望它返回的相同。如果测试失败,test将打印一些诊断信息,例如: MyFunction(df.orig) is not identical to df.expected. Differences: Names: 1 string mismatch 但是,我确实希望看到函数的实际输出,即打印返回的data.frame。如果测试失败,是否有办法打印测试功能的输出(或其他一些自定义诊断信息)?间接地,是的!如果您查看exp

我使用
testthat
单元测试来检查函数返回的
data.frame
是否与我期望它返回的相同。如果测试失败,
test将打印一些诊断信息,例如:

MyFunction(df.orig) is not identical to df.expected. Differences: 
Names: 1 string mismatch

但是,我确实希望看到函数的实际输出,即打印返回的
data.frame
。如果
测试失败,是否有办法打印测试功能的输出(或其他一些自定义诊断信息)?

间接地,是的!如果您查看
expect_that
的参数,您将看到“info”参数-您可以在此处抛出一个匿名函数或调用以打印结果。比如说:

expect_that(df.orig, is_identical_to(df.expected), info = print(df.orig))
tryCatch(
    expr = {
        expect_that(df.orig, is_identical_to(df.expected))
    }, 
    error = function(e){
        print(e)
        print(df.orig)
        #And anything else you want to only happen when errors do
    }
)
这样做的缺点是,即使测试通过,它也会/始终/打印df.orig或类似信息

唯一的另一种方法是使用tryCatch(唯一能确保它只在发生错误时触发的方法);比如:

expect_that(df.orig, is_identical_to(df.expected), info = print(df.orig))
tryCatch(
    expr = {
        expect_that(df.orig, is_identical_to(df.expected))
    }, 
    error = function(e){
        print(e)
        print(df.orig)
        #And anything else you want to only happen when errors do
    }
)

这看起来很笨重,但有两个优点-如果调用的expect_产生错误,它将只打印df.orig,您可以输出…嗯,任何您想要的,并且您可以为错误和警告生成不同的结果。但是,相当粗糙。

您可以将expect\u的结果存储在一个临时变量b中,检查它是否在it构造中失败并返回b

b <- expect_that(df.orig, is_identical_to(df.expected))

if (!b$passed){

    #do something
}
b