我正在使用该testthat库在R项目中进行单元测试.我想测试依赖于数据库查询的代码,但不测试实际的查询本身.换句话说,我想模拟数据库连接和查询(让它们返回预定的数据集或命中测试数据库).
我知道Ruby中有很多宝石,以及其他语言中的其他宝石,它们提供了这种功能.R有什么类似的吗?或者我该如何完成它?
some_file.R:
sqlQuery <- function(some_query) {
chnl <- odbcConnect(get.db.name())
data <- sqlQuery(chnl, query)
}
Run Code Online (Sandbox Code Playgroud)
从测试文件:
test_that("test query", {
dataset <- sqlQuery("SELECT * FROM some_database_table")
#How to make this not actually hit the production database?
expect_equal(nrow(dataset), 2)
} )
Run Code Online (Sandbox Code Playgroud)
如果没有方便的包,testthat::with_mock()我最好的选择?
如何在RHS上使用变量列名:= operations?例如,给定此data.table"dt",我想创建两个新列"first_y"和"first_z",其中包含对"x"值的给定列的第一次观察.
dt <- data.table(x = c("one","one","two","two","three"),
y = c("a", "b", "c", "d", "e"),
z = c(1, 2, 3, 4, 5))
dt
x y z
1: one a 1
2: one b 2
3: two c 3
4: two d 4
5: three e 5
Run Code Online (Sandbox Code Playgroud)
如果没有变量列名,您可以这样做.
dt[, c("first_y", "first_z") := .(first(y), first(z)), by = x]
dt
x y z first_y first_z
1: one a 1 a 1
2: one b 2 a 1
3: two c 3 c 3
4: …Run Code Online (Sandbox Code Playgroud)