Home | History | Annotate | Download | only in text
      1 
      2 package org.hamcrest.text;
      3 
      4 import org.hamcrest.Description;
      5 import org.hamcrest.Matcher;
      6 import org.hamcrest.TypeSafeMatcher;
      7 
      8 import java.util.regex.Pattern;
      9 
     10 import static org.hamcrest.core.AnyOf.anyOf;
     11 import static org.hamcrest.core.IsNull.nullValue;
     12 
     13 /**
     14  * Matches blank Strings (and null).
     15  */
     16 public final class IsBlankString extends TypeSafeMatcher<String> {
     17     private static final IsBlankString BLANK_INSTANCE = new IsBlankString();
     18     @SuppressWarnings("unchecked")
     19     private static final Matcher<String> NULL_OR_BLANK_INSTANCE = anyOf(nullValue(), BLANK_INSTANCE);
     20 
     21     private static final Pattern REGEX_WHITESPACE = Pattern.compile("\\s*");
     22 
     23     private IsBlankString() { }
     24 
     25     @Override
     26     public boolean matchesSafely(String item) {
     27         return REGEX_WHITESPACE.matcher(item).matches();
     28     }
     29 
     30     @Override
     31     public void describeTo(Description description) {
     32         description.appendText("a blank string");
     33     }
     34 
     35     /**
     36      * Creates a matcher of {@link String} that matches when the examined string contains
     37      * zero or more whitespace characters and nothing else.
     38      * For example:
     39      * <pre>assertThat("  ", is(blankString()))</pre>
     40      */
     41     public static Matcher<String> blankString() {
     42         return BLANK_INSTANCE;
     43     }
     44 
     45     /**
     46      * Creates a matcher of {@link String} that matches when the examined string is <code>null</code>, or
     47      * contains zero or more whitespace characters and nothing else.
     48      * For example:
     49      * <pre>assertThat(((String)null), is(blankOrNullString()))</pre>
     50      *
     51      */
     52     public static Matcher<String> blankOrNullString() {
     53         return NULL_OR_BLANK_INSTANCE;
     54     }
     55 }
     56