Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Best Practice: Different Fixtures for each @Test

Tags:

junit

fixtures

I understand that there are @Before and @BeforeClass, which are used to define fixtures for the @Test's. But what should I use if I need different fixtures for each @Test?

  • Should I define the fixture in the @Test?
  • Should I create a test class for each @Test?

I am asking for the best practices here, since both solutions aren't clean in my opinion. With the first solution, I would test the initialization code. And with the second solution I would break the "one test class for each class" pattern.

like image 861
Juri Glass Avatar asked May 03 '10 15:05

Juri Glass


People also ask

How do we run setup () and tearDown () methods once for all the tests in the class for JUnit framework?

As outlined in Recipe 4.6, JUnit calls setUp( ) before each test, and tearDown( ) after each test. In some cases you might want to call a special setup method once before a series of tests, and then call a teardown method once after all tests are complete.

What is the benefit of test fixtures in JUnit?

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. Test suites: Bundles a few unit test cases and runs them together.

What are the examples of fixtures in JUnit?

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.


1 Answers

Tips:

  1. Forget the one test class per class pattern, it has little merit. Switch to one test class per usage perspective. In one perspective you might have multiple cases: upper boundary, lower boundary, etc. Create different @Tests for those in the same class.
  2. Remember that JUnit will create an instance of the test class for each @Test, so each test will get a distinct fixture (set up by the same @Before methods). If you need a dissimilar fixture you need a different test class, because you are in a different perspective (see 1.)
  3. There is nothing wrong with tweaking the fixture for a particular test, but you should try to keep the test clean so it tells a story. This story should be particularly clear when the test fails, hence the different, well named @Test for each case (see 1.)
like image 148
iwein Avatar answered Sep 30 '22 19:09

iwein