Is there a way to use anyNonEmptyString instead of anyString

Viewed 101

I am trying to mock a Java method with multiple arguments. One of the arguments is a String. The String can take on many values while my program is running, but it may not be null or blank (it must contain at least one non-whitespace character).

Using anyString() is insufficient here. What is a good way to mock a method like MyClass.bar() (shown below)?

public class MyClass {
    public Foo bar(String str, int myInt) {
        assert(!str.isBlank());
        return new Foo(str, myInt);
    }
}

Sorry, the example is contrived - only for illustration purposes.

1 Answers

Regex is your friend here. The '\s' character tests for whitespace while the '\S' command tests for non-whitespace. The Matcher command find will search all characters and return true if any match the regex. You will need the pattern and matcher classes, from Java.util.regex package.

Pattern p = Pattern.compile("\\S");
Matcher m = p.matcher(str);
m.find(); 
/*
Will return true if and only if the string str contains a non-whitespace character.
Otherwise, returns false.
*/

Note that a simple alternative is to remove all whitespace from the string and then check that the length is not 0. str.replaceAll("\\s+","").length() == 0 will return true if the string is only whitespace. The plus in the regex is optional, and it will run a bit faster without it, unless the string contains a lot of whitespace characters.

Related