2

Let say I have the function

mean_wrapper <- function(x) {
  mean(x)
}

How can I check if the mean function is called?

An use case is for instance If I want to check this behavior in a unit test.

EDIT:

I make another exampe to be clearer. Let consider this function:

library(readr)
library(magrittr)

read_data <- function(file_name) {
  read_csv(file_name) %>%
    validate_data()
}

The aim of read_data is to read a CVS file and validate it. validate_data performs some checks on the data. It raises an error if one of them fail, otherwise returns the input object.

I want to test both functions but I don't want replicate the same tests I wrote for validate_data in the case of read_data. Anyway I have to check that the latter function has been called in read_data, so I wolud like to write a test that does this for me.

4
  • 2
    Check this tutorial to maybe get you started thinking about unit testing in R. There is a package called RUnit for unit testing. Commented Aug 21, 2017 at 13:56
  • Actually I need a strategy to check the call in a unit test, in general I know how to perform unit test :) Commented Aug 21, 2017 at 13:59
  • I'm not sure if I understand what you need. Can you explain in more detail? Maybe crawl the expression tree returned by body(mean_wrapper) for an expression of more than two elements with mean as the first element? Commented Aug 21, 2017 at 14:12
  • I'll edit the question so that what I am asking should be clearer Commented Aug 21, 2017 at 14:29

1 Answer 1

2

You could trace mean:

trace(mean, tracer = quote(message("mean was called")))
mean_wrapper(3)
#Tracing mean(x) on entry 
#mean was called
#[1] 3
untrace(mean)
#Untracing function "mean" in package "base"

Instead of a message you can use anything (e.g., assignment to a variable in the enclosing environment) as tracer.

Sign up to request clarification or add additional context in comments.

2 Comments

That's an interesting approach, I am checking if it works for me.
The approach works when I use devtools::test() but it doesn't when I use devtools::check(document = FALSE) or in the CI environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.