Conceptintro
Test framework
Also called testing framework, test automation framework, unit testing framework.
A test framework does the work that is the same for every test: it finds the tests, makes a fixture for each one, checks results with assertions, runs the tests and reports the outcome.
- Applies to
- core-languages
Idea
Each automated test has some logic of its own: it calls the code and checks one result. Around that logic are many steps that are the same for every test. Something must find the tests, prepare the objects that each test needs, run the tests one after another, catch the failures and tell a person what went wrong. A test framework does these common steps, so the author of a test writes only the part that is specific to the test. Gerard Meszaros puts it this way: "We use a framework that provides all the mechanisms needed to run the test logic so the test writer only needs to provide the test-specific logic."1
A test framework has these parts:
- Discovery finds the tests, for example each function whose name starts with
test. - Fixtures prepare the objects and the state that a test needs, and clean them up after the test.
- Assertions check a result and stop the test with a clear message when the check is false.
- The runner runs each test, keeps the tests apart from each other and records the outcome of each one.
- The report tells a person which tests passed and which failed, and gives the build an exit status.
Most frameworks belong to one of two families. The xUnit family comes from JUnit: tests are methods or functions with names, and the framework calls a setup method before each one.2 The spec family writes tests as nested describe and it blocks, with names that read as sentences about behaviour.3
How it works
Meszaros lists what the framework does: "These mechanisms include the ability to find individual tests, assemble them into a test suite to run, execute each test in turn, verify expected outcomes have occurred, collect and report any test failures or test errors and to clean up when they do occur."1 The following program is a test framework in about 30 lines of Python. It is not for real use, but it has each of these parts.
class Failure(Exception):
"""An assertion that does not hold."""
def assert_equal(actual, expected):
if actual != expected:
raise Failure(f"expected {expected!r}, got {actual!r}")
# The fixture: the framework calls it again for each test.
def new_account():
return {"owner": "Ana", "balance": 100}
# The tests. The framework finds them by the prefix of their names.
def test_deposit(account):
account["balance"] += 50
assert_equal(account["balance"], 150)
def test_balance_starts_at_100(account):
assert_equal(account["balance"], 100)
def test_two_deposits(account):
account["balance"] += 20 + 30
assert_equal(account["balance"], 160)
def test_currency(account):
assert_equal(account["currency"], "EUR")
def run(namespace, fixture):
counts = {"passed": 0, "failed": 0, "errors": 0}
# Discovery: each function whose name starts with test_, in the order of the file.
for name in [n for n in namespace if n.startswith("test_")]:
try:
namespace[name](fixture())
except Failure as e:
counts["failed"] += 1
print(f"{name} ... FAIL: {e}")
except Exception as e:
counts["errors"] += 1
print(f"{name} ... ERROR: {type(e).__name__}: {e}")
else:
counts["passed"] += 1
print(f"{name} ... ok")
# The report: a count of each outcome, and an exit status for the caller.
print(", ".join(f"{k}: {v}" for k, v in counts.items()))
return 0 if counts["failed"] + counts["errors"] == 0 else 1
print("exit status:", run(dict(globals()), new_account))
test_deposit ... ok
test_balance_starts_at_100 ... ok
test_two_deposits ... FAIL: expected 160, got 150
test_currency ... ERROR: KeyError: 'currency'
passed: 2, failed: 1, errors: 1
exit status: 1
Each part of the program has a counterpart in a real framework:
- Discovery. The runner looks for names with the prefix
test_. Meszaros calls this Test Discovery: the framework "uses runtime reflection (or compile time knowledge) to discover all the Test Methods that belong to the test suite".4 pytest uses the same rule for functions: it collects "test prefixed test functions or methods outside of class".5 Newer frameworks often mark each test with an annotation such as@Testin Java, or an attribute such as[Test]in C#, in place of a rule for names.4 - A new fixture for each test.
test_depositadds 50 to the balance, buttest_balance_starts_at_100still sees 100, because the runner callsnew_accountagain for each test. A fixture that tests share lets one test change the result of the next one. - Failures and errors. The runner keeps two kinds of bad outcome apart. A failure is a check that is false. An error is any other exception, which often means that the test itself is wrong. Python's
unittestkeeps the same two lists: an error is "a test which raised an unexpected exception", and a failure is "a test where a failure was explicitly signalled using the assert* methods".6 - The report and the exit status. The person reads the lines. The build reads the exit status.
unittest.mainexits with "an exit code indicating success (0) or failure (1) of the tests run".6
A real runner adds more: it runs a subset of the tests by name, runs tests in parallel, captures the output of each test, and writes reports in formats that other tools read. Meszaros notes that the runner can get its tests by "Test Enumeration", "Test Discovery" or "Test Selection".7 Two common report formats are the Test Anything Protocol, a text stream of ok and not ok lines,8 and JUnit XML, which continuous integration services read.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Library | The C++ standard library has no test framework. Alternative: GoogleTest, Catch2 or doctest, often run through CTest. |
| Java | Library | |
| C | Idiom | The C standard library has only the assert macro; a test is a program that checks results and returns a nonzero status. Alternative: A test program with assert, or the libraries Unity, CMocka and Check. |
| C# | Library | The .NET base class library has no test framework; dotnet test runs the tests of a framework library. Alternative: XUnit.net, NUnit or MSTest, run by dotnet test. |
| JavaScript | Standard library | |
| TypeScript | Standard library | Node.js runs TypeScript test files with node:test when it strips the types; the TypeScript compiler itself has no test runner. Alternative: Node:test, or the libraries Vitest and Jest. |
| Go | Standard library | |
| Rust | Native | |
| Kotlin | Library | The Kotlin standard library has no test runner; kotlin.test is a separate library that runs on JUnit or TestNG. Alternative: Kotlin.test or JUnit Jupiter, or Kotest, run by Gradle. |
| SQL | Library | Standard SQL has no test framework. Alternative: PgTAP for PostgreSQL, tSQLt for SQL Server, or queries that compare results with expected rows. |
| Bash | Library | Bash has no test framework; a test is a script that checks exit statuses. Alternative: Bats-core, which reports in TAP, or a script with set -e and the test command. |
| PowerShell | Library | PowerShell has no test framework in the language or its core modules. Alternative: The Pester module, with Describe, It, BeforeEach and Should. |
| HTML | Does not apply | Markup has no units to call; it is tested through a browser. |
| CSS | Does not apply | Style rules have no units to call; they are tested through a browser. |
| Regular expressions | Does not apply | A pattern is tested through the language that uses it. |
The example files show the same tests in the main framework of each language: a new account for each test, a deposit, a table of withdrawals and a withdrawal that must fail. The table gives the verdict for each tier 1 language.
| Language | Verdict | Framework |
|---|---|---|
| Python | stdlib | unittest; pytest is a library |
| JavaScript | stdlib | node:test in Node.js; Jest, Vitest and Mocha are libraries |
| TypeScript | stdlib | node:test with type stripping; Jest and Vitest are libraries |
| Java | library | JUnit; TestNG |
| C | idiom | a test program with assert; Unity, CMocka and Check are libraries |
| C++ | library | GoogleTest; Catch2 and doctest |
| C# | library | xUnit.net, NUnit and MSTest, run by dotnet test |
| Go | stdlib | package testing and the command go test |
| Rust | native | the #[test] attribute, run by cargo test |
| Kotlin | library | kotlin.test on JUnit; Kotest |
| PowerShell | library | Pester |
| Bash | library | bats-core |
| SQL | library | pgTAP for PostgreSQL; tSQLt for SQL Server |
| Regex | n/a | a pattern is tested by the language that uses it |
| HTML/CSS | n/a | markup and style rules are tested through a browser |
The frameworks differ most in where they live. In Python, the standard library has unittest, which "was originally inspired by JUnit".6 In Node.js, "The node:test module facilitates the creation of JavaScript tests."9 Go puts the framework in the toolchain: "Package testing provides support for automated testing of Go packages", and the command go test runs the tests.10 Rust puts it in the compiler: "To change a function into a test function, add #[test] on the line before fn".11 In Java, C# and C++, the framework is a library. JUnit 6 has three parts: "JUnit 6.1.3 = JUnit Platform + JUnit Jupiter + JUnit Vintage".12 The platform is "a foundation for launching testing frameworks on the JVM", and Jupiter is the programming model for new tests, with an engine that runs them on the platform.12
The two families also show in the examples. JavaScript uses describe and it, the words of the spec family. Node.js gives both sets of names: "describe() is an alias for suite() , and it() is an alias for test()".9 The other examples use the xUnit style.
import unittest
class InsufficientFunds(Exception):
pass
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFunds(f"balance {self.balance}, asked {amount}")
self.balance -= amount
class AccountTest(unittest.TestCase):
def setUp(self):
# The fixture: unittest calls setUp before each test method.
self.account = Account(100)
def test_deposit_adds_to_balance(self):
self.account.deposit(50)
self.assertEqual(self.account.balance, 150)
def test_withdraw_leaves_the_rest(self):
for amount, rest in [(30, 70), (100, 0)]:
with self.subTest(amount=amount):
account = Account(100)
account.withdraw(amount)
self.assertEqual(account.balance, rest)
def test_withdraw_more_than_balance_fails(self):
with self.assertRaises(InsufficientFunds):
self.account.withdraw(150)
self.assertEqual(self.account.balance, 100)
if __name__ == "__main__":
unittest.main()
test_deposit_adds_to_balance (test_main.AccountTest.test_deposit_adds_to_balance) ... ok
test_withdraw_leaves_the_rest (test_main.AccountTest.test_withdraw_leaves_the_rest) ... ok
test_withdraw_more_than_balance_fails (test_main.AccountTest.test_withdraw_more_than_balance_fails) ... ok
----------------------------------------------------------------------
Ran 3 tests in $TIME
OK
- Verdict: stdlib.
unittestis in the standard library. It finds the methods whose names start withtestin each subclass ofunittest.TestCase, andunittest.main()runs them and exits with the status. setUpis the fixture.unittestmakes a new instance of the class for each test method and callssetUpfirst, sotest_withdraw_more_than_balance_failsgets an account with 100, whatever the other tests did.subTestreports each row of a table as its own case. When one row fails, the other rows still run, and the report shows the parameters of the failed row.setUpruns once for the method, not once for each row, so the loop makes its own account.- pytest also runs this file. It collects
unittest.TestCaseclasses, and adds plain test functions and fixtures that are function arguments.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class InsufficientFundsException extends RuntimeException {
InsufficientFundsException(String message) {
super(message);
}
}
final class Account {
private int balance;
Account(int balance) {
this.balance = balance;
}
int balance() {
return balance;
}
void deposit(int amount) {
balance += amount;
}
void withdraw(int amount) {
if (amount > balance) {
throw new InsufficientFundsException("balance " + balance + ", asked " + amount);
}
balance -= amount;
}
}
class AccountTest {
private Account account;
// The fixture: JUnit makes a new AccountTest and calls this method before each test.
@BeforeEach
void newAccount() {
account = new Account(100);
}
@Test
void depositAddsToBalance() {
account.deposit(50);
assertEquals(150, account.balance());
}
@ParameterizedTest
@CsvSource({"30, 70", "100, 0"})
void withdrawLeavesTheRest(int amount, int rest) {
account.withdraw(amount);
assertEquals(rest, account.balance());
}
@Test
void withdrawMoreThanBalanceFails() {
assertThrows(InsufficientFundsException.class, () -> account.withdraw(150));
assertEquals(100, account.balance());
}
}
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ AccountTest ✔
│ ├─ withdrawMoreThanBalanceFails() ✔
│ ├─ depositAddsToBalance() ✔
│ └─ withdrawLeavesTheRest(int, int) ✔
│ ├─ [1] 30, 70 ✔
│ └─ [2] 100, 0 ✔
└─ JUnit Vintage ✔
Test run finished after $TIME
[ 5 containers found ]
[ 0 containers skipped ]
[ 5 containers started ]
[ 0 containers aborted ]
[ 5 containers successful ]
[ 0 containers failed ]
[ 4 tests found ]
[ 0 tests skipped ]
[ 4 tests started ]
[ 0 tests aborted ]
[ 4 tests successful ]
[ 0 tests failed ]
- Verdict: library. The Java platform has no test framework. JUnit is the usual one; this page runs it with the JUnit console launcher. Maven and Gradle run the same tests in their test phase.
- JUnit finds tests by annotation, not by name.
@Testmarks a test, and@BeforeEachmarks the fixture method. - By default, JUnit Jupiter makes a new instance of the test class for each test method, so the field
accountis new in each test. @ParameterizedTestwith@CsvSourceruns the method once for each row. The report shows each row as its own test under the method.assertThrowsfails when the lambda does not throw an exception of the given class.
import { describe, it, beforeEach } from "node:test";
import assert from "node:assert/strict";
class InsufficientFunds extends Error {}
class Account {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
if (amount > this.balance) {
throw new InsufficientFunds(`balance ${this.balance}, asked ${amount}`);
}
this.balance -= amount;
}
}
describe("Account", () => {
let account;
// The fixture: the runner calls this hook before each test in the suite.
beforeEach(() => {
account = new Account(100);
});
it("adds a deposit to the balance", () => {
account.deposit(50);
assert.equal(account.balance, 150);
});
for (const [amount, rest] of [[30, 70], [100, 0]]) {
it(`leaves ${rest} after a withdrawal of ${amount}`, () => {
account.withdraw(amount);
assert.equal(account.balance, rest);
});
}
it("rejects a withdrawal larger than the balance", () => {
assert.throws(() => account.withdraw(150), InsufficientFunds);
assert.equal(account.balance, 100);
});
});
▶ Account
✔ adds a deposit to the balance ($TIME)
✔ leaves 70 after a withdrawal of 30 ($TIME)
✔ leaves 0 after a withdrawal of 100 ($TIME)
✔ rejects a withdrawal larger than the balance ($TIME)
✔ Account ($TIME)
ℹ tests 4
ℹ suites 1
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms $TIME
- Verdict: stdlib.
node:testandnode:assertare built into Node.js.node --testfinds the test files and runs them. - This file uses the spec style:
describemakes a suite anditmakes a test. They are aliases ofsuiteandtest, so the two styles give the same report. beforeEachis the fixture. It runs before each test of the suite, so each test gets a new account.- The table of withdrawals is a plain loop that registers one test for each row. The name of each test comes from a template string, so the report names the row.
- Jest, Vitest and Mocha use the same
describe,itandbeforeEachnames. Jest and Vitest also addit.eachfor tables.
package account
import "fmt"
// InsufficientFundsError is the error of a withdrawal larger than the balance.
type InsufficientFundsError struct {
Balance, Amount int
}
func (e *InsufficientFundsError) Error() string {
return fmt.Sprintf("balance %d, asked %d", e.Balance, e.Amount)
}
// Account holds a balance in whole units.
type Account struct {
Balance int
}
func (a *Account) Deposit(amount int) {
a.Balance += amount
}
func (a *Account) Withdraw(amount int) error {
if amount > a.Balance {
return &InsufficientFundsError{a.Balance, amount}
}
a.Balance -= amount
return nil
}
package account
import (
"errors"
"fmt"
"testing"
)
// newAccount is the fixture. Each test calls it to get its own account.
func newAccount() *Account {
return &Account{Balance: 100}
}
func TestDeposit(t *testing.T) {
a := newAccount()
a.Deposit(50)
if a.Balance != 150 {
t.Errorf("balance = %d, want 150", a.Balance)
}
}
func TestWithdraw(t *testing.T) {
tests := []struct{ amount, rest int }{
{30, 70},
{100, 0},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("withdraw %d", tt.amount), func(t *testing.T) {
a := newAccount()
if err := a.Withdraw(tt.amount); err != nil {
t.Fatalf("Withdraw(%d) returned error %v", tt.amount, err)
}
if a.Balance != tt.rest {
t.Errorf("balance = %d, want %d", a.Balance, tt.rest)
}
})
}
}
func TestWithdrawMoreThanBalance(t *testing.T) {
a := newAccount()
var e *InsufficientFundsError
if err := a.Withdraw(150); !errors.As(err, &e) {
t.Fatalf("Withdraw(150) returned %v, want an InsufficientFundsError", err)
}
if a.Balance != 100 {
t.Errorf("balance = %d, want 100", a.Balance)
}
}
=== RUN TestDeposit
--- PASS: TestDeposit ($TIME)
=== RUN TestWithdraw
=== RUN TestWithdraw/withdraw_30
=== RUN TestWithdraw/withdraw_100
--- PASS: TestWithdraw ($TIME)
--- PASS: TestWithdraw/withdraw_30 ($TIME)
--- PASS: TestWithdraw/withdraw_100 ($TIME)
=== RUN TestWithdrawMoreThanBalance
--- PASS: TestWithdrawMoreThanBalance ($TIME)
PASS
ok example $TIME
- Verdict: stdlib. The
testingpackage and thego testcommand come with Go.go testfinds the functionsTestXxx(t *testing.T)in the files whose names end in_test.go, builds a test binary and runs it. - Go has no fixture hook for each test. A test calls a helper function, such as
newAccount, to get a new value.TestMaincan do setup once for the whole package. t.Runmakes a subtest for each row of the table. The report gives each subtest its own name, andgo test -run 'TestWithdraw/withdraw_30'runs one row.- Go has no assertion functions in the standard library. A test compares values with
ifand callst.Errorfort.Fatalf.
#[derive(Debug, PartialEq)]
pub struct InsufficientFunds {
pub balance: i64,
pub asked: i64,
}
pub struct Account {
balance: i64,
}
impl Account {
pub fn new(balance: i64) -> Self {
Account { balance }
}
pub fn balance(&self) -> i64 {
self.balance
}
pub fn deposit(&mut self, amount: i64) {
self.balance += amount;
}
pub fn withdraw(&mut self, amount: i64) -> Result<(), InsufficientFunds> {
if amount > self.balance {
return Err(InsufficientFunds { balance: self.balance, asked: amount });
}
self.balance -= amount;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
// The fixture: each test calls this function to get its own account.
fn account() -> Account {
Account::new(100)
}
#[test]
fn deposit_adds_to_balance() {
let mut a = account();
a.deposit(50);
assert_eq!(a.balance(), 150);
}
#[test]
fn withdraw_leaves_the_rest() {
for (amount, rest) in [(30, 70), (100, 0)] {
let mut a = account();
a.withdraw(amount).unwrap();
assert_eq!(a.balance(), rest, "after a withdrawal of {amount}");
}
}
#[test]
fn withdraw_more_than_balance_fails() {
let mut a = account();
assert_eq!(a.withdraw(150), Err(InsufficientFunds { balance: 100, asked: 150 }));
assert_eq!(a.balance(), 100);
}
}
running 3 tests
test tests::deposit_adds_to_balance ... ok
test tests::withdraw_leaves_the_rest ... ok
test tests::withdraw_more_than_balance_fails ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME
- Verdict: native. The
#[test]attribute is part of the language. The compiler, with--test, builds a binary that runs each function that has the attribute.cargo testdoes this for each crate. - Rust has no fixture hook. A test calls a plain function, such as
account, to get a new value, and the value is dropped at the end of the test. - Rust has no built-in parameterized test. A loop over a table checks each row in one test, and the message of
assert_eq!names the row. The first row that fails stops the test. Crates such as rstest add parameterized tests and fixtures. - The harness runs the tests on several threads by default. A test fails when it panics, and the attribute
#[should_panic]marks a test that must panic.
Variations and related ideas
- The spec family. Dan North found that test names work best as sentences that start with the word should. At the end of 2003, North started to write "a replacement for JUnit called JBehave", with "a vocabulary built around verifying behaviour".3 RSpec for Ruby "began life in 2005 as an experiment by Steven Baker".13 Jasmine, Mocha and Jest use the same
describeanditstyle. See Test-driven development for the practice behind it. - Table-driven and parameterized tests. One test function takes a table of inputs and expected results, and the framework reports each row as its own case. JUnit has
@ParameterizedTest, pytest has@pytest.mark.parametrize, and Go tests loop over a table witht.Run. - Fixtures as arguments. pytest gives a test its fixtures through the names of its parameters, in place of a
setUpmethod. A fixture can also request other fixtures. See pytest. - Tests in documentation. Python's Python doctest runs the examples of an interactive session that are in a docstring, and checks that the output is the same.14
- Generated inputs. A Property-based testing library generates many inputs for one test and shrinks a failing input to a small one. It runs inside a normal test framework.
- Test doubles. A framework often comes with a library for Test double objects, such as
unittest.mockin Python or gMock with GoogleTest.
Pitfalls
A test that the framework does not find never runs, and the run is still green. Discovery goes by a rule, and a test that breaks the rule is not an error. In the following program, a method name starts with check and not with test. The function withdraw has a bug: it lets the balance go below zero. The test that would find the bug never runs.
This code runs but gives a wrong answer on purpose.
import io
import unittest
def withdraw(balance, amount):
# The bug: no check that the balance is large enough.
return balance - amount
class WithdrawTest(unittest.TestCase):
def test_withdraw_part(self):
self.assertEqual(withdraw(100, 30), 70)
# The name does not start with "test", so the loader does not see it.
def check_withdraw_too_much(self):
with self.assertRaises(ValueError):
withdraw(100, 150)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(WithdrawTest)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("successful:", "yes" if result.wasSuccessful() else "no")
tests run: 1
successful: yes
Read the count of tests in the report, not only the colour. When the name of the method starts with test, the run has 2 tests and fails, as it should:
import io
import unittest
def withdraw(balance, amount):
return balance - amount
class WithdrawTest(unittest.TestCase):
def test_withdraw_part(self):
self.assertEqual(withdraw(100, 30), 70)
def test_withdraw_too_much(self):
with self.assertRaises(ValueError):
withdraw(100, 150)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(WithdrawTest)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("successful:", "yes" if result.wasSuccessful() else "no")
tests run: 2
successful: no
The failure now shows the bug in withdraw, and the fix is to raise ValueError when the amount is larger than the balance. When no test at all is found, unittest reports it: "An exit code of 5 indicates that no tests were run or skipped."6 pytest uses exit code 5 for the same case: "No tests were collected".15
A test that catches every exception also catches its own failure. An assertion stops a test by raising an exception. A broad except in the test catches that exception, and the test passes.
This code runs but gives a wrong answer on purpose.
import io
import unittest
def withdraw(balance, amount):
# The same bug: no check that the balance is large enough.
return balance - amount
class WithdrawTest(unittest.TestCase):
def test_withdraw_too_much(self):
try:
withdraw(100, 150)
self.fail("withdraw gave no error")
except Exception:
pass # This also catches the AssertionError of self.fail.
suite = unittest.defaultTestLoader.loadTestsFromTestCase(WithdrawTest)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("successful:", "yes" if result.wasSuccessful() else "no")
tests run: 1
successful: yes
Use the assertion of the framework for an expected exception, and name the type of the exception: with self.assertRaises(ValueError): in unittest, pytest.raises in pytest, assertThrows in JUnit and assert.throws in Node.js. With that change, this test fails and shows the bug.
Tests that share state depend on their order. When two tests use the same object, the first test can change what the second one sees. The tests then pass in one order and fail in another. Make a new fixture for each test, as the frameworks do by default. Unit testing shows an example.
Cost
A framework costs little when it runs, but it does work before the first test starts. Discovery must load the code to find the tests: in unittest, "Test discovery loads tests by importing them."6 A large suite therefore pays to import each test module, even to run one test. A new fixture for each test also costs time when the fixture is large, such as a database. Frameworks let a fixture be shared by a class, a module or the whole run, and that brings back the risk of shared state.
The larger cost is in learning. Meszaros writes that the cost to learn a framework "can be reduced if the framework implements a common protocol such as xUnit which makes it easier for us to learn the second or third such framework once we have experience with the first."1
History
The idea started in Smalltalk. Martin Fowler writes that Kent Beck "would build a simple framework to organize and run unit tests" to help Beck and the clients of Beck test their code.2 There was no single framework at first: Beck liked each team to build its own, and "it only took a couple of hours".2
Fowler also tells how JUnit started: it "was born on a flight from Zurich to the 1997 OOPSLA in Atlanta", where Beck and Erich Gamma wrote the first version together.2 JUnit spread the idea, and other languages copied it. Fowler remembers "Michael Feathers putting together CppUnit for C++, which may have been the first port".2 The family took its name from JUnit: "XUnit is the family name given to bunch of testing frameworks".2 Python 2.1 added two test modules in 2001. One was PyUnit by Steve Purcell, "a unit testing framework inspired by JUnit", and the other was doctest by Tim Peters.14
The Test Anything Protocol "started life as part of the test harness for Perl".8 In the 2000s the spec family grew out of test-driven development: North began JBehave at the end of 2003,3 and RSpec started in 2005.13 Later languages put the framework in the toolchain from the start, as Go does with go test10 and Rust does with #[test].11
References
- Gerard Meszaros, Test Automation Framework, xunitpatterns.com, the problem and the solution statements; How It Works; Why We Do This
- Martin Fowler, Xunit, bliki, 17 January 2006, the whole entry
- Dan North, Introducing BDD, 20 September 2006, Test method names should be sentences; JBehave emphasizes behaviour over testing
- Gerard Meszaros, Test Discovery, xunitpatterns.com, How It Works; When To Use It; Testcase Class Discovery
- pytest documentation, Good Integration Practices, Conventions for Python test discovery
- The Python Standard Library, unittest, Unit testing framework, introduction (test fixture, test case, test suite, test runner); Basic example; TestResult, errors and failures; unittest.main
- Gerard Meszaros, Test Runner, xunitpatterns.com, the solution statement; How It Works
- Test Anything Protocol, home page, the introduction and the example stream
- Node.js documentation, Test runner (node:test), introduction; describe() and it() aliases; beforeEach
- Go standard library, package testing, package overview
- The Rust Programming Language, 11.1 How to Write Tests, Structuring Test Functions
- JUnit User Guide, Overview, What is JUnit?
- RSpec, About RSpec, History, History
- A.M. Kuchling, What's New in Python 2.1, Introduction; New and Improved Modules (doctest and PyUnit)
- pytest documentation, Exit codes, Exit code 5
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag P32KX6 Edit this page History Report an error Markdown