用testthat在哪里放置库调用?

问题描述 投票:6回答:2

我正在寻找最好的实践帮助与辉煌的testthat。你的library(xyzpackage)调用使用所有包功能的最佳位置在哪里?

我首先设置了runtest.R设置路径和包。然后我运行test_files(test-code.R),它只保存上下文和测试。结构示例如下:

# runtests.R
library(testthat)
library(data.table)

source("code/plotdata-fun.R")

mytestreport <- test_file("code/test-plotdata.R")

# does other stuff like append date and log test report (not shown)

在我的测试文件中,例如test-plotdata.R(精简版):

#my tests for plotdata
context("Plot Chart")

test_that("Inputs valid", {

  test.dt  = data.table(px = c(1,2,3), py = c(1,4,9))
  test.notdt <- c(1,2,3)

  # illustrating the check for data table as first param in my code
  expect_error(PlotMyStandardChart(test.notdt, 
                                   plot.me = FALSE),
                "Argument must be data table/frame")

  # then do other tests with test.dt etc...
})
  1. 这是@hadley打算使用的方式吗?从journal article不清楚。我是否也应该在我的测试文件中复制库调用?您是否需要在每个上下文中设置库,或者只需要在文件开头设置一个库?
  2. 中过度调用库(包)是否可以?
  3. 要使用test_dir()和其他功能,最好的方法是设置文件。我在我的函数中使用require(),但我也在上下文中设置了测试数据示例。 (在上面的例子中,您将看到我需要用于test.dt的data.table包以在其他测试中使用)。

谢谢你的帮助。

r testing testthat
2个回答
4
投票

一些建议/意见:

  • 设置每个文件,以便它可以使用test_file自行运行,无需额外设置。这样,如果您只关注较大项目的一小部分,则可以在开发时轻松运行单个文件(如果运行所有测试的速度很慢,则非常有用)
  • 多次调用library几乎没有什么惩罚,因为该函数首先检查包是否已经附加
  • 如果你设置每个文件,以便它可以使用test_file运行,那么test_dir将工作正常,而无需做任何额外的事情
  • 您不需要在任何测试文件中使用library(testthat),因为可能是您使用test_filetest_dir运行它们,这需要加载testthat

另外,你可以看看Hadley最近的一个包装,看看他是如何做到的(例如dplyr tests)。


0
投票

如果您使用devtools::test(filter="mytestfile"),那么devtools将负责为您调用帮助文件等。通过这种方式,您无需执行任何特殊操作即可使测试文件自行运行。基本上,这与运行测试时相同,但在test_mytestfile.R文件夹中只有testthat

© www.soinside.com 2019 - 2024. All rights reserved.