Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertContains on strings in jUnit

Is there a nicer way to write in jUnit

String x = "foo bar"; Assert.assertTrue(x.contains("foo")); 
like image 207
ripper234 Avatar asked Jul 07 '09 13:07

ripper234


People also ask

Can you use assertEquals for strings?

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) .

What is assertTrue and assertFalse in JUnit?

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.

What is assertSame in JUnit?

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.


2 Answers

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; 
like image 98
Yishai Avatar answered Sep 19 '22 12:09

Yishai


use fest assert 2.0 whenever possible EDIT: assertj may have more assertions (a fork)

assertThat(x).contains("foo"); 
like image 40
piotrek Avatar answered Sep 19 '22 12:09

piotrek