AssertContains on strings in jUnit

前端 未结 10 1526
清酒与你
清酒与你 2020-12-22 21:09

Is there a nicer way to write in jUnit

String x = \"foo bar\";
Assert.assertTrue(x.contains(\"foo\"));
相关标签:
10条回答
  • 2020-12-22 21:49

    I've tried out many answers on this page, none really worked:

    • org.hamcrest.CoreMatchers.containsString does not compile, cannot resolve method.
    • JUnitMatchers.containsString is depricated (and refers to CoreMatchers.containsString).
    • org.hamcrest.Matchers.containsString: NoSuchMethodError

    So instead of writing readable code, I decided to use the simple and workable approach mentioned in the question instead.

    Hopefully another solution will come up.

    0 讨论(0)
  • 2020-12-22 21:51

    Use hamcrest Matcher containsString()

    // Hamcrest assertion
    assertThat(person.getName(), containsString("myName"));
    
    // Error Message
    java.lang.AssertionError:
    Expected: a string containing "myName"
         got: "some other name"
    

    You can optional add an even more detail error message.

    // Hamcrest assertion with custom error message
    assertThat("my error message", person.getName(), containsString("myName"));
    
    // Error Message
    java.lang.AssertionError: my error message
    Expected: a string containing "myName"
         got: "some other name"
    

    Posted my answer to a duplicate question here

    0 讨论(0)
  • 2020-12-22 21:57

    Another variant is

    Assert.assertThat(actual, new Matches(expectedRegex));
    

    Moreover in org.mockito.internal.matchers there are some other interesting matchers, like StartWith, Contains etc.

    0 讨论(0)
  • 2020-12-22 21:57

    Example (junit version- 4.13)

    import static org.assertj.core.api.Assertions.assertThat;
    import org.junit.Test;
    
    public class TestStr {
    
    @Test
    public void testThatStringIsContained(){
        String testStr = "hi,i am a test string";
        assertThat(testStr).contains("test");
     }
    
    }
    
    0 讨论(0)
  • 2020-12-22 22:00

    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;
    
    0 讨论(0)
  • 2020-12-22 22:01

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

    assertThat(x).contains("foo");
    
    0 讨论(0)
提交回复
热议问题