1

Assuming I want to write unit tests for the following function using the package testthat:

make_matrix = function(vec) {
    matrix(vec, nrow=2)
}

The expected function is as follows:

make_matrix(seq(1:4))
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Following suggestions on SO I will store the input for the test functions in inst/testdata Where should I put data for automated tests with testthat?

#input = system.file("testdata/input.rds, package "my_package")
input = seq(1:4)

# expected_output_for_seq_1_4 = readRDS()/system.file()?
expected_output_for_seq_1_4 = matrix(c(1,2,3,4), nrow=2)

test_that("basic_test", {
    expect_equal(make_matrix(input), expected_output_for_seq_1_4)
})

But where and how shall I store the expected outputs? Also in inst/testdata? Given a more complex function there could be many expected outputs for a single input dependent on the functions' parameters

MrNetherlands
  • 920
  • 7
  • 14

1 Answers1

0

I came up with two options:

Option 1: Rdata files at inst/testdata

As per the most accepted answer in the linked question, I would go to save it in inst/testdata, but using RData files that allows saving multiple objects in one file. This way you can save all the expected outputs for related tests in the same file:

inst/testdata/expected_outputs_function1.Rdata # contains all the outputs for function1
inst/testdata/expected_outputs_function2.Rdata # contains all the outputs for function2

Option 2: R files to generate the outputs on the fly

However, if the project/package is complex, or it needs big expected outputs, the previous method can generate RData files that exceed the package size policy at CRAN (only relevant if you want to upload the package to CRAN). So, other option is store the code generating the expected outputs in inst/testdata/expected_outputs.R and add source(system.file("testdata/expected_outputs.R", package "my_package")) before executing the tests:

expected_outputs.R

expected_output_for_seq_1_4 <- matrix(c(1,2,3,4), nrow=2)
expected_output_for_data_frame <- {code to generate output for data_frame here}
{...}

Drawback for this method is that if the expected outputs take long time to calculate, tests are not gonna be fast.

MalditoBarbudo
  • 1,815
  • 12
  • 18