Exploring expect statements

Developing R Packages

Jasmin Ludolf

Content Developer

Most common expect statements

  • Expect statements validate R functions, or units

In testthat package:

  • expect_equal(): equality with small tolerance allowed
  • expect_identical(): exact equality

  • expect_output(): matching text from object call

 

  • expect_error(): error from object call
    • Errors stop code execution; warnings don't
  • expect_warning(): warning produced by object call
Developing R Packages

From example to unit test

#' @examples
#' # Convert 32F to C
#' temp_converter(32, "Fahrenheit", "Celsius")
[1] 0

In the tests/testthat/test-temp_converter.R file:

library(testthat)
expect_equal(

object = temp_converter(32, "Fahrenheit", "Celsius"),
expected = 0
)
Developing R Packages

Expecting identical and expecting equal

expect_identical()

expect_identical(sqrt(3) ^ 2, 3)
Error: sqrt(3)^2 (`actual`) not 
identical to 3 (`expected`).

  `actual`: 2.9999999999999996
`expected`: 3.0000000000000000

expect_equal()

  • Use expect_equal() when comparing numeric values
expect_equal(sqrt(3) ^ 2, 3)
  • expect_equal()
    • Allows for small differences
    • Has a tolerance argument, default usually good
Developing R Packages

Expecting output

expect_output(

print("Testing R Packages is fun"),
"funk"
)
Error: `print\("Testing R Packages is 
fun"\)` does not match "funk".
Actual value: "\[1\] "Testing R 
Packages is fun""

Output diagram

Developing R Packages

Expecting warning

expect_warning(
  temp_converter(-40, 
                 "Celsius", 
                 "Celsius")
)

Warning sign

Developing R Packages

Expecting error

expect_error(
  temp_converter(300, 
                 "Kelvin", 
                 "Fahrenheit")
)

Error sign

Developing R Packages

Recap

  • Each expectation should test an aspect of a function
  • When combined together, 100% of function aspects should be covered by unit tests
Developing R Packages

Let's practice!

Developing R Packages

Preparing Video For Download...