Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want a JUnitMatchers AssertThat to test string contains 3 or more sub strings (currently using assertThat ... both ... and ....)

import static org.junit.matchers.JUnitMatchers.both;
import static org.junit.matchers.JUnitMatchers.containsString;

Now I check it contains foo and bar as below ...

        Assert.assertThat(text,
            both(containsString("foo")).
            and(containsString("bar")));

What is cleanest way to test also check it contains 3 or more strings e.g. 'foo', 'bar' and 'baz' ?

like image 588
k1eran Avatar asked Jul 01 '13 11:07

k1eran


People also ask

What does assertThat do in JUnit?

The assertThat is one of the JUnit methods from the Assert object that can be used to check if a specific value match to an expected one. It primarily accepts 2 parameters. First one if the actual value and the second is a matcher object.

How do you check if something contains assert?

StringUtils. containsIgnoreCase("Runaway train", "train")); Assert. assertTrue(StringUtils. containsIgnoreCase("Runaway train", "Train")); We can see that it will check if a substring is contained in a String, ignoring the case.

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


2 Answers

I don't know a elegant way in pure JUnit but you could take a look at Fixtures for Easy Software Testing

I'm using it for quite some time and it makes like so much easier.

assertThat(text).contains("foo").contains("bar");
like image 43
ssindelar Avatar answered Oct 19 '22 14:10

ssindelar


Use AllOf

 Assert.assertThat(test, CoreMatchers.allOf(
      containsString("foo"),
      containsString("bar"),
      containsString("bar2"),
      containsString("ba3")));
like image 111
John B Avatar answered Oct 19 '22 16:10

John B