Is there a nicer way to write in jUnit
String x = "foo bar"; Assert.assertTrue(x.contains("foo"));
You should always use . equals() when comparing Strings in Java. JUnit calls the . equals() method to determine equality in the method assertEquals(Object o1, Object o2) .
In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.
The assertSame() method tests if two object references point to the same object. 7. void assertNotSame(object1, object2) The assertNotSame() method tests if two object references do not point to the same object.
If you add in Hamcrest and JUnit4, you could do:
String x = "foo bar"; Assert.assertThat(x, CoreMatchers.containsString("foo"));
With some static imports, it looks a lot better:
assertThat(x, containsString("foo"));
The static imports needed would be:
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.containsString;
use fest assert 2.0 whenever possible EDIT: assertj may have more assertions (a fork)
assertThat(x).contains("foo");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With