testthat icon indicating copy to clipboard operation
testthat copied to clipboard

Mocking for R6 methods

Open hadley opened this issue 2 years ago • 1 comments

Seems to be a popular mockery feature.

hadley avatar Oct 31 '23 18:10 hadley

See also #1936

hadley avatar Oct 22 '24 21:10 hadley

Maybe something like:

MyClass <- R6::R6Class("MyClass", public = list(
  n = function() 1
))

mock_r6_class <- function(class, public = list(), private = list()) {
  if (!inherits(class, "R6ClassGenerator")) {
    stop_input_type(class, "an R6 class definition")
  }
  R6::R6Class(
    paste0("Mocked", class$classname),
    inherit = class,
    private = private,
    public = public
  )
}

test_that("test", {
  local_mocked_bindings(
    MyClass = mock_r6_class(MyClass, public = list(
      n = function() 2
    ))
  )
  obj <- MyClass$new()
  expect_equal(obj$n(), 2)
})

hadley avatar Aug 08 '25 17:08 hadley

We could also combine the two into a single function:

local_mocked_r6_class(
  MyClass,
  public = list(
    n = function() 2
  )
)

hadley avatar Aug 08 '25 17:08 hadley