Holger Hoefling Holger Hoefling - 2 months ago 20
R Question

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!

Answer

There is currently a way to access the private environment of an R6 object. However, since this is reaching into an object in an undocumented way, it may break in the future... I don't think that will happen any time soon though.

# Gets private environment from an R6 object
get_private <- function(x) {
  x[['.__enclos_env__']]$private
}

A <- R6::R6Class("A",
  private = list(x = 1)
)

a <- A$new()

get_private(a)$x
# [1] 1
Comments