16

I want to check whether a String contains a certain substring n times. I know I can do:

Assertions.assertThat(myString).contains("xyz");

Or even Assertions.assertThat(myString).containsOnlyOnce("xyz");

But how can I ensure this for n times?

I tried something like:

Assertions.assertThat(myString).areExactly(n, myString.contains("xyz")); but sadly this is not compilable.

Any ideas?

5 Answers5

15

You are probably looking for StringUtils.countMatches

Counts the number of occurrences of one String in another

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • And another library... *sighs* No aspectj/junit solution alone? –  Dec 15 '15 at 14:18
  • 4
    @Kayaman I think he was actually referring to `assertj` library (the library he used to test assertions), not `aspectj`. :-) And from this point of view (and looking at how many different assertions `assertj` already implements), it would be convinient to have `containsTimes(int n, String expected)` in addition to `containsOnlyOnce(String expected)`. – Ruslan Stelmachenko Feb 04 '18 at 21:56
5

You can have the regex like this which test String "myString" has SubString "xyz" n times.

Assertions.assertThat(myString).containsPattern("(xyz.*?){n}");

You can replace n with the count of substring you want to test.

Himank Batra
  • 301
  • 5
  • 3
0

The AssertJ way would be to use a Condition but it requires a little bit of work to implement it so I would use StringUtils.countMatches as Rahul Tripathi suggested.

Joel Costigliola
  • 6,308
  • 27
  • 35
0

Hamcrest has matchers for regex. You could do

assertThat(actual, matchesPattern("(mystring.*?){2}))

Which will test that mystring is shown up exactly twice

http://hamcrest.org/JavaHamcrest/javadoc/2.0.0.0/org/hamcrest/text/MatchesPattern.html

and yes, another library, but for assertions this should be the only one you need. :-)

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
-1

You could do something like:

        String testString = "XXwwYYwwLOK";
        int count = 0;
        while (testString.contains("ww")) {
            count++;
            int index = testString.indexOf("ww");
            if(index + 1 == testString.length()){
                break;
            }
            testString = testString.substring(index + 1);
        }

I didn't test this code but it should work.

Richard Loth
  • 79
  • 1
  • 7
  • Good for you for contributing, but in this case this doesn't answer the question as the OP is asking about doing this within a unit test, ideally with a matcher. Besides that, it's best not to post code you didn't run. – Samuel Neff Sep 11 '19 at 16:35