Free preview.You're sampling one lesson — enroll free to unlock all 8 lessons and track your progress.
Enroll free
lesson

Why and What to Test

Why and What to Test

In this lesson — part of Testing Fundamentals — you'll learn why and what to test in R and why it matters in real work.

Why it matters

Tests prove your code works and keep it working as you change it.

Key ideas

  • What to test
  • Arrange-Act-Assert
  • Running a test suite
  • Good vs. brittle tests

In practice

Here's how it looks in idiomatic R:

library(testthat)
add <- function(a, b) a + b
test_that("add works", {
  expect_equal(add(2, 3), 5)
  expect_type(add(1L, 1L), "integer")
  expect_error(add(1, "x"), "non-numeric")
  expect_true(is.numeric(add(0, 0)))
})

R note: testthat is the de facto standard, and expect_equal uses *approximate* numeric comparison by default (a tolerance) whereas expect_identical demands exact, type-strict equality.

Try it yourself

Exercise: In R, write three tests for a function that reverses a string.

Recap

You now understand why and what to test and can apply it in R. Mark this lesson complete and continue to the next one.