Use assert statement in @Before method of JUnit test?

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

If the statement fails, all tests fail, so it behaves exactly the way I want, but I'm not sure if this is a good idea, since the @Before -annotated method is not a test.

+6
source share
2 answers

Assume seems to be more appropriate.

A set of methods useful for formulating assumptions about the conditions in which the test makes sense. An unsuccessful assumption does not mean that the code does not work, but the test does not contain any useful information. By default, the JUnit runner considers tests with errors that are ignored. Custom runners can behave differently.

Perhaps this seems more intuitive as you check the precondition of the test before actually executing each test. Pay attention to the link above for custom runners that perform differently, and you can change the runner to fail, and not silently ignore the test.

+6
source

Personally, I do not see any problems with this. If the desired for all tests is not fulfilled, some preconditions are not fulfilled, which meets the requirement. My only thought here is that you should check the preconditions without checking the code under test. Otherwise, this would seem to be misleading, and I would suggest setting a condition in the method that is called from each test.

+3
source

All Articles