Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Concurrency and Tooling

Testing in Zig

Write and run tests in Zig with test blocks, std.testing expect functions, testing.allocator leak detection, error tests, table-driven tests, filters and zig build test.

Testing is built into the Zig language. A test block is a declaration like a function, the compiler knows about it, and zig test runs all of them. There is no external framework to install and no separate file naming rules: tests usually sit right below the code they check.

Your first test

ZIG
const std = @import("std");

fn add(a: i32, b: i32) i32 {
    return a + b;
}

test "add works" {
    try std.testing.expect(add(2, 3) == 5);
}

test "add handles negatives" {
    try std.testing.expectEqual(@as(i32, -1), add(2, -3));
}

Run it:

TEXT
zig test src/math.zig

or through a project's build.zig with zig build test. A test passes if the block finishes without returning an error. That is why every assertion is a try: the expect* functions return an error when the check fails, and try ends the test with it. Failed tests print what was expected and what was found, plus a stack trace.

Test blocks are compiled only in test mode, and they cost nothing in your real build. The name is a string (or an identifier); descriptive sentences read best in the output.

The std.testing functions

Function Checks
expect(cond) cond is true
expectEqual(expected, actual) two values are equal (expected first!)
expectEqualStrings(a, b) two strings are equal, with a readable diff
expectEqualSlices(T, a, b) two slices are equal element by element
expectError(error.X, expr) expr returned exactly that error
expectApproxEqAbs(a, b, tol) floats are within a tolerance
expectEqualDeep(a, b) structs/unions are equal deeply

Put the expected value first: the failure message labels them, so the order matters for clarity.

Compare floats with a tolerance, never ==:

ZIG
try std.testing.expectApproxEqAbs(0.3, 0.1 + 0.2, 1e-9);

Integer literals have type comptime_int, so expectEqual(5, add(2, 3)) can fail to compile with a type mismatch. Give the expected value a type with @as(i32, 5), or compare with expect(... == ...).

Testing errors

Functions that return errors are tested with expectError:

ZIG
fn parseDigit(c: u8) !u8 {
    if (c < '0' or c > '9') return error.NotADigit;
    return c - '0';
}

test "parseDigit" {
    try std.testing.expectEqual(@as(u8, 7), try parseDigit('7'));
    try std.testing.expectError(error.NotADigit, parseDigit('x'));
}

Note try parseDigit('7') inside the first check: if the call itself fails unexpectedly, the test fails with that error, which is the behavior you want.

std.testing.allocator: leak detection

std.testing.allocator is a leak-checking allocator. When the test ends, it verifies that every allocation was freed; if not, the test fails and prints the allocation's stack trace. This makes tests the cheapest place to catch memory bugs.

ZIG
test "builds a greeting without leaking" {
    const gpa = std.testing.allocator;
    const msg = try std.fmt.allocPrint(gpa, "Hello, {s}!", .{"Zig"});
    defer gpa.free(msg); // delete this line and the test fails
    try std.testing.expectEqualStrings("Hello, Zig!", msg);
}

Use it everywhere a function takes an allocator (see Allocators in Zig). It also checks the cleanup of failure paths. The next idea tests exactly that.

Testing out-of-memory paths

std.testing.FailingAllocator fails after N allocations. Run a function repeatedly with a growing N to prove that every error path cleans up (the errdefers from errdefer and error sets):

ZIG
test "no leaks when allocation fails" {
    var fail_index: usize = 0;
    while (fail_index < 10) : (fail_index += 1) {
        var failing = std.testing.FailingAllocator.init(
            std.testing.allocator,
            .{ .fail_index = fail_index },
        );
        const result = buildThing(failing.allocator());
        if (result) |thing| {
            thing.deinit(failing.allocator());
        } else |err| {
            try std.testing.expectEqual(error.OutOfMemory, err);
        }
    }
}

If any path leaks, the leak-checking base allocator fails the test. Libraries such as the standard library's own containers use a helper called checkAllAllocationFailures that automates this loop.

Table-driven tests

Zig has no parameterized-test syntax, but loops over comptime or runtime tables work well:

ZIG
test "digits" {
    const cases = [_]struct { input: u8, want: ?u8 }{
        .{ .input = '0', .want = 0 },
        .{ .input = '9', .want = 9 },
        .{ .input = 'a', .want = null },
    };
    for (cases) |c| {
        const got = parseDigit(c.input) catch null;
        try std.testing.expectEqual(c.want, got);
    }
}

catch null turns an error into "no value", so one comparison covers both success and failure.

Organizing and running tests

  • Where tests live. Next to the code they test, in the same file. Tests in a file run when that file is part of a test build.
  • Pulling in other files. A test build only analyzes files that are referenced. Add a test that uses std.testing.refAllDecls(@This()) in a root file, or _ = @import("other.zig"); in a test block, so tests in other files are included.
  • Filtering. zig test src/main.zig --test-filter "parseDigit" runs only tests whose name contains that text.
  • Release modes. zig test -O ReleaseSafe ... tests the optimized build, which catches bugs that only appear after optimization. Run both.
  • Skipping. return error.SkipZigTest; marks a test as skipped, for example when a platform lacks a feature.
  • Output. std.debug.print in a test goes to stderr, visible while debugging. Test output for passing tests is summarized.

Testing code that reads input or prints

Make such functions take a writer or a reader instead of using stdout directly, so a test can pass an in-memory buffer and check what was produced. Passing dependencies in (allocators, writers, clocks, random generators) is Zig's general approach to testability; there are no mocks and no global state to patch.

Doc tests and comptime tests

A comptime assertion fails the build, not a test run:

ZIG
comptime {
    std.debug.assert(@sizeOf(Header) == 16);
}

Use these for layout facts that must never change.

A runnable stand-in

Go's testing package is separate from go run, so as a stand-in we write a tiny "expect" helper that returns errors, in the same shape as Zig's try expect.... Each test returns an error and a runner reports it.

Go Stand-in: tests that return errors (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Forgetting try before expect...: the compiler complains that an error union is ignored.
  • Swapping expected and actual, which makes failure messages misleading.
  • Comparing floats with expectEqual.
  • Testing with page_allocator and so never finding leaks; use std.testing.allocator.
  • Writing a test in a file that is never imported, so it never runs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a Zig test block pass?

    Tests are error-returning blocks; any failed try (such as a failed expect) ends the test with an error.
  2. 2. What does std.testing.allocator do at the end of a test?

    It is a leak-checking allocator, so forgotten frees become test failures with stack traces.
  3. 3. How do you check that a function returns error.NotADigit?

    expectError calls for an exact error from an error-union expression.
  4. 4. How do you run only tests whose names contain 'parse'?

    --test-filter restricts the run to matching test names.

Summary

  • test "name" { ... } blocks live next to the code; zig test file.zig or zig build test runs them.
  • std.testing.expect* return errors, so use try; expected value first.
  • std.testing.allocator detects leaks; FailingAllocator tests out-of-memory paths.
  • Pass dependencies (allocators, writers) in so code is testable; use filters and -O ReleaseSafe runs too.

Next: Cross-compiling and tooling