R
R packages
Best practices
Testing series · part 2

Test design: fixtures, temporary state and mocking

Keep unit tests isolated, deterministic, and free of persistent side effects

Isolate test state with withr, manage fixtures cleanly in testthat 3e, and mock boundary functions to build repeatable verification suites.
Published

2026-09-26

Modified

2026-09-27

The problem

In the first post in this series, we set up automated tests to replace manual console checks. But as a test suite grows, a subtler set of failures emerges: tests that pass when run on their own, but fail when run together.

You hit devtools::test() or run tests in CI, and suddenly assertions break:

  • State leaks across tests: A test sets options(OutDec = ",") or changes an environment variable, and downstream tests fail because the global session was silently mutated.
  • Leftover files and directories: A test writes scratch outputs to the project folder, leaving artefacts behind or failing on subsequent runs because the file already exists.
  • Shifting working directories: A test calls setwd(), hits an unexpected error before resetting it, and leaves the remaining suite pointing at the wrong path.
  • Non-deterministic dependencies: Code that calls Sys.Date(), Sys.time(), or an external API behaves differently on Monday than it did on Friday, or fails entirely when run offline.
  • Bloated, brittle test data: Developers copy whole production tables or hand-craft fragile 1,000-row data frames with inconsistent column types, making tests slow to run and painful to maintain.

Unit tests must be hermetic: each test should run in a clean sandbox, execute independently in any order, and leave the environment exactly as it found it.

The web-repo way

In JavaScript and TypeScript repositories, frameworks such as Vitest and Jest solve isolation and determinism with explicit lifecycle hooks, fixture loaders, and first-class mocking APIs:

// src/trial-tracker.test.ts
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { daysSinceEnrollment } from "./trial-tracker";

describe("daysSinceEnrollment", () => {
  beforeEach(() => {
    // Freeze the clock to a deterministic date
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-09-26"));
  });

  afterEach(() => {
    // Restore global state completely
    vi.useRealTimers();
    vi.restoreAllMocks();
  });

  it("calculates elapsed days from enrollment", () => {
    expect(daysSinceEnrollment("2026-09-20")).toBe(6);
  });
});

Web repositories rely on three fundamental test-design principles:

  1. Deterministic boundaries: Timers, network requests, and external clocks are frozen or replaced during the test.
  2. Teardown always runs: Setup logic in beforeEach is paired with cleanup in afterEach, ensuring that even when a test throws an unhandled error, the global environment is reset.
  3. Dedicated fixtures: Persistent sample inputs live in a dedicated fixtures/ folder, decoupled from application code.

The R way

In R, the combination of testthat (3rd edition) and withr provides a tidier model. Rather than pairing setup and teardown callbacks, you call scoped local_*() functions that undo their change automatically when the calling function (or test_that() block) finishes.

1 · Structuring test fixtures in testthat 3e

testthat reserves specific file prefixes and folder conventions inside tests/testthat/:

Path / File pattern Loading behaviour Best used for
tests/testthat/helper-*.R Sourced by devtools::load_all() and devtools::test() Shared fixture generators, domain data factories, custom expectations
tests/testthat/setup*.R (e.g. setup.R) Run once before the tests; not sourced by load_all() Session-wide options, global test database connections
tests/testthat/fixtures/ Ignored by test runners; paths resolved with test_path() Static reference files (CSVs, JSON, clinical domain subsets)

Static fixtures with test_path()

When tests run, your working directory changes depending on context: running interactively, running via devtools::test(), or running under R CMD check (where the directory is set to a temporary check folder).

Never use relative file paths like "../../fixtures/input.csv". Instead, use testthat::test_path(), which always constructs paths relative to tests/testthat/:

test_that("read_lab_data() ingests raw vendor files", {
  raw_file <- testthat::test_path("fixtures", "sample_labs.csv")
  res <- read_lab_data(raw_file)

  expect_s3_class(res, "data.frame")
  expect_equal(nrow(res), 5)
})

Shared helpers in helper-*.R

Files named tests/testthat/helper-*.R run before test execution. Because devtools::load_all() sources them too, your fixture generators are immediately available while you develop interactively in the console.

2 · Managing temporary state with withr

The withr package provides local_*() functions that alter state for the lifetime of the current environment (such as a test_that() block) and restore the prior state when that environment closes.

If a test fails halfway through, withr still restores the original settings.

test_that("formatting respects decimal and directory settings", {
  # 1. Temporary directory: automatically removed when this test block exits
  temp_dir <- withr::local_tempdir(pattern = "study-export")

  # 2. Temporary option: OutDec restored to "." when test block exits
  withr::local_options(OutDec = ",")

  # 3. Temporary environment variable: un-set when test block exits
  withr::local_envvar(ANALYSIS_ENV = "test")

  # 4. Temporary working directory: reverted when test block exits
  withr::local_dir(temp_dir)

  # 5. Temporary seed: previous RNG state restored when test block exits
  withr::local_seed(2026)

  # The code under test sees the temporary settings
  writeLines("PARAM,VAL", "results.csv") # written inside temp_dir
  expect_true(file.exists("results.csv"))
  expect_equal(format(1.5), "1,5")
  expect_equal(Sys.getenv("ANALYSIS_ENV"), "test")
})

