javajunittddassertj

How to ensure a string has a substring exactly n times?


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?


Solution

  • You are probably looking for StringUtils.countMatches

    Counts the number of occurrences of one String in another