====================================================================================
Install ‘testthat’ package in R
# install.packages('testthat')
Testing is something which should always be done but it is a little painful and boring It is not that we do not test our code, it is just that we do not store our tests so that they can be re-run automatically.
testthat package:
Provides functions that make it easy to describe what you expect a function to do
Easily integrates in your existing workflow
Displays test progress visually, showing a pass, fail or error for every expectation
Decreased frustration
Better code structure
Increased confidence when making changes
The structure of a test in R is a combination of ‘expectations’, ‘test’, context
Expectations It describes what the result of a computation should be. Does it have the right value and right class?
Test A test groups together multiple expectations to test one function
Context A context groups together multiple tests that test related functionality
An expectation is the finest level of testing. Anything that you want to check is done through this. For example ‘I expect that the output should be a datframe.’
There are 11 different expectation functions that we can use.
# Passes expect_that(10, equals(10))
# Passes expect_that(c("one" = 1, "two" = 2), is_equivalent_to(1:2))
# shows_message() checks that an expression shows a message:
# gives_warning() expects that you get a warning:
# expect_that(log(-1), gives_warning())
Each test should test a single functionality of the code and should have an informative name When there’s a failure, it’s the test name that will help you figure out what’s gone wrong. A test name must start with ‘test’ so that the package is able to understand that it is a test file
Contexts group together the tests that perform related test functinality