如何在单元测试中重用示例?

How to reuse examples in unit tests?

假设我有一个函数,用示例记录(使用 roxygen):

#' @title Add two numbers
#' @param x a scalar
#' @param y a scalar
#' @examples 
#' testobj <- add(x + y)

add <- function(x, y) {
  return(x+y)
}

现在我想运行对生成的对象进行一些测试,以确保函数按预期运行。 为此,我将使用 testthat

context("Adding stuff")

testobj <- add(x, y) # THIS is the duplicate line that bothers me.

test_that(desc = "Additions work", code = {
  testthat::expect_length(object = x, n = 1)
})

如何重用示例中创建的testobj,然后运行在testthat中对其进行一些测试?

在这种情况下很简单,但如果函数更复杂,则会导致大量重复。

还是我用错了?

您可以使用从 utils 导出的 example 函数到 运行 函数文档中包含的示例。

testobj <- example(add)
# add> testobj <- add(x, y)

请注意,建议在您的 roxygen 评论中使用具体示例:

而不是

#' @examples 
#' testobj <- add(x, y)

使用

#' @examples 
#' testobj <- add(2, 3)