Search code examples
rr6

Testing private methods in R6 classes in R


I am currently using R6 classes in a project.

I would like to write unit tests that also test the functionality of private methods that I am using (preferably by not going through the more complicated public methods that are using these private methods).

However, I can't access seem to access the private methods.

How do I best do that?

Thanks!


Solution

  • Here is a solution that does not require environment hacking or altering the class you want to test, but instead creating a new class that does the testing for you.

    In R6, derived classes have access to private Methods of their base classes (unlike in C++ or Java where you need the protected keyword to archieve the same result). Therefore, you can write a TesterClass that derives from the class you want to test. For example:

    ClassToTest <- R6::R6Class(
      private = list(
        privateMember = 7,
        privateFunction = function(x) {
          return(x * private$privateMember)
        }
      )
    )
    
    TesterClass <- R6::R6Class(
      inherit = ClassToTest,
      public = list(
        runTest = function(x = 5) {
          if (x * private$privateMember != private$privateFunction(x))
            cat("Oops. Somethig is wrong\n")
          else
            cat("Everything is fine\n")
        }
      )
    )
    
    t <- TesterClass$new()
    t$runTest()
    #> Everything is fine
    

    One advantage of this approach is that you can save detailed test results in the TesterClass.