AssertContains on strings in jUnit

前端 未结 10 1527
清酒与你
清酒与你 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 22:09

    It's too late, but just to update I got it done with below syntax

    import org.hamcrest.core.StringContains;
    import org.junit.Assert;
    
    Assert.assertThat("this contains test", StringContains.containsString("test"));
    
    0 讨论(0)
  • 2020-12-22 22:09

    You can use assertj-fluent assertions. It has lot of capabilities to write assertions in more human readable - user friendly manner.

    In your case, it would be

     String x = "foo bar";
     assertThat(x).contains("foo");
    

    It is not only for the strings, it can be used to assert lists, collections etc.. in a friendlier way

    0 讨论(0)
  • 2020-12-22 22:13

    Use the new assertThat syntax together with Hamcrest.

    It is available starting with JUnit 4.4.

    0 讨论(0)
  • 2020-12-22 22:15

    assertj variant

    import org.assertj.core.api.Assertions;
    Assertions.assertThat(actualStr).contains(subStr);
    
    0 讨论(0)
提交回复
热议问题