Mock new

mock.new is a function in R that creates a new mock object. A mock object is a fake object that mimics the behavior of a real object, but doesn't actually interact with the outside world. It's often used in unit testing to isolate the code being tested and make it easier to predict the behavior of the code.

Here's an example of how you might use mock.new in R:

library(mockr)

# Create a mock object that mimics the behavior of a file
file_mock <- mock.new("file")

# Set up the mock object to return a specific value when the "read" method is called
file_mock$read <- function() {
  "Hello, world!"
}

# Use the mock object in your code
file <- file_mock
read_file <- function(file) {
  file$read()
}

# Test the code
result <- read_file(file)
print(result)  # Output: "Hello, world!"

In this example, we create a mock object that mimics the behavior of a file. We then set up the mock object to return a specific value when the "read" method is called. Finally, we use the mock object in our code and test it to make sure it behaves as expected.

mock.new is a powerful tool for isolating dependencies and making your code easier to test. It's often used in conjunction with other testing tools and techniques, such as mocking and stubbing, to create a robust and reliable testing strategy.