【问题标题】:How to reuse examples in unit tests?如何在单元测试中重用示例?
【发布时间】:2017-08-30 12:26:10
【问题描述】:

假设我有一个函数,用一个例子记录(使用 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 中对其进行一些测试?

在这种情况下它是微不足道的,但如果函数更复杂,它会导致大量重复。

还是我用错了?

【问题讨论】:

  • 我现在添加了一个issue for testthat,以考虑添加一种更惯用的方式来在测试、示例、小插曲等之间共享代码/对象。

标签: r unit-testing documentation roxygen2 testthat


【解决方案1】:

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

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

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

代替

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

使用

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

【讨论】:

    猜你喜欢
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    相关资源
    最近更新 更多