出于单元测试的目的,我想模拟另一个包中的函数。在以下示例的上下文中,我想使用mockery
包为base::mean
创建一个stub
。
在下面的示例中,在base::mean
中调用strange_mean
应该返回0
。
strange_mean <- function(...) {
base::mean.default(...)
}
# Replace mean with two
stub(where = base::mean.default,
what = 'strange_mean',
how = 0)
strange_mean(1:10)
# 5.5
# Desired: 0
library(mockery)
strange_mean <- function(...) {
base::mean.default(...)
}
# Replace mean with two
stub(where = base::mean.default,
what = 'strange_mean',
how = 0)
strange_mean(1:10)
# 5.5
strange_mean_two <- function(...) {
mean(...)
}
stub(where = mean, what = 'strange_mean_two', how = 0)
strange_mean_two(1:10)
# 5.5
alt_mean <- function(...) {
mean(...)
}
strange_mean_three <- function(...) {
alt_mean(...)
}
stub(where = alt_mean, what = 'strange_mean_three', how = 0)
strange_mean_three(1:10)
# 5.5