I'm using testthat package for unit testing in R. I have a function CalcByResultSubModel which has one more function CalculateX which is called inside the main function. This is the main function,
CalcByResultSubModel = function(doll_data, fn_master, modelPath) {
# load sub model result
load(modelPath)
# calculation
for(abc in c("ABC", fn_master$fn_a)) {
# columns
col_name = paste0("x", abc)
iterModel = resultSubmodel[[abc]]
# calculate yhat X
doll_data[, col_name] = iterModel %>%
purrr::map(., function(imodel) {
CalculateX(data, imodel)
}) %>%
as.data.frame(.) %>%
apply(., 1, mean)
message(paste(col_name, "calculated"))
}
This is the function CalculateX
CalculateX = function(data, model) {
iterData = data %>%
dplyr::select(model$feature_names) %>%
as.matrix(.)
set.seed(131)
result = predict(model, iterData, missing = NA)
result = matrix(result, 2)[2, ]
return(result)
}
Inorder to perform unit testing we have to mock the function CalculateX. But the complexity here is that, the function is called inside for loop in the main function. I'm quite new to this scenario in my unit testing. Can anyone help me with the mocking of the function in a for loop? This is the code for mocking and I tried this.
local_mock(CalculateX = function(data, model){
for (abc in c("ABC", fn_master$fn_a)
case_when(
abc == "feature1" ~ .ReadCsvWrapper("feature1.csv"),
abc == "feature2" ~ .ReadCsvWrapper( "feature2.csv"),
abc == "feature3" ~ .ReadCsvWrapper("feature3.csv"))
})
But the above approach doesn't seem to work for me. Can anyone help me with this?