Search code examples
runit-testingclosurestestthat

How to test a function within a function in R?


I would like to use the testthat package to test a function that is enclosed by another function.

How can I test such a function?

If this is not possible, how can I refactor the code so that testing objective_function is possible?


Illustrative Example

model <- function(parameter) {
  objective_function <- function(x) {
    (x - p)^2
  }

  # Make parameter integer
  p <- round(parameter)
  result <- optimize(objective_function, c(-10, 10))
  result$minimum
}

# Works
testthat::expect_equal(model(4.2), 4)

# Does not work
# And how would you pass p to the following?
testthat::expect_equal(objective_function(4.2), 4)
#> Error in objective_function(4.2): could not find function "objective_function"

Created on 2019-05-13 by the reprex package (v0.2.1)


Solution

  • Another approach: explicitly set function scope within model function:

    objective_function <- function(x) {
      (x - p)^2
    }
    
    model <- function(parameter) {
      # Make parameter integer
      p <- round(parameter)
      environment(objective_function) <- environment()
      result <- optimize(objective_function, interval=c(-10, 10))
      result$minimum
    }
    
    model(4.2)
    
    p <- 4
    objective_function(4.2)