@Fixture to enhance fixtures in JUnit tests

fixtureIn this post I’d like to briefly present extended approach to provide fixtures into JUnit tests. JUnit already provides a possibility to execute methods right before/after test method and before/after test class. This standard functionality does not fulfill more sophisticated requirements. Thanks to @Beofre/@After annotations, for each test there is always executed exactly the same method. In a case in which we’d like to have a dedicated fixture code for each method the existing approach is not so convenient. I’ve developed fixture handling addition to JUnit framework with a possibility to define different fixture for each test.


Let’s start with a fixture definition coming from Wikipedia [1]:

“In software testing, a test fixture is a fixed state of the software under test used as a baseline for running tests; also known as the test context. It may also refer to the actions performed in order to bring the system into such a state.”

In testing there are generally two kinds of fixture:

  1. Before test fixture
  2. After test fixture

The purpose of the developed fixture feature is to provide a simple way to define before/after test’s fixtures and associate them with a certain test method. A fixture has a name and composes two methods – executed before and after test accordingly.


Because the feature is a subject of further development the more detailed overview is provided in the Fixtures [2] article. I encourage to read the article and leave constructing comments in order to support me in development a better solution. For now, there is presented a simple fixtures usage to give a picture of the idea. The core part of the feature if the @Fixture annotation.

public class FixtureSimpleTest {

	FixtureSuite createFixtureSuite() {
		RegistrantsFixtureSuite fixtureSuite = new RegistrantsFixtureSuite();
		fixtureSuite.registerFixture("simpleFixture", this::executeBeforeTest, this::executeAfterTest);
		return fixtureSuite;

	public FixtureRule fixtureRule = new FixtureRule(createFixtureSuite());

	@Fixture(value = "simpleFixture")
	public void testOfCertainService() {
		// do the actual test

	void executeBeforeTest(FixtureExecutionContext context) {
		// before-test's fixture code goes here

	void executeAfterTest(FixtureExecutionContext context) {
		// after-test's fixture code goes here

Example usage of @Fixture


[1] http://en.wikipedia.org/wiki/Test_fixture

[2] Fixtures

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>