Learn testthat package in R

====================================================================================


What to do first?

Install ‘testthat’ package in R

# install.packages('testthat')

Why test?

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.

Introduction to testthat

testthat package:

  1. Provides functions that make it easy to describe what you expect a function to do

  2. Easily integrates in your existing workflow

  3. Displays test progress visually, showing a pass, fail or error for every expectation

Benefits of testing

  1. Decreased frustration

  2. Better code structure

  3. Increased confidence when making changes

The structure of test

The structure of a test in R is a combination of ‘expectations’, ‘test’, context

  1. Expectations It describes what the result of a computation should be. Does it have the right value and right class?

  2. Test A test groups together multiple expectations to test one function

  3. Context A context groups together multiple tests that test related functionality

Expectations

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())

Tests

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

Contexts group together the tests that perform related test functinality

Let us look at an example