Question

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.

Was it helpful?

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.

OTHER TIPS

Personally, I don't see any problem with it. If the desired is for all tests to fail is some precondition is not met, that meets the requirement. My only thought here is that you should be verifying preconditions not doing testing of the code under test. Otherwise it would seem to be misleading and I would suggest putting the condition in a method that is called from each test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top