【问题标题】:Printing custom diagnostic information if `testthat` test fails in `R`如果 `testthat` 测试在 `R` 中失败,则打印自定义诊断信息
【发布时间】:2015-01-11 17:48:18
【问题描述】:

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

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

但是,我真的很想看看函数的实际输出,即打印返回的data.frame。如果testthat 测试失败,有没有办法打印测试函数的输出(或其他一些自定义诊断信息)?

【问题讨论】:

    标签: r unit-testing testthat


    【解决方案1】:

    间接地,是的!如果你查看expect_that 的参数,你会看到“info”参数——你可以在这里抛出一个匿名函数或调用来打印结果。所以,类似:

    expect_that(df.orig, is_identical_to(df.expected), info = print(df.orig))
    

    这样做的缺点是它会/总是/打印 df.orig 或类似的信息,即使测试通过了。

    唯一的另一种方法是使用 tryCatch;类似:

    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_that 调用产生错误,它只会打印 df.orig,你可以输出......嗯,你想要的任何东西,你可以产生不同的错误与警告的结果。然而,相当粗糙。

    【讨论】:

      【解决方案2】:

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

      b <- expect_that(df.orig, is_identical_to(df.expected))
      
      if (!b$passed){
      
          #do something
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-02
        • 2023-03-10
        • 2021-05-19
        • 2014-10-19
        相关资源
        最近更新 更多