首页 > 解决方案 > 失败时报告来自 test_that 块的额外信息

问题描述

我想cat()在测试失败的情况下向控制台提供一些信息(我确信这不会发生,但我无法证明它不会发生),以便我可以调查这个问题。

现在我有大约是这样的代码:

testthat::test_that('Maybe fails', {
  seed <- as.integer(Sys.time())
  set.seed(seed)
  
  testthat::expect_true(maybe_fails(runif(100L)))
  testthat::expect_equal(long_vector(runif(100L)), target, tol = 1e-8)

  if (failed()) {
    cat('seed: ', seed, '\n')
  }
})

不幸的是,failed()不存在。

的返回值expect_*()似乎没有用,它们只是返回实际参数。

我正在考虑再次检查使用all.equal(),但这是一个非常丑陋的重复。

标签: rtestingtestthat

解决方案


代替 using cat,您可以使用由info管理的参数testthat及其reporters用于所有expect函数(出于兼容性原因保留参数):

library(testthat)

testthat::test_that("Some tests",{
  
  testthat::expect_equal(1,2,info=paste('Test 1 failed at',Sys.time()))
  testthat::expect_equal(1,1,info=paste('Test 2 failed at',sys.time()))

})
#> -- Failure (<text>:5:3): Some tests --------------------------------------------
#> 1 not equal to 2.
#> 1/1 mismatches
#> [1] 1 - 2 == -1
#> Test 1 failed at 2021-03-03 17:25:37

推荐阅读