Search code examples
javaunit-testingjunitannotations

Use an assert statement in the @Before method of a JUnit test?


Should I use assert statements (assertEquals,...) in the @Before method of a JUnit test?

If the assertion fails, all tests will fail, so it behaves exactly how I want, but I'm not convinced this is a good idea as the @Before-annotated method is not a test.


Solution

  • It sounds like the Assume mechanism would be more appropriate.

    A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information. The default JUnit runner treats tests with failing assumptions as ignored. Custom runners may behave differently.

    That perhaps seems more intuitive, since you're testing a test precondition before actually executing each test. Note the reference above to custom runners performing differently, and you could amend a runner to fail rather than silently ignore the test.