簡體   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