Add the necessary infrastructure to enable C++ unit testing
in R packages with Catch and
The directory containing an R package.
Create a file
src/test-runner.cpp, which ensures that the
testthat package will understand how to run your package's
Create an example test file
showcases how you might use Catch to write a unit test,
Add a test file
tests/testthat/test-cpp.R, which ensures that
testthat will run your compiled tests during invocations of
R CMD check, and
Create a file
R/catch-routine-registration.R, which ensures that
R will automatically register this routine when
tools::package_native_routine_registration_skeleton() is invoked.
You will also need to:
Add xml2 to Suggests, with e.g.
Add testthat to LinkingTo, with e.g.
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. Here's a simple example
of a unit test written with
testthat + Catch:
1 2 3 4 5 6
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
will use that entry point to run your unit tests when detected.
All of the functions provided by Catch are
available with the
CATCH_ prefix – see
for a full list.
testthat provides the
following wrappers, to conform with
|| ||The context of a set of tests.|
|| ||A test section.|
|| || Test that an expression evaluates to
|| || Test that an expression evalutes to
|| ||Test that evaluation of an expression throws an exception.|
|| ||Test that evaluation of an expression throws an exception of a specific class.|
In general, you should prefer using the
testthat also does some work to
ensure that any unit tests within will not be compiled or
run when using the Solaris Studio compilers (as these are
currently unsupported by Catch). This should make it
easier to submit packages to CRAN that use Catch.
If you've opted to disable dynamic symbol lookup in your
package, then you'll need to explicitly export a symbol
in your package that
testthat can use to run your unit
testthat will look for a routine with one of the names:
1 2 3
C_run_testthat_tests c_run_testthat_tests run_testthat_tests
If you'd like to write your own Catch test runner, you can
instead use the
testthat::catchSession() object in a file
with the form:
1 2 3 4 5 6 7 8
This can be useful if you'd like to run your unit tests with custom arguments passed to the Catch session.
If you'd like to use the C++ unit testing facilities provided
by Catch, but would prefer not to use the regular
R testing infrastructure, you can manually run the unit tests
by inserting a call to:
.Call("run_testthat_tests", PACKAGE = <pkgName>)
as necessary within your unit test suite.
Catch, the library used to enable C++ unit testing.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.