Explain Codes LogoExplain Codes Logo

Assertcontains on strings in jUnit

java
assertions
testing
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 29, 2025
TLDR

Here's the quick and dirty version, using assertTrue and String's contains:

import static org.junit.Assert.assertTrue; assertTrue("Expected substring not found. Bet you didn't 'see' this coming!", "full string".contains("substring"));

This test will pass if "full string" contains "substring", or else it will sparkle with that witty comeback!

Hamcrest Matchers: The Alchemists of JUnit

On the shores of JUnit lies a secret order known as Hamcrest. They craft matchers that transform ordinary tests into extraordinary assertions.

import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; assertThat("full string", containsString("substring"));

With static imports, you keep the code neat and prevent your screen from turning into a jumbled mess.

AssertJ Magic: Fluent Assertions at Your Fingertips

Want a more stunningly fluent approach? AssertJ is a wizard's best friend:

import static org.assertj.core.api.Assertions.assertThat; assertThat("full string").contains("substring");

AssertJ spells are known for their readability and intuitive syntax, producing clean and fluent assertions.

Custom Error Messages: A Lighthouse in Debugging Storm

When a test fails, you feel like a sailor lost in a tempest. Custom error messages are your lighthouse:

import static org.junit.Assert.assertTrue; assertTrue("Expected substring 'substring' not found in 'full string'. This is not the 'substring' you're looking for!", "full string".contains("substring"));

This customized message will guide you safely back to the shore of debugging.

Exploring Other Libraries: The Curious Code Explorer

Like in every expedition, there are other intriguing libraries to navigate such as fest-assert-2.x and assertj offering enriched testing remedies:

// With Fest Assert: import static org.fest.assertions.Assertions.assertThat; assertThat("full string").contains("substring"); // "substring" found, extra golden coins to the bag! // With AssertJ for collections: import static org.assertj.core.api.Assertions.assertThat; assertThat(listOfStrings).contains("expected string"); // "expected string" - well, that was unexpected!

With these libraries, your tests will be as powerful as a galleon's armada.

Best Practices: The Compass of Maintainability

What's a sea voyage without a compass? Here are some best practices guiding you to maintainable tests:

  • Keep variable names meaningful. Let "myStr" walk the plank!
  • One definitive assertion per test. Clutter-free is the way to be!
  • Implement parameterized tests when similar assertions surface. Two birds, one stone!

By sticking to these best practices, your tests will be a reliable logbook for your application's journey.