Explain Codes LogoExplain Codes Logo

Why doesn't JUnit provide assertNotEquals methods?

java
assertions
junit
testing
Alex KataevbyAlex KataevยทOct 22, 2024
โšกTLDR

For JUnit 4, use assertThat with Hamcrest's not(equalTo(value)):

@Test public void testNotEquals() { // This will pass only if 'actual' has some other plans than being 'unexpected'. ๐Ÿ˜‰ assertThat(actual, not(equalTo(unexpected))); }

For JUnit 5, just use the cool kid of the block, assertNotEquals:

@Test public void testNotEquals() { // No room for 'actual' and 'unexpected' to be same. They aren't twins anyway! ๐Ÿ˜ assertNotEquals(unexpected, actual); }

Both of these methods validate that actual is not equal to unexpected.

Alternative ways to assert inequality

If you prefer to write tests in JUnit 4 or earlier, where assertNotEquals method is missing, or you're looking for alternative methods to assert inequality, consider these practical solutions:

  1. assertFalse method in JUnit 4: equals method can help us here:

    // Good old equals method, but this time, as Darth Vader on the Dark Side. assertFalse(actual.equals(unexpected));
  2. Customised assertTrue: Create a personalised assertion with a friendly fail message:

    // The laziest method to create your own assertNotEquals. assertTrue( "These values were supposed to fight, but they got along very well.", !actual.equals(unexpected));
  3. JUnit-addons for classic users: Provides an assertNotEqual method to handle inequality.

  4. DIY assertNotEqual method: Customize your own assertion for ultimate control over output messages:

    public static void assertNotEqual(Object actual, Object unexpected, String message) { // If actual and unexpected are super clingy, time to break 'em up. if(actual.equals(unexpected)) { throw new AssertionError(message); } }

Decoding the design of JUnit

Understanding JUnit's design choices can offer clarity about the limitations and flexibilities of the framework:

  • Less is More: JUnit maintains a minimalistic API to avoid cluttering with unnecessary methods.
  • Symmetry in Assertions: JUnit promotes composable and flexible assertions using assertThat.
  • User Driven Updates: JUnit enhances its features based on user feedback hence assertNotEquals made its debut in JUnit 4.11.

Assert negatively, but in style

Negation in testing isn't just about refuting equality. JUnit provides a wide range of tools for asserting the inverse of multiple conditions:

  • assertNotSame: Asserts that two objects don't point to the same memory location. Quite the memory-specific Sherlock, isn't it?

And then there's the wonder tool, assertThat:

  • It's capable of asserting interactions with collections and complex domains.

assertThat to the rescue

The enigmatic assertThat offers much more than just variety. It provides expressive language mechanics, flexibility in defining custom conditions, and improved readability.