Writing your own local_*() helpers

You can write domain-specific fixture helpers using withr::defer() and the .local_envir argument:

# Inside tests/testthat/helper-fixtures.R

local_scratch_file <- function(lines, filename = "input.txt", .local_envir = parent.frame()) {
  temp_dir <- withr::local_tempdir(.local_envir = .local_envir)
  file_path <- file.path(temp_dir, filename)
  writeLines(lines, file_path)

  # Any extra clean-up goes in defer(); it runs when the calling test ends
  withr::defer(unlink(file_path), envir = .local_envir)

  file_path
}

When called inside a test_that() block, .local_envir = parent.frame() binds the lifetime of the scratch directory and its deferred cleanup to that specific test. When the test completes, the folder is pruned automatically.

3 · Mocking with testthat::local_mocked_bindings()

Tests that rely on Sys.Date(), Sys.time(), or external HTTP services are prone to transient failures. local_mocked_bindings() (testthat 3.1.7 and later) is the tool for this now. The older with_mock() and local_mock() were deprecated in testthat 3.0.0 and are defunct since 3.3.0: the technique they relied on isn’t allowed from R 4.5.0.

local_mocked_bindings() temporarily overrides a function binding within your package’s namespace for the duration of the calling scope:

test_that("days_since_baseline() computes correct duration", {
  # Temporarily mock the package-internal clock helper
  local_mocked_bindings(
    current_date = function() as.Date("2026-09-26")
  )

  # days_since_baseline() calls current_date() internally
  duration <- days_since_baseline(as.Date("2026-09-20"))
  expect_equal(duration, 6L)
})

The rule: you can only mock what your package can see

local_mocked_bindings() works by temporarily changing bindings in your package’s own namespace. Under R CMD check that namespace is locked, so it can replace a binding that exists but can’t create a new one. A base function such as Sys.Date() has no binding in your package, so there’s nothing to replace. The testthat docs give two ways round this:

  • add a NULL binding to your package (for example Sys.Date <- NULL in R/zzz.R), then mock Sys.Date; or
  • use the “wrap it” pattern, which also makes the code’s intent clearer:
  1. In your package code (R/utils.R), define a thin wrapper:

    today <- function() Sys.Date()
  2. In your package logic, call today() instead of Sys.Date().

  3. In your tests, mock today with local_mocked_bindings(today = function() ...):

# R/trial_status.R
study_day <- function(baseline_date) {
  as.integer(today() - as.Date(baseline_date)) + 1L
}

# tests/testthat/test-trial_status.R
test_that("study_day calculates Day 1 correctly", {
  local_mocked_bindings(today = function() as.Date("2026-01-15"))
  expect_equal(study_day("2026-01-15"), 1L)
})

(A real study-day derivation also handles dates before day 1, where there is no day 0; in ADaM code, admiral::derive_vars_dy() does this for you.)

This pattern isolates external boundaries (dates, random numbers, APIs) into explicit, testable ports.

4 · Test data design: minimal, realistic, clean

Unit tests do not need massive data frames. A common failure mode in data-heavy teams is a suite slowed down by massive tables that test nothing extra.

Follow three principles when designing test data:

  1. Minimal rows: Two to five rows are typically enough to test grouping, summarisation, and edge cases (e.g. one treated patient, one placebo patient, and one subject with missing baseline data).
  2. Subset existing open schemas: In clinical reporting, do not invent fictional column structures that diverge from CDISC standards. Subset standard open datasets from {pharmaverseadam} (such as adsl or advs) or {pharmaversesdtm} (such as dm or ex):
# tests/testthat/helper-clinical-fixtures.R

make_test_adsl <- function() {
  # Take the minimum columns and rows from a known open CDISC standard
  pharmaverseadam::adsl[1:3, c("USUBJID", "ARM", "AGE", "SEX", "SAFFL")]
}
  1. Never commit real patient data: Never store real, pseudonymised, or production patient data in a repository. Aside from severe regulatory and data protection violations (HIPAA, GDPR, ICH GCP), real clinical data is unnecessarily large and subject to drift. Synthetic, minimal data belongs in code.

5 · The GxP angle: determinism as evidence

In regulated environments, test results are part of the evidence that software does what it should. If a test suite passes on the build server on Tuesday but fails on Wednesday because of an un-mocked date or an un-reset environment variable, the audit trail loses credibility.

Isolated, deterministic tests mean that:

  • Verification evidence is reproducible across developer laptops and CI runners.
  • Results are independent of execution sequence: running test-alpha.R before test-beta.R yields the exact same outcome as running them in reverse.
  • Test runs leave no side effects behind on the machine.

The next post in this series covers snapshot tests, verifying complex data structures, printed tables, and graphical outputs without fragile manual assertions.

