-
Notifications
You must be signed in to change notification settings - Fork 316
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add examples how to mock objects #1936
Comments
Like |
I'll try it :D |
I just have no idea how to do it for R6:
|
What are you trying to do? |
I will try to give more real-life example. I tried to minimize my code to reprex.
I want to test the
Such messages are returned by GraphQL API when queries are too large, but I don't want to connect to API in this test. |
@hadley I did it more reprex 😃 :
So as shown above, I want to mock response object. But it does not seem to work when I run it:
|
I feel like for R6 objects the natural way to mock them is to create a subclass. e.g. something like this: TestObject <- R6::R6Class(
"TestObject",
public = list(
method_wrapper = function() {
response <- self$request_method_one()
if (private$is_wrong(response)) {
message("Switching to method two.")
response <- self$request_method_two()
}
response
},
request_method_one = function() {
"assuming nice response"
},
request_method_two = function() {
"for sure nice response"
}
),
private = list(
is_wrong = function(response) {
any(grepl("wrong", response))
}
)
)
R6Mock <- function(class, public = list(), private = list()) {
R6::R6Class(
paste0("Mocked", class$classname),
inherit = class,
private = private,
public = public
)$new()
}
test_that("test", {
x <- R6Mock(TestObject, private = list(
is_wrong = function(response) {
TRUE
}
))
expect_equal(x$method_wrapper(), "for sure nice response")
}) |
Thanks @hadley this looks pretty cool! Definitely I will make use of it. For the time being I still used Still, would be great to have such example anywhere in |
With
3.2.1
it is reported that great functionslocal_mocked_bindings()
(really, I love them, started to switch frommockery
) can mock also objects.Still, there is no example how to do it in function docs. Can you provide it?
The text was updated successfully, but these errors were encountered: