Explain Codes LogoExplain Codes Logo

Warning: The method assertEquals from the type Assert is deprecated

java
assertions
testing
null-safety
Alex KataevbyAlex Kataev·Aug 6, 2024
TLDR

Migrate to JUnit 5's Assertions.assertEquals from org.junit.jupiter.api for observing equivalent values:

Assertions.assertEquals(expected, actual); // Easy as pie, right?

For JUnit 4, stick with org.junit.Assert:

Assert.assertEquals(expected, actual); // Oldie but goodie

Comparing floats/doubles? Toss in a third (delta) in the mix:

Assert.assertEquals(expected, actual, delta); // It's all Greek to me

Running a string comparison? Consider throwing in null checks or utilize StringUtils:

assertEquals("Expected and actual strings don't match", expected, actual); // No more hide and seek

Switching gears: From deprecated to updated methods

Learning to let go of deprecated methods

Farewell to our cherished assertEquals. Its deprecation warning is an invitation to stay current and incorporate efficient testing mechanisms.

Accounting for precision in float/double comparisons

Counting on delta for floating-point comparisons is crucial. Think of it as your lifeline when swimming in the sea of decimals.

Null safety with Strings

Handle strings with care. Including null checks or using libraries like Apache Commons Lang for null-safe comparisons can save a lot of heartaches later on.

Mastery level: Expanding assert tools

Expressiveness with Assert assertThat

Unleash the power of expressiveness and readability with Assert.assertThat, which has matchers with self-explanatory semantics.

Exploring third-party lib assertion wonders

When ‘aid is made from unlikely allies,’ broaden your horizons with third-party libraries, like Truth and AssertJ, for fluent, expressive assertions and cryptic test scenarios.

Guarding precision with delta

For veterans of junit.framework.Assert, remember to declare delta while comparing floats and doubles in assertEquals. It's an old habit that still holds weight.