Test fixtures

Pat Hawks edited this page Jun 17, 2017 · 9 revisions

A test fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. Examples of fixtures:

  • Preparation of input data and setup/creation of fake or mock objects
  • Loading a database with a specific, known set of data
  • Copying a specific known set of files creating a test fixture will create a set of objects initialized to certain states.

JUnit provides annotations so that test classes can have fixture run before or after every test, or one time fixtures that run before and after only once for all test methods in a class.

There are four fixture annotations: two for class-level fixtures and two for method-level ones. At the class level, you have @BeforeClass and @AfterClass, and at the method (or test) level, you have @Before and @After.

A deeper explanation of fixtures, and how they could also be implemented using Rules is discussed here.

An example of usage:

package test;

import java.io.Closeable;
import java.io.IOException;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestFixturesExample {
  static class ExpensiveManagedResource implements Closeable {
    public void close() throws IOException {}

  static class ManagedResource implements Closeable {
    public void close() throws IOException {}

  public static void setUpClass() {
    System.out.println("@BeforeClass setUpClass");
    myExpensiveManagedResource = new ExpensiveManagedResource();

  public static void tearDownClass() throws IOException {
    System.out.println("@AfterClass tearDownClass");
    myExpensiveManagedResource = null;

  private ManagedResource myManagedResource;
  private static ExpensiveManagedResource myExpensiveManagedResource;

  private void println(String string) {

  public void setUp() {
    this.println("@Before setUp");
    this.myManagedResource = new ManagedResource();

  public void tearDown() throws IOException {
    this.println("@After tearDown");
    this.myManagedResource = null;

  public void test1() {
    this.println("@Test test1()");

  public void test2() {
    this.println("@Test test2()");

Will Output something like the following:

@BeforeClass setUpClass
@Before setUp
@Test test2()
@After tearDown
@Before setUp
@Test test1()
@After tearDown
@AfterClass tearDownClass
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.