【发布时间】:2021-12-29 20:18:41
【问题描述】:
我在 R 中有一个函数如下
DrawDistroGenerationClass <- function(in_hourStr, in_data){
me <- methods::setRefClass(
## Define the environment where this list is defined so
## that I can refer to it later.
"Draw",
fields = list(hourStr = "character",
data = "numeric"),
methods = list(
getModel = function(){
return("Draw Distro")
},
getName = function(){
return(hourStr)
},
#'
#' @param strName the data to be drawn from
#' @return the new hours value
generateHoursFromStorage = function(strName){
indSelect <- stats::runif(1, min = 1, max = length(data))
componentLife <- data[indSelect]
return(componentLife)
}
)
)
## Set the name for the class
newMe <- me$new(hourStr = in_hourStr, data = in_data)
return(newMe)
}
测试看起来像......
test_that("test Time2Repair-DrawDistroHoursGenerationClass", {
distroHoursGenerationClass <- DrawDistroHoursGenerationClass("test", c(0.0, 1.0, 2.0, 3.0))
testthat::expect_equal(distroHoursGenerationClass$getModel(), "Draw Distro")
testthat::expect_equal(distroHoursGenerationClass$getName(), "test")
testthat::expect_true(is.numeric(distroHoursGenerationClass$generateHoursFromStorage("test")))
}
)
目的是我可以使用标签和一组值调用函数 DrawDistroGenerationClass,并生成一个函数,该函数将在调用时从该集合中随机抽取。
该功能有效,但在我的 R 项目中,我对此功能有一个单元测试(testthat),当我运行 R cmd 时,我得到:
- -methods::setRefClass(...)
- -methods::setClass(...)
- -methods::assignClassDef(Class, classDef, where)
- -base::assign(mname, def, where)
“assign(mname, def, where) 中的错误:无法将绑定添加到锁定的环境”。
我不知道为什么会出现这个问题/
我宁愿不让我的输入变量全局化(因为它们可能与其他类冲突),我在这里使用 setRefClass 方法,因此我可以制作这个函数的许多独立版本。
【问题讨论】:
-
在您分享重现错误的测试代码之前,我们无法开始诊断错误。
-
RPost 已更新测试。单独运行测试通过,但是当使用 R cmd check 运行测试时(在项目中)它失败并报告错误。
标签: r unit-testing oop