Quickstart
unittest2 is a Nim module for writing automated tests.
It is mostly compatible with Nim's built-in unittest, while adding better output, flexible reporting, and advanced execution features like test discovery.
Installation
$ nimble install -y unittest2
Add unittest2 to your .nimble file:
requires "unittest2"
First Test File
unittest2 follows this test structure:
- Module. A .nim file that has an
import unittest2in it, usually sits intestsdirectory of your project, and is named starting with atby convention, e.g.tmath.nim. A module holds the tests that cover a particular topic or a module in your project. - Suite. Defined with
suiteblock, it's a group of related tests. In hetmath.nimexample, you could have a suite like "Overflow checks" and "Basic arithmetic." - Test case. A single atomic check under a
testblock. Intmath.nimsuite "Basic arithmetic," you could have tests like "Addition"and "Subtraction."
Aside from test, you can use setup and teardown blocks inside suite.
setup block defines the code that runs before each test.
teardown block defines the code that runs after each test.
Create test.nim:
import unittest2
# A suite groups related tests and can share common setup/teardown code.
suite "math":
setup:
# Code inside setup runs before every single test in this suite.
discard
test "2 + 2 == 4":
# 'check' verifies that a condition is true.
# If it fails, the test is marked as FAILED and the values are printed.
check:
1 + 1 == 2
test "out of bounds raises":
let xs = @[1, 2, 3]
# 'expect' verifies that the code block raises a specific exception.
# It is useful for testing error conditions.
expect IndexDefect:
discard xs[4]
Compile and run:
nim c -r test.nim
This exits with 0 on success and 1 when any test fails.
See command options:
# Running the compiled binary directly
./test --help
Compilation Flags
unittest2 behavior can be customized using compilation flags (-d:flag).
A detailed list of all available flags, including execution modes and advanced features, can be found on the Compilation Flags page.
Compile-Time Testing
One of unittest2 standout features is the ability to run tests during compilation. Use staticTest, runtimeTest, or dualTest for explicit control over when your tests execute.
You can also opt into compile-time execution globally for all test blocks:
nim c -d:unittest2Static=true test.nim
Contributing and Testing This Repository
Run tests locally:
# this calls a task in "config.nims"
nim test
Build the documentation locally:
# Build both the book and apidocs
nim docs
# Build only the book
nim book
# Build only the apidocs
nim apidocs
Navigate the generated docs:
Tip: start from the API index, then jump to symbols in unittest2.nim for implementation details.