繁体   English   中英

测试失败后如何使用 testthat 运行代码?

[英]How to run code after test failure with testthat?

这是我的测试文件:

## 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")

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

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

它被称为fixtures (参见此处)并与 package withr

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

组织所有这些的一种简洁设计是使用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"))
})

您可以使用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"))
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM