To speed some functions in R package, I have re-coded them in cpp functions using Rcpp and successfully embedded those cpp functions into this package. The next step is to test if the cpp functions can output the same results as the original functions in R. So writing tests is necessary.
However, I was stuck on this step. I have read some links Testing, R package by Hadley Wickham
and CRAN:testthat, page 11.
What I have done is that I run devtools::use_testthat()
to create a tests/testthat directory. Then, run use_catch(dir = getwd())
to add a test file tests/testthat/test-cpp.R. At this point, I think expect_cpp_tests_pass()
might work but was just stuck on it. If I have the original function called add_inflow
and add_inflow_Cpp
. How can I test if these two functions are equal?
The documentation for ?use_catch
attempts to describe exactly how the testing infrastructure for testthat
works here, so I'll just copy that as an answer:
Calling use_catch() will:
Create a file src/test-runner.cpp, which ensures that the testthat package will understand how to run your package's unit tests,
Create an example test file src/test-example.cpp, which showcases how you might use Catch to write a unit test, and
Add a test file tests/testthat/test-cpp.R, which ensures that testthat will run your compiled tests during invocations of devtools::test() or R CMD check.
C++ unit tests can be added to C++ source files within the src/ directory of your package, with a format similar to R code tested with testthat.
When your package is compiled, unit tests alongside a harness for running these tests will be compiled into your R package, with the C entry point run_testthat_tests(). testthat will use that entry point to run your unit tests when detected.
In short, if you want to write your own C++ unit tests using Catch, you can follow the example of the auto-generated test-example.cpp
file. testthat
will automatically run your tests, and report failures during the regular devtools::test()
process.
Note that the use of Catch is specifically for writing unit tests at the C++ level. If you want to write R test code, then Catch won't be relevant for your use case.
One package you might look at as motivation is the icd package -- see this file for one example of how you might write Catch unit tests with the testthat
wrappers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With