如何使用mockery :: stub

时间:2019-05-08 13:40:14

标签: r function unit-testing mocking scoping

出于单元测试的目的,我想模拟另一个包中的函数。在以下示例的上下文中,我想使用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

0 个答案:

没有答案