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?
You are probably looking for StringUtils.countMatches
Counts the number of occurrences of one String in another
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With