【发布时间】:2018-10-30 12:03:12
【问题描述】:
我在我的代码中从 base 调用一个函数,我想在我的 testthat 单元测试中模拟这个函数。
我该怎么做?
library(testthat)
my.func <- function() {
return(Sys.info()["sysname"]) # e. g. "Linux"
}
my.func()
# sysname
# "Linux"
test_that("base function can be mocked",
with_mock(
Sys.info = function() return(list(sysname = "Clever OS")), # see edit 2 !!!
expect_equal(my.func(), "Clever OS", fixed = TRUE)
)
)
# Error: Test failed: 'base function can be mocked'
# * my.func() not equal to "Clever OS".
?with_mock 说:
基础包中的函数不能被模拟,但这可以工作 通过定义一个包装函数来轻松解决。
我可以通过我从my.func 调用的包装函数封装对Sys.info() 的基本函数调用,但是假设我不能这样做,因为我正在测试我无法更改的包中的函数...
有什么解决办法吗?
我在 Ubuntu 14.04 上使用 R3.4.4 64 位和 testthat 2.0.0.9000。
编辑 1:
使用
`base::Sys.info` = function() return(list(sysname = "Clever OS"))
导致testthat 错误消息:
不能模拟基础包(base)中的函数
编辑2:正如@suren在他的回答中显示的那样,我的代码示例是错误的(模拟函数返回另一个类,然后返回原始类:-(
正确的模拟函数应该是:Sys.info = function() return(c(sysname = "Clever OS"))
【问题讨论】: