【问题标题】:How to run code after test failure with testthat?测试失败后如何使用 testthat 运行代码?
【发布时间】:2021-06-05 02:00:46
【问题描述】:

这是我的测试文件:

## test-foo_files.R

## Setup
dir.create("temp")
file.create("temp/file1.R")
file.create("temp/file2.R")

## test
test_that("List all R files works", {
  expect_equal(list_R_scripts("temp"), c("file1.R", "file2.R"))
})

## Cleaning
unlink("temp")

即使测试失败,如何让清洗部分运行?

【问题讨论】:

    标签: r tdd testthat


    【解决方案1】:

    @Waldi 的回答是正确的,但多亏了他,经过一番研究,我找到了一种更清洁的方法。

    它被称为fixtures(参见here)并与包withr一起使用。

    withr::defer() 解决了on.exit() 函数的一些缺点。

    一个简洁的设计来组织所有这些,是使用 setup-xxx.R 这样的文件:

    ## tests/testthat/setup-dir-with-2-files.R
    fs::dir_create("temp")
    fs::file.create(paste0("temp/", c("file1.R", "file2.R"))
    
    withr::defer(fs::dir_delete("temp"), teardown_env())
    

    测试文件现在是:

    ## tests/testthat/test_list_r_scripts.R
    test_that("List all R files works", {
      expect_equal(list_R_scripts("temp"), c("file1.R", "file2.R"))
    })
    

    【讨论】:

      【解决方案2】:

      你可以使用on.exit:

      ## test-foo_files.R
      
      ## Setup
      temp <- tempdir()
      ## Triggered cleaning
      on.exit(unlink(temp))
      
      file.create("file1.R")
      file.create("file2.R")
      
      ## test
      test_that("List all R files works", {
        expect_equal(list_R_scripts("temp"), c("file1.R", "file2.R"))
      })
      
      

      【讨论】:

        猜你喜欢
        • 2012-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 2017-03-22
        • 1970-01-01
        • 2022-11-02
        相关资源
        最近更新 更多