Pitfalls

  • Mocking internal business logic: Mock external dependencies (dates, file systems, web APIs), not your own calculations. If you mock every internal helper, you end up verifying your mock definitions rather than your package code.
  • Fixtures that drift from production schemas: When APIs or CDISC schemas evolve, outdated static fixtures will pass tests while your package breaks on real datasets. Keep fixtures minimal and align them with open reference standards.
  • Calling set.seed() or setwd() directly: Calling set.seed(123) or setwd(dir) without resetting leaves the R process altered for all subsequent tests. Always use withr::local_seed() and withr::local_dir().
  • Relying on alphabetical test file ordering: testthat executes test files alphabetically (test-a.R before test-b.R). Never rely on state established in an earlier file. Each file must be completely self-contained.
  • Putting heavy computation in setup.R: Code in setup.R runs unconditionally before the suite. Reserve it for lightweight session guards, and place specific data generation inside helper-*.R functions invoked only where required.

Companion code

View test-design-demo.R · Download

Builds a throwaway package whose tests use a helper fixture, withr::local_tempdir(), withr::local_options(), and testthat::local_mocked_bindings() to freeze dates, then runs the test suite. Requires {testthat}, {usethis}, and {withr}.

# Test design in practice: builds a throwaway package whose tests use a helper
# fixture, withr::local_tempdir() and local_options(), and
# testthat::local_mocked_bindings() to freeze "today", then runs the tests.
#
#   Rscript test-design-demo.R

demo_files <- list(
  # A thin wrapper around the clock, so tests can replace it.
  "R/today.R" = c(
    "today <- function() Sys.Date()"
  ),
  "R/days-since.R" = c(
    "#' Whole days from a date until today",
    "#' @export",
    "days_since <- function(date) {",
    "  as.integer(today() - as.Date(date))",
    "}"
  ),
  "R/report.R" = c(
    "#' Write a data frame to summary.csv in `dir`, returning the path",
    "#' @export",
    "write_summary <- function(data, dir) {",
    "  path <- file.path(dir, \"summary.csv\")",
    "  utils::write.csv(data, path, row.names = FALSE)",
    "  path",
    "}",
    "",
    "#' Mean to one decimal place, using the session's decimal separator",
    "#' @export",
    "format_mean <- function(x) {",
    "  format(round(mean(x), 1), nsmall = 1)",
    "}"
  ),
  # Helpers are sourced before the tests: fixtures live here.
  "tests/testthat/helper-fixtures.R" = c(
    "# The smallest data set the tests need.",
    "make_subjects <- function(n = 3) {",
    "  data.frame(",
    "    USUBJID = sprintf(\"01-701-%04d\", seq_len(n)),",
    "    AGE = seq(60, by = 10, length.out = n)",
    "  )",
    "}",
    "",
    "# A local_*() helper: a folder that is deleted when the calling test ends.",
    "local_output_dir <- function(env = parent.frame()) {",
    "  withr::local_tempdir(\"output-\", .local_envir = env)",
    "}"
  ),
  "tests/testthat/test-days-since.R" = c(
    "test_that(\"days_since() counts whole days up to today\", {",
    "  local_mocked_bindings(today = function() as.Date(\"2026-01-31\"))",
    "  expect_equal(days_since(\"2026-01-01\"), 30L)",
    "})"
  ),
  "tests/testthat/test-report.R" = c(
    "test_that(\"write_summary() writes one row per subject\", {",
    "  dir <- local_output_dir()",
    "  path <- write_summary(make_subjects(), dir)",
    "  expect_true(file.exists(path))",
    "  expect_equal(nrow(utils::read.csv(path)), 3)",
    "})",
    "",
    "test_that(\"format_mean() follows the decimal separator option\", {",
    "  withr::local_options(OutDec = \",\")",
    "  expect_equal(format_mean(c(1, 2)), \"1,5\")",
    "})",
    "",
    "test_that(\"local_options() restores the option afterwards\", {",
    "  with_comma <- function() {",
    "    withr::local_options(OutDec = \",\")",
    "    format_mean(c(1, 2))",
    "  }",
    "  expect_equal(with_comma(), \"1,5\")",
    "  expect_equal(format_mean(c(1, 2)), \"1.5\")",
    "})"
  )
)

# Creates the package and returns its path.
make_demo_package <- function(path = file.path(tempdir(), "trialclock")) {
  usethis::create_package(path, rstudio = FALSE, open = FALSE)
  usethis::with_project(path, {
    usethis::use_testthat(3)
    usethis::use_package("withr", type = "Suggests")
  })
  for (file in names(demo_files)) {
    writeLines(demo_files[[file]], file.path(path, file))
  }
  path
}

# Loads the package from source and runs its tests (like devtools::test()).
run_demo_tests <- function(path, reporter = testthat::default_reporter()) {
  testthat::test_local(path, reporter = reporter, stop_on_failure = FALSE)
}

# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
  path <- make_demo_package()
  results <- run_demo_tests(path)
  print(as.data.frame(results)[, c("file", "test", "nb", "failed")])
}

Sources

Package documentation

Web-repo comparison

  • Vitest (vi.useFakeTimers(), vi.setSystemTime()): vitest.dev
NoteUpdates
  • 2026-09-26: Removed the end-of-post checklist. Marked package-dependent testthat blocks as .norun.
  • 2026-09-27: Added a Sources section.
  • 2026-09-27: Added a Companion code section with the full script.