Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 354
usan Avatar asked May 06 '14 13:05

usan


People also ask

What is assert method in JUnit?

The assertSame() method tests if two object references point to the same object. The assertNotSame() method tests if two object references do not point to the same object. void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other.

What does @before mean in JUnit?

In JUnit 5, the tags @BeforeEach and @BeforeAll are the equivalents of @Before and @BeforeClass in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

What does assertSame () method use for assertion?

What does assertSame() method use for assertion? Explanation: == is used to compare the objects not the content. assertSame() method compares to check if actual and expected are the same objects.

How do you assert in unit testing?

Assert the exact desired behavior; avoid overly precise or overly loose conditions. One assertion, one condition. Don't aggregate multiple checks in one assertion. Write assertions that check requirements, not implementation details of the unit under test.


1 Answers

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.

like image 99
Brian Agnew Avatar answered Sep 28 '22 21:09

Brian Agnew