From c2a42aa25bda80c9c2af8ba3238f90a23632a404 Mon Sep 17 00:00:00 2001 From: JJ Brown Date: Sun, 19 Apr 2020 21:49:03 -0500 Subject: [PATCH] Enforced indentation style of 2 spaces (with further details matching Google's CheckStyle specs). Formatted existing .java code to match. See #295 --- checkstyle.xml | 13 + .../deprecated/HamcrestCoreIsDeprecated.java | 3 +- .../java/org/hamcrest/EasyMock2Matchers.java | 13 +- .../java/org/hamcrest/JMock1Matchers.java | 10 +- .../org/hamcrest/JavaLangMatcherAssert.java | 16 +- .../integration/EasyMock2Adapter.java | 53 +- .../hamcrest/integration/JMock1Adapter.java | 49 +- .../HamcrestLibraryIsDeprecated.java | 3 +- .../java/org/hamcrest/BaseDescription.java | 283 ++++---- .../main/java/org/hamcrest/BaseMatcher.java | 67 +- .../src/main/java/org/hamcrest/Condition.java | 113 ++-- .../main/java/org/hamcrest/CoreMatchers.java | 164 +++-- .../main/java/org/hamcrest/CustomMatcher.java | 31 +- .../org/hamcrest/CustomTypeSafeMatcher.java | 29 +- .../main/java/org/hamcrest/Description.java | 133 ++-- .../java/org/hamcrest/DiagnosingMatcher.java | 25 +- .../java/org/hamcrest/FeatureMatcher.java | 47 +- .../src/main/java/org/hamcrest/Matcher.java | 80 +-- .../main/java/org/hamcrest/MatcherAssert.java | 52 +- .../src/main/java/org/hamcrest/Matchers.java | 633 +++++++++++------- .../java/org/hamcrest/SelfDescribing.java | 21 +- .../java/org/hamcrest/StringDescription.java | 107 +-- .../hamcrest/TypeSafeDiagnosingMatcher.java | 114 ++-- .../java/org/hamcrest/TypeSafeMatcher.java | 151 +++-- .../java/org/hamcrest/beans/HasProperty.java | 73 +- .../hamcrest/beans/HasPropertyWithValue.java | 259 +++---- .../java/org/hamcrest/beans/PropertyUtil.java | 74 +- .../hamcrest/beans/SamePropertyValuesAs.java | 279 ++++---- .../collection/ArrayAsIterableMatcher.java | 24 +- .../hamcrest/collection/ArrayMatching.java | 48 +- .../hamcrest/collection/HasItemInArray.java | 51 +- .../java/org/hamcrest/collection/IsArray.java | 169 ++--- .../IsArrayContainingInAnyOrder.java | 182 ++--- .../collection/IsArrayContainingInOrder.java | 148 ++-- .../hamcrest/collection/IsArrayWithSize.java | 89 +-- .../collection/IsCollectionWithSize.java | 77 ++- .../collection/IsEmptyCollection.java | 87 +-- .../hamcrest/collection/IsEmptyIterable.java | 74 +- .../java/org/hamcrest/collection/IsIn.java | 230 +++---- .../IsIterableContainingInAnyOrder.java | 267 ++++---- .../IsIterableContainingInOrder.java | 268 ++++---- .../IsIterableContainingInRelativeOrder.java | 210 +++--- .../collection/IsIterableWithSize.java | 90 +-- .../hamcrest/collection/IsMapContaining.java | 225 ++++--- .../hamcrest/collection/IsMapWithSize.java | 99 +-- .../comparator/ComparatorMatcherBuilder.java | 336 +++++----- .../main/java/org/hamcrest/core/AllOf.java | 89 +-- .../main/java/org/hamcrest/core/AnyOf.java | 85 +-- .../org/hamcrest/core/CombinableMatcher.java | 60 +- .../java/org/hamcrest/core/DescribedAs.java | 110 +-- .../main/java/org/hamcrest/core/Every.java | 71 +- .../src/main/java/org/hamcrest/core/Is.java | 111 +-- .../java/org/hamcrest/core/IsAnything.java | 83 ++- .../hamcrest/core/IsCollectionContaining.java | 168 ++--- .../main/java/org/hamcrest/core/IsEqual.java | 154 +++-- .../java/org/hamcrest/core/IsInstanceOf.java | 172 +++-- .../hamcrest/core/IsIterableContaining.java | 230 ++++--- .../main/java/org/hamcrest/core/IsNot.java | 94 +-- .../main/java/org/hamcrest/core/IsNull.java | 116 ++-- .../main/java/org/hamcrest/core/IsSame.java | 86 +-- .../hamcrest/core/ShortcutCombination.java | 52 +- .../org/hamcrest/core/StringContains.java | 76 ++- .../org/hamcrest/core/StringEndsWith.java | 72 +- .../core/StringRegularExpression.java | 22 +- .../org/hamcrest/core/StringStartsWith.java | 74 +- .../org/hamcrest/core/SubstringMatcher.java | 86 ++- .../org/hamcrest/internal/ArrayIterator.java | 52 +- .../org/hamcrest/internal/NullSafety.java | 19 +- .../internal/ReflectiveTypeFinder.java | 66 +- .../internal/SelfDescribingValue.java | 23 +- .../internal/SelfDescribingValueIterator.java | 43 +- .../java/org/hamcrest/io/FileMatchers.java | 224 ++++--- .../hamcrest/number/BigDecimalCloseTo.java | 51 +- .../java/org/hamcrest/number/IsCloseTo.java | 105 +-- .../main/java/org/hamcrest/number/IsNaN.java | 61 +- .../hamcrest/number/OrderingComparison.java | 146 ++-- .../org/hamcrest/object/HasEqualValues.java | 130 ++-- .../java/org/hamcrest/object/HasToString.java | 71 +- .../org/hamcrest/object/IsCompatibleType.java | 74 +- .../java/org/hamcrest/object/IsEventFrom.java | 119 ++-- .../org/hamcrest/text/CharSequenceLength.java | 94 +-- .../java/org/hamcrest/text/IsBlankString.java | 84 +-- .../java/org/hamcrest/text/IsEmptyString.java | 118 ++-- .../text/IsEqualCompressingWhiteSpace.java | 115 ++-- .../hamcrest/text/IsEqualIgnoringCase.java | 85 +-- .../org/hamcrest/text/MatchesPattern.java | 70 +- .../hamcrest/text/StringContainsInOrder.java | 123 ++-- .../main/java/org/hamcrest/xml/HasXPath.java | 305 +++++---- .../org/hamcrest/AbstractMatcherTest.java | 85 ++- .../org/hamcrest/BaseDescriptionTest.java | 226 ++++--- .../java/org/hamcrest/BaseMatcherTest.java | 37 +- .../java/org/hamcrest/CustomMatcherTest.java | 26 +- .../hamcrest/CustomTypeSafeMatcherTest.java | 70 +- .../java/org/hamcrest/FeatureMatcherTest.java | 111 +-- .../java/org/hamcrest/MatcherAssertTest.java | 54 +- .../org/hamcrest/NullDescriptionTest.java | 16 +- .../TypeSafeDiagnosingMatcherTest.java | 134 ++-- .../org/hamcrest/TypeSafeMatcherTest.java | 29 +- .../org/hamcrest/beans/HasPropertyTest.java | 70 +- .../beans/HasPropertyWithValueTest.java | 155 +++-- .../beans/SamePropertyValuesAsTest.java | 116 ++-- .../ArrayMatchingInAnyOrderTest.java | 74 +- .../collection/ArrayMatchingInOrderTest.java | 79 ++- .../collection/HasItemInArrayTest.java | 122 ++-- .../IsArrayContainingInAnyOrderTest.java | 74 +- .../IsArrayContainingInOrderTest.java | 70 +- .../org/hamcrest/collection/IsArrayTest.java | 113 ++-- .../collection/IsArrayWithSizeTest.java | 58 +- .../collection/IsCollectionWithSizeTest.java | 116 ++-- .../collection/IsEmptyCollectionTest.java | 74 +- .../collection/IsEmptyIterableTest.java | 74 +- .../org/hamcrest/collection/IsInTest.java | 73 +- .../IsIterableContainingInAnyOrderTest.java | 42 +- .../IsIterableContainingInOrderTest.java | 142 ++-- ...IterableContainingInRelativeOrderTest.java | 190 +++--- .../collection/IsIterableWithSizeTest.java | 21 +- .../collection/IsMapContainingKeyTest.java | 77 ++- .../collection/IsMapContainingTest.java | 76 ++- .../collection/IsMapContainingValueTest.java | 72 +- .../collection/IsMapWithSizeTest.java | 130 ++-- .../ComparatorMatcherBuilderTest.java | 237 ++++--- .../comparator/ComparatorMatcherTest.java | 158 +++-- .../java/org/hamcrest/core/AllOfTest.java | 108 +-- .../java/org/hamcrest/core/AnyOfTest.java | 105 +-- .../org/hamcrest/core/CombinableTest.java | 107 +-- .../org/hamcrest/core/DescribedAsTest.java | 82 +-- .../java/org/hamcrest/core/EveryTest.java | 66 +- .../org/hamcrest/core/IsAnythingTest.java | 68 +- .../core/IsCollectionContainingTest.java | 175 ++--- .../java/org/hamcrest/core/IsEqualTest.java | 311 +++++---- .../org/hamcrest/core/IsInstanceOfTest.java | 103 +-- .../core/IsIterableContainingTest.java | 191 +++--- .../java/org/hamcrest/core/IsNotTest.java | 67 +- .../java/org/hamcrest/core/IsNullTest.java | 69 +- .../java/org/hamcrest/core/IsSameTest.java | 80 ++- .../test/java/org/hamcrest/core/IsTest.java | 86 +-- .../org/hamcrest/core/SampleBaseClass.java | 39 +- .../org/hamcrest/core/SampleSubClass.java | 12 +- .../org/hamcrest/core/StringContainsTest.java | 70 +- .../org/hamcrest/core/StringEndsWithTest.java | 72 +- .../org/hamcrest/core/StringMatchingTest.java | 12 +- .../core/StringRegularExpressionTest.java | 11 +- .../hamcrest/core/StringStartsWithTest.java | 74 +- .../org/hamcrest/io/FileMatchersTest.java | 168 ++--- .../number/BigDecimalCloseToTest.java | 19 +- .../org/hamcrest/number/IsCloseToTest.java | 44 +- .../java/org/hamcrest/number/IsNanTest.java | 75 ++- .../number/OrderingComparisonTest.java | 145 ++-- .../hamcrest/object/HasEqualsValuesTest.java | 86 +-- .../org/hamcrest/object/HasToStringTest.java | 96 +-- .../hamcrest/object/IsCompatibleTypeTest.java | 79 ++- .../org/hamcrest/object/IsEventFromTest.java | 84 +-- .../hamcrest/object/MatchesPatternTest.java | 103 +-- .../hamcrest/text/CharSequenceLengthTest.java | 52 +- .../org/hamcrest/text/IsBlankStringTest.java | 98 +-- .../org/hamcrest/text/IsEmptyStringTest.java | 98 +-- .../IsEqualCompressingWhiteSpaceTest.java | 80 ++- .../text/IsEqualIgnoringCaseTest.java | 114 ++-- .../text/StringContainsInOrderTest.java | 50 +- .../java/org/hamcrest/xml/HasXPathTest.java | 247 +++---- 160 files changed, 9169 insertions(+), 7336 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index c1dbabf3..76b6a163 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -8,4 +8,17 @@ + + + + + + + + + + + + + diff --git a/hamcrest-core/src/main/java/org/hamcrest/core/deprecated/HamcrestCoreIsDeprecated.java b/hamcrest-core/src/main/java/org/hamcrest/core/deprecated/HamcrestCoreIsDeprecated.java index 19482c3d..0f87931a 100644 --- a/hamcrest-core/src/main/java/org/hamcrest/core/deprecated/HamcrestCoreIsDeprecated.java +++ b/hamcrest-core/src/main/java/org/hamcrest/core/deprecated/HamcrestCoreIsDeprecated.java @@ -5,5 +5,6 @@ * hamcrest.jar. Please use that dependency instead. */ @Deprecated -class HamcrestCoreIsDeprecated { +class HamcrestCoreIsDeprecated +{ } diff --git a/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java b/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java index 936aa7d5..9e3dc1cb 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java @@ -4,14 +4,15 @@ import org.hamcrest.core.IsEqual; /** - * * @author Joe Walnes */ -public class EasyMock2Matchers { +public class EasyMock2Matchers +{ - public static String equalTo(String string) { - EasyMock2Adapter.adapt(IsEqual.equalTo(string)); - return null; - } + public static String equalTo(String string) + { + EasyMock2Adapter.adapt(IsEqual.equalTo(string)); + return null; + } } diff --git a/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java b/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java index 6aac6f87..47c79fed 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java @@ -4,9 +4,11 @@ import org.hamcrest.core.IsEqual; import org.jmock.core.Constraint; -public class JMock1Matchers { +public class JMock1Matchers +{ - public static Constraint equalTo(String string) { - return JMock1Adapter.adapt(IsEqual.equalTo(string)); - } + public static Constraint equalTo(String string) + { + return JMock1Adapter.adapt(IsEqual.equalTo(string)); + } } diff --git a/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java b/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java index 6cc97e81..68bb113c 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java @@ -9,10 +9,16 @@ * * @author Neil Dunn */ -public class JavaLangMatcherAssert { - private JavaLangMatcherAssert() {}; +public class JavaLangMatcherAssert +{ + private JavaLangMatcherAssert() + { + } - public static boolean that(T argument, Matcher matcher) { - return matcher.matches(argument); - } + ; + + public static boolean that(T argument, Matcher matcher) + { + return matcher.matches(argument); + } } diff --git a/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java b/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java index 09ab0f7d..cc694a89 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java @@ -11,33 +11,38 @@ * * @author Joe Walnes */ -public class EasyMock2Adapter implements IArgumentMatcher { +public class EasyMock2Adapter implements IArgumentMatcher +{ - /** - * Convenience factory method that will adapt a - * Hamcrest {@link org.hamcrest.Matcher} to act as an - * EasyMock {@link org.easymock.IArgumentMatcher} and - * report it to EasyMock so it can be kept track of. - */ - public static IArgumentMatcher adapt(Matcher matcher) { - EasyMock2Adapter easyMock2Matcher = new EasyMock2Adapter(matcher); - EasyMock.reportMatcher(easyMock2Matcher); - return easyMock2Matcher; - } + /** + * Convenience factory method that will adapt a + * Hamcrest {@link org.hamcrest.Matcher} to act as an + * EasyMock {@link org.easymock.IArgumentMatcher} and + * report it to EasyMock so it can be kept track of. + */ + public static IArgumentMatcher adapt(Matcher matcher) + { + EasyMock2Adapter easyMock2Matcher = new EasyMock2Adapter(matcher); + EasyMock.reportMatcher(easyMock2Matcher); + return easyMock2Matcher; + } - private final Matcher hamcrestMatcher; + private final Matcher hamcrestMatcher; - public EasyMock2Adapter(Matcher matcher) { - this.hamcrestMatcher = matcher; - } + public EasyMock2Adapter(Matcher matcher) + { + this.hamcrestMatcher = matcher; + } - @Override - public boolean matches(Object argument) { - return hamcrestMatcher.matches(argument); - } + @Override + public boolean matches(Object argument) + { + return hamcrestMatcher.matches(argument); + } - @Override - public void appendTo(StringBuffer buffer) { - hamcrestMatcher.describeTo(new StringDescription(buffer)); - } + @Override + public void appendTo(StringBuffer buffer) + { + hamcrestMatcher.describeTo(new StringDescription(buffer)); + } } diff --git a/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java b/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java index fa2021ce..b8398c0f 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java @@ -12,31 +12,36 @@ * * @author Joe Walnes */ -public class JMock1Adapter implements Constraint { +public class JMock1Adapter implements Constraint +{ - /** - * Convenience factory method that will adapt a - * Hamcrest {@link org.hamcrest.Matcher} to act as an - * jMock {@link org.jmock.core.Constraint}. - */ - public static Constraint adapt(Matcher matcher) { - return new JMock1Adapter(matcher); - } + /** + * Convenience factory method that will adapt a + * Hamcrest {@link org.hamcrest.Matcher} to act as an + * jMock {@link org.jmock.core.Constraint}. + */ + public static Constraint adapt(Matcher matcher) + { + return new JMock1Adapter(matcher); + } - private final Matcher hamcrestMatcher; + private final Matcher hamcrestMatcher; - public JMock1Adapter(Matcher matcher) { - this.hamcrestMatcher = matcher; - } + public JMock1Adapter(Matcher matcher) + { + this.hamcrestMatcher = matcher; + } - @Override - public boolean eval(Object o) { - return hamcrestMatcher.matches(o); - } + @Override + public boolean eval(Object o) + { + return hamcrestMatcher.matches(o); + } - @Override - public StringBuffer describeTo(StringBuffer buffer) { - hamcrestMatcher.describeTo(new StringDescription(buffer)); - return buffer; - } + @Override + public StringBuffer describeTo(StringBuffer buffer) + { + hamcrestMatcher.describeTo(new StringDescription(buffer)); + return buffer; + } } diff --git a/hamcrest-library/src/main/java/org/hamcrest/library/deprecated/HamcrestLibraryIsDeprecated.java b/hamcrest-library/src/main/java/org/hamcrest/library/deprecated/HamcrestLibraryIsDeprecated.java index b7ec20c3..acce98ca 100644 --- a/hamcrest-library/src/main/java/org/hamcrest/library/deprecated/HamcrestLibraryIsDeprecated.java +++ b/hamcrest-library/src/main/java/org/hamcrest/library/deprecated/HamcrestLibraryIsDeprecated.java @@ -5,5 +5,6 @@ * hamcrest.jar. Please use that dependency instead. */ @Deprecated -class HamcrestLibraryIsDeprecated { +class HamcrestLibraryIsDeprecated +{ } diff --git a/hamcrest/src/main/java/org/hamcrest/BaseDescription.java b/hamcrest/src/main/java/org/hamcrest/BaseDescription.java index d0c8fc41..b2a09073 100644 --- a/hamcrest/src/main/java/org/hamcrest/BaseDescription.java +++ b/hamcrest/src/main/java/org/hamcrest/BaseDescription.java @@ -11,142 +11,181 @@ /** * A {@link Description} that is stored as a string. */ -public abstract class BaseDescription implements Description { +public abstract class BaseDescription implements Description +{ - @Override - public Description appendText(String text) { - append(text); - return this; + @Override + public Description appendText(String text) + { + append(text); + return this; + } + + @Override + public Description appendDescriptionOf(SelfDescribing value) + { + value.describeTo(this); + return this; + } + + @Override + public Description appendValue(Object value) + { + if (value == null) + { + append("null"); } - - @Override - public Description appendDescriptionOf(SelfDescribing value) { - value.describeTo(this); - return this; + else if (value instanceof String) + { + toJavaSyntax((String) value); } - - @Override - public Description appendValue(Object value) { - if (value == null) { - append("null"); - } else if (value instanceof String) { - toJavaSyntax((String) value); - } else if (value instanceof Character) { - append('"'); - toJavaSyntax((Character) value); - append('"'); - } else if (value instanceof Byte) { - append('<'); - append(descriptionOf(value)); - append("b>"); - } else if (value instanceof Short) { - append('<'); - append(descriptionOf(value)); - append("s>"); - } else if (value instanceof Long) { - append('<'); - append(descriptionOf(value)); - append("L>"); - } else if (value instanceof Float) { - append('<'); - append(descriptionOf(value)); - append("F>"); - } else if (value.getClass().isArray()) { - appendValueList("[",", ","]", new ArrayIterator(value)); - } else { - append('<'); - append(descriptionOf(value)); - append('>'); - } - return this; + else if (value instanceof Character) + { + append('"'); + toJavaSyntax((Character) value); + append('"'); } - - private String descriptionOf(Object value) { - try { - return valueOf(value); - } - catch (Exception e) { - return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); - } + else if (value instanceof Byte) + { + append('<'); + append(descriptionOf(value)); + append("b>"); } - - @SafeVarargs - @Override - public final Description appendValueList(String start, String separator, String end, T... values) { - return appendValueList(start, separator, end, Arrays.asList(values)); + else if (value instanceof Short) + { + append('<'); + append(descriptionOf(value)); + append("s>"); } - - @Override - public Description appendValueList(String start, String separator, String end, Iterable values) { - return appendValueList(start, separator, end, values.iterator()); + else if (value instanceof Long) + { + append('<'); + append(descriptionOf(value)); + append("L>"); } - - private Description appendValueList(String start, String separator, String end, Iterator values) { - return appendList(start, separator, end, new SelfDescribingValueIterator<>(values)); + else if (value instanceof Float) + { + append('<'); + append(descriptionOf(value)); + append("F>"); + } + else if (value.getClass().isArray()) + { + appendValueList("[", ", ", "]", new ArrayIterator(value)); + } + else + { + append('<'); + append(descriptionOf(value)); + append('>'); + } + return this; + } + + private String descriptionOf(Object value) + { + try + { + return valueOf(value); } - - @Override - public Description appendList(String start, String separator, String end, Iterable values) { - return appendList(start, separator, end, values.iterator()); + catch (Exception e) + { + return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); } + } - private Description appendList(String start, String separator, String end, Iterator i) { - boolean separate = false; - - append(start); - while (i.hasNext()) { - if (separate) append(separator); - appendDescriptionOf(i.next()); - separate = true; - } - append(end); - - return this; + @SafeVarargs + @Override + public final Description appendValueList(String start, String separator, String end, T... values) + { + return appendValueList(start, separator, end, Arrays.asList(values)); + } + + @Override + public Description appendValueList(String start, String separator, String end, Iterable values) + { + return appendValueList(start, separator, end, values.iterator()); + } + + private Description appendValueList(String start, String separator, String end, Iterator values) + { + return appendList(start, separator, end, new SelfDescribingValueIterator<>(values)); + } + + @Override + public Description appendList(String start, String separator, String end, Iterable values) + { + return appendList(start, separator, end, values.iterator()); + } + + private Description appendList(String start, String separator, String end, Iterator i) + { + boolean separate = false; + + append(start); + while (i.hasNext()) + { + if (separate) + { + append(separator); + } + appendDescriptionOf(i.next()); + separate = true; } + append(end); + + return this; + } - /** - * Append the String str to the description. - * The default implementation passes every character to {@link #append(char)}. - * Override in subclasses to provide an efficient implementation. - */ - protected void append(String str) { - for (int i = 0; i < str.length(); i++) { - append(str.charAt(i)); - } + /** + * Append the String str to the description. + * The default implementation passes every character to {@link #append(char)}. + * Override in subclasses to provide an efficient implementation. + */ + protected void append(String str) + { + for (int i = 0; i < str.length(); i++) + { + append(str.charAt(i)); } - - /** - * Append the char c to the description. - */ - protected abstract void append(char c); - - private void toJavaSyntax(String unformatted) { - append('"'); - for (int i = 0; i < unformatted.length(); i++) { - toJavaSyntax(unformatted.charAt(i)); - } - append('"'); + } + + /** + * Append the char c to the description. + */ + protected abstract void append(char c); + + private void toJavaSyntax(String unformatted) + { + append('"'); + for (int i = 0; i < unformatted.length(); i++) + { + toJavaSyntax(unformatted.charAt(i)); } + append('"'); + } - private void toJavaSyntax(char ch) { - switch (ch) { - case '"': - append("\\\""); - break; - case '\n': - append("\\n"); - break; - case '\r': - append("\\r"); - break; - case '\t': - append("\\t"); - break; - case '\\': - append("\\\\"); - break; - default: - append(ch); - } + private void toJavaSyntax(char ch) + { + switch (ch) + { + case '"': + append("\\\""); + break; + case '\n': + append("\\n"); + break; + case '\r': + append("\\r"); + break; + case '\t': + append("\\t"); + break; + case '\\': + append("\\\\"); + break; + default: + append(ch); } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java b/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java index aaa6e957..d4c10b99 100644 --- a/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java @@ -5,38 +5,47 @@ * * @see Matcher */ -public abstract class BaseMatcher implements Matcher { +public abstract class BaseMatcher implements Matcher +{ - /** - * @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_() - */ - @Override - @Deprecated - public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() { - // See Matcher interface for an explanation of this method. - } + /** + * @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_() + */ + @Override + @Deprecated + public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() + { + // See Matcher interface for an explanation of this method. + } - @Override - public void describeMismatch(Object item, Description description) { - description.appendText("was ").appendValue(item); - } + @Override + public void describeMismatch(Object item, Description description) + { + description.appendText("was ").appendValue(item); + } - @Override - public String toString() { - return StringDescription.toString(this); - } + @Override + public String toString() + { + return StringDescription.toString(this); + } - /** - * Useful null-check method. Writes a mismatch description if the actual object is null - * @param actual the object to check - * @param mismatch where to write the mismatch description, if any - * @return false iff the actual object is null - */ - protected static boolean isNotNull(Object actual, Description mismatch) { - if (actual == null) { - mismatch.appendText("was null"); - return false; - } - return true; + /** + * Useful null-check method. Writes a mismatch description if the actual object is null + * + * @param actual + * the object to check + * @param mismatch + * where to write the mismatch description, if any + * @return false iff the actual object is null + */ + protected static boolean isNotNull(Object actual, Description mismatch) + { + if (actual == null) + { + mismatch.appendText("was null"); + return false; } + return true; + } } diff --git a/hamcrest/src/main/java/org/hamcrest/Condition.java b/hamcrest/src/main/java/org/hamcrest/Condition.java index 02ce09e6..d1cdaba2 100644 --- a/hamcrest/src/main/java/org/hamcrest/Condition.java +++ b/hamcrest/src/main/java/org/hamcrest/Condition.java @@ -5,65 +5,90 @@ * that have a sequence of steps, where each step depends on the result of the previous * step and we can stop processing as soon as a step fails. These classes provide * infrastructure for writing such a sequence. - * + *

* Based on https://github.com/npryce/maybe-java + * * @author Steve Freeman 2012 http://www.hamcrest.com */ -public abstract class Condition { - public static final NotMatched NOT_MATCHED = new NotMatched(); +public abstract class Condition +{ + public static final NotMatched NOT_MATCHED = new NotMatched(); - public interface Step { - Condition apply(I value, Description mismatch); - } + public interface Step + { + Condition apply(I value, Description mismatch); + } + + private Condition() + { + } + + public abstract boolean matching(Matcher match, String message); - private Condition() { } + public abstract Condition and(Step mapping); - public abstract boolean matching(Matcher match, String message); - public abstract Condition and(Step mapping); + public final boolean matching(Matcher match) + { + return matching(match, ""); + } - public final boolean matching(Matcher match) { return matching(match, ""); } - public final Condition then(Step mapping) { return and(mapping); } + public final Condition then(Step mapping) + { + return and(mapping); + } - @SuppressWarnings("unchecked") - public static Condition notMatched() { - return (Condition) NOT_MATCHED; + @SuppressWarnings("unchecked") + public static Condition notMatched() + { + return (Condition) NOT_MATCHED; + } + + public static Condition matched(final T theValue, final Description mismatch) + { + return new Matched(theValue, mismatch); + } + + private static final class Matched extends Condition + { + private final T theValue; + private final Description mismatch; + + private Matched(T theValue, Description mismatch) + { + this.theValue = theValue; + this.mismatch = mismatch; } - public static Condition matched(final T theValue, final Description mismatch) { - return new Matched(theValue, mismatch); + @Override + public boolean matching(Matcher matcher, String message) + { + if (matcher.matches(theValue)) + { + return true; + } + mismatch.appendText(message); + matcher.describeMismatch(theValue, mismatch); + return false; } - private static final class Matched extends Condition { - private final T theValue; - private final Description mismatch; - - private Matched(T theValue, Description mismatch) { - this.theValue = theValue; - this.mismatch = mismatch; - } - - @Override - public boolean matching(Matcher matcher, String message) { - if (matcher.matches(theValue)) { - return true; - } - mismatch.appendText(message); - matcher.describeMismatch(theValue, mismatch); - return false; - } - - @Override - public Condition and(Step next) { - return next.apply(theValue, mismatch); - } + @Override + public Condition and(Step next) + { + return next.apply(theValue, mismatch); } + } - private static final class NotMatched extends Condition { - @Override public boolean matching(Matcher match, String message) { return false; } + private static final class NotMatched extends Condition + { + @Override public boolean matching(Matcher match, String message) + { + return false; + } - @Override public Condition and(Step mapping) { - return notMatched(); - } + @Override public Condition and(Step mapping) + { + return notMatched(); } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java b/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java index 02b5e426..755cf457 100644 --- a/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java +++ b/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java @@ -3,14 +3,16 @@ import org.hamcrest.core.IsIterableContaining; @SuppressWarnings("UnusedDeclaration") -public class CoreMatchers { +public class CoreMatchers +{ /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(java.lang.Iterable> matchers) { + public static org.hamcrest.Matcher allOf(java.lang.Iterable> matchers) + { return org.hamcrest.core.AllOf.allOf(matchers); } @@ -20,7 +22,8 @@ public static org.hamcrest.Matcher allOf(java.lang.IterableassertThat("myValue", allOf(startsWith("my"), containsString("Val"))) */ @SafeVarargs - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher... matchers) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher... matchers) + { return org.hamcrest.core.AllOf.allOf(matchers); } @@ -30,7 +33,8 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher. * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ - public static org.hamcrest.core.AnyOf anyOf(java.lang.Iterable> matchers) { + public static org.hamcrest.core.AnyOf anyOf(java.lang.Iterable> matchers) + { return org.hamcrest.core.AnyOf.anyOf(matchers); } @@ -40,7 +44,8 @@ public static org.hamcrest.core.AnyOf anyOf(java.lang.IterableassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ @SafeVarargs - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher... matchers) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher... matchers) + { return org.hamcrest.core.AnyOf.anyOf(matchers); } @@ -49,7 +54,8 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("fab", both(containsString("a")).and(containsString("b"))) */ - public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcher both(org.hamcrest.Matcher matcher) { + public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcher both(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.CombinableMatcher.both(matcher); } @@ -58,7 +64,8 @@ public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcherassertThat("fan", either(containsString("a")).or(containsString("b"))) */ - public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher either(org.hamcrest.Matcher matcher) { + public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher either(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.CombinableMatcher.either(matcher); } @@ -67,7 +74,7 @@ public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher< * delegated to the decorated matcher, including its mismatch description. * For example: *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
- * + * * @param description * the new description for the wrapped matcher * @param matcher @@ -75,7 +82,8 @@ public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher< * @param values * optional values to insert into the tokenised description */ - public static org.hamcrest.Matcher describedAs(java.lang.String description, org.hamcrest.Matcher matcher, java.lang.Object... values) { + public static org.hamcrest.Matcher describedAs(java.lang.String description, org.hamcrest.Matcher matcher, java.lang.Object... values) + { return org.hamcrest.core.DescribedAs.describedAs(description, matcher, values); } @@ -85,11 +93,12 @@ public static org.hamcrest.Matcher describedAs(java.lang.String descripti * itemMatcher. * For example: *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
- * + * * @param itemMatcher * the matcher to apply to every item provided by the examined {@link Iterable} */ - public static org.hamcrest.Matcher> everyItem(org.hamcrest.Matcher itemMatcher) { + public static org.hamcrest.Matcher> everyItem(org.hamcrest.Matcher itemMatcher) + { return org.hamcrest.core.Every.everyItem(itemMatcher); } @@ -101,7 +110,8 @@ public static org.hamcrest.Matcher> everyIte * instead of: *
assertThat(cheese, equalTo(smelly))
*/ - public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) { + public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.Is.is(matcher); } @@ -112,7 +122,8 @@ public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) { * instead of: *
assertThat(cheese, is(equalTo(smelly)))
*/ - public static org.hamcrest.Matcher is(T value) { + public static org.hamcrest.Matcher is(T value) + { return org.hamcrest.core.Is.is(value); } @@ -123,25 +134,28 @@ public static org.hamcrest.Matcher is(T value) { * instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
*/ - public static org.hamcrest.Matcher isA(java.lang.Class type) { + public static org.hamcrest.Matcher isA(java.lang.Class type) + { return org.hamcrest.core.Is.isA(type); } /** * Creates a matcher that always matches, regardless of the examined object. */ - public static org.hamcrest.Matcher anything() { + public static org.hamcrest.Matcher anything() + { return org.hamcrest.core.IsAnything.anything(); } /** * Creates a matcher that always matches, regardless of the examined object, but describes * itself with the specified {@link String}. - * + * * @param description * a meaningful {@link String} used when describing itself */ - public static org.hamcrest.Matcher anything(java.lang.String description) { + public static org.hamcrest.Matcher anything(java.lang.String description) + { return org.hamcrest.core.IsAnything.anything(description); } @@ -152,11 +166,12 @@ public static org.hamcrest.Matcher anything(java.lang.String d * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
- * + * * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ - public static org.hamcrest.Matcher> hasItem(org.hamcrest.Matcher itemMatcher) { + public static org.hamcrest.Matcher> hasItem(org.hamcrest.Matcher itemMatcher) + { return IsIterableContaining.hasItem(itemMatcher); } @@ -167,11 +182,12 @@ public static org.hamcrest.Matcher> hasItem(or * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
- * + * * @param item * the item to compare against the items provided by the examined {@link Iterable} */ - public static org.hamcrest.Matcher> hasItem(T item) { + public static org.hamcrest.Matcher> hasItem(T item) + { return IsIterableContaining.hasItem(item); } @@ -182,12 +198,13 @@ public static org.hamcrest.Matcher> hasItem(T * the examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
- * + * * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> hasItems(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher> hasItems(org.hamcrest.Matcher... itemMatchers) + { return IsIterableContaining.hasItems(itemMatchers); } @@ -198,12 +215,13 @@ public static org.hamcrest.Matcher> hasItems(org.hamcr * examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
- * + * * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> hasItems(T... items) { + public static org.hamcrest.Matcher> hasItems(T... items) + { return IsIterableContaining.hasItems(items); } @@ -211,24 +229,25 @@ public static org.hamcrest.Matcher> hasItems(T... item * Creates a matcher that matches when the examined object is logically equal to the specified * operand, as determined by calling the {@link java.lang.Object#equals} method on * the examined object. - * + * *

If the specified operand is null then the created matcher will only match if * the examined object's equals method returns true when passed a * null (which would be a violation of the equals contract), unless the * examined object itself is null, in which case the matcher will return a positive * match.

- * + * *

The created matcher provides a special behaviour when examining Arrays, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) in the same - * indexes.

+ * indexes.

* For example: *
    * assertThat("foo", equalTo("foo"));
    * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
    * 
*/ - public static org.hamcrest.Matcher equalTo(T operand) { + public static org.hamcrest.Matcher equalTo(T operand) + { return org.hamcrest.core.IsEqual.equalTo(operand); } @@ -236,7 +255,8 @@ public static org.hamcrest.Matcher equalTo(T operand) { * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being * compared to be of the same static type. */ - public static org.hamcrest.Matcher equalToObject(java.lang.Object operand) { + public static org.hamcrest.Matcher equalToObject(java.lang.Object operand) + { return org.hamcrest.core.IsEqual.equalToObject(operand); } @@ -244,14 +264,15 @@ public static org.hamcrest.Matcher equalToObject(java.lang.Obj * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. - * + * *

The created matcher forces a relationship between specified type and the examined object, and should be * used when it is necessary to make generics conform, for example in the JMock clause * with(any(Thing.class))

* For example: *
assertThat(new Canoe(), instanceOf(Canoe.class));
*/ - public static org.hamcrest.Matcher any(java.lang.Class type) { + public static org.hamcrest.Matcher any(java.lang.Class type) + { return org.hamcrest.core.IsInstanceOf.any(type); } @@ -259,12 +280,13 @@ public static org.hamcrest.Matcher any(java.lang.Class type) { * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. - * + * *

The created matcher assumes no relationship between specified type and the examined object.

* For example: *
assertThat(new Canoe(), instanceOf(Paddlable.class));
*/ - public static org.hamcrest.Matcher instanceOf(java.lang.Class type) { + public static org.hamcrest.Matcher instanceOf(java.lang.Class type) + { return org.hamcrest.core.IsInstanceOf.instanceOf(type); } @@ -273,11 +295,12 @@ public static org.hamcrest.Matcher instanceOf(java.lang.Class type) { * it will match. * For example: *
assertThat(cheese, is(not(equalTo(smelly))))
- * + * * @param matcher * the matcher whose sense should be inverted */ - public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) { + public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.IsNot.not(matcher); } @@ -287,11 +310,12 @@ public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) { *
assertThat(cheese, is(not(smelly)))
* instead of: *
assertThat(cheese, is(not(equalTo(smelly))))
- * + * * @param value * the value that any examined object should not equal */ - public static org.hamcrest.Matcher not(T value) { + public static org.hamcrest.Matcher not(T value) + { return org.hamcrest.core.IsNot.not(value); } @@ -302,7 +326,8 @@ public static org.hamcrest.Matcher not(T value) { * instead of: *
assertThat(cheese, is(not(nullValue())))
*/ - public static org.hamcrest.Matcher notNullValue() { + public static org.hamcrest.Matcher notNullValue() + { return org.hamcrest.core.IsNull.notNullValue(); } @@ -313,11 +338,12 @@ public static org.hamcrest.Matcher notNullValue() { *
assertThat(cheese, is(notNullValue(X.class)))
* instead of: *
assertThat(cheese, is(not(nullValue(X.class))))
- * + * * @param type * dummy parameter used to infer the generic type of the returned matcher */ - public static org.hamcrest.Matcher notNullValue(java.lang.Class type) { + public static org.hamcrest.Matcher notNullValue(java.lang.Class type) + { return org.hamcrest.core.IsNull.notNullValue(type); } @@ -326,7 +352,8 @@ public static org.hamcrest.Matcher notNullValue(java.lang.Class type) * For example: *
assertThat(cheese, is(nullValue())
*/ - public static org.hamcrest.Matcher nullValue() { + public static org.hamcrest.Matcher nullValue() + { return org.hamcrest.core.IsNull.nullValue(); } @@ -335,33 +362,36 @@ public static org.hamcrest.Matcher nullValue() { * single dummy argument to facilitate type inference. * For example: *
assertThat(cheese, is(nullValue(Cheese.class))
- * + * * @param type * dummy parameter used to infer the generic type of the returned matcher */ - public static org.hamcrest.Matcher nullValue(java.lang.Class type) { + public static org.hamcrest.Matcher nullValue(java.lang.Class type) + { return org.hamcrest.core.IsNull.nullValue(type); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. - * + * * @param target * the target instance against which others should be assessed */ - public static org.hamcrest.Matcher sameInstance(T target) { + public static org.hamcrest.Matcher sameInstance(T target) + { return org.hamcrest.core.IsSame.sameInstance(target); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. - * + * * @param target * the target instance against which others should be assessed */ - public static org.hamcrest.Matcher theInstance(T target) { + public static org.hamcrest.Matcher theInstance(T target) + { return org.hamcrest.core.IsSame.theInstance(target); } @@ -370,11 +400,12 @@ public static org.hamcrest.Matcher theInstance(T target) { * {@link String} anywhere. * For example: *
assertThat("myStringOfNote", containsString("ring"))
- * + * * @param substring * the substring that the returned matcher will expect to find within any examined string */ - public static org.hamcrest.Matcher containsString(java.lang.String substring) { + public static org.hamcrest.Matcher containsString(java.lang.String substring) + { return org.hamcrest.core.StringContains.containsString(substring); } @@ -383,11 +414,12 @@ public static org.hamcrest.Matcher containsString(java.lang.St * {@link String} anywhere, ignoring case. * For example: *
assertThat("myStringOfNote", containsString("ring"))
- * + * * @param substring * the substring that the returned matcher will expect to find within any examined string */ - public static org.hamcrest.Matcher containsStringIgnoringCase(java.lang.String substring) { + public static org.hamcrest.Matcher containsStringIgnoringCase(java.lang.String substring) + { return org.hamcrest.core.StringContains.containsStringIgnoringCase(substring); } @@ -398,11 +430,12 @@ public static org.hamcrest.Matcher containsStringIgnoringCase( *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
- * + * * @param prefix - * the substring that the returned matcher will expect at the start of any examined string + * the substring that the returned matcher will expect at the start of any examined string */ - public static org.hamcrest.Matcher startsWith(java.lang.String prefix) { + public static org.hamcrest.Matcher startsWith(java.lang.String prefix) + { return org.hamcrest.core.StringStartsWith.startsWith(prefix); } @@ -413,11 +446,12 @@ public static org.hamcrest.Matcher startsWith(java.lang.String *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
- * + * * @param prefix - * the substring that the returned matcher will expect at the start of any examined string + * the substring that the returned matcher will expect at the start of any examined string */ - public static org.hamcrest.Matcher startsWithIgnoringCase(java.lang.String prefix) { + public static org.hamcrest.Matcher startsWithIgnoringCase(java.lang.String prefix) + { return org.hamcrest.core.StringStartsWith.startsWithIgnoringCase(prefix); } @@ -426,11 +460,12 @@ public static org.hamcrest.Matcher startsWithIgnoringCase(java * {@link String}. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
- * + * * @param suffix - * the substring that the returned matcher will expect at the end of any examined string + * the substring that the returned matcher will expect at the end of any examined string */ - public static org.hamcrest.Matcher endsWith(java.lang.String suffix) { + public static org.hamcrest.Matcher endsWith(java.lang.String suffix) + { return org.hamcrest.core.StringEndsWith.endsWith(suffix); } @@ -439,11 +474,12 @@ public static org.hamcrest.Matcher endsWith(java.lang.String s * {@link String}, ignoring case. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
- * + * * @param suffix - * the substring that the returned matcher will expect at the end of any examined string + * the substring that the returned matcher will expect at the end of any examined string */ - public static org.hamcrest.Matcher endsWithIgnoringCase(java.lang.String suffix) { + public static org.hamcrest.Matcher endsWithIgnoringCase(java.lang.String suffix) + { return org.hamcrest.core.StringEndsWith.endsWithIgnoringCase(suffix); } diff --git a/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java b/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java index 036a7640..fc128185 100644 --- a/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java @@ -15,23 +15,28 @@ * matcher makes sense. It should not be used by API designers implementing * matchers. * + * @param + * The type of object being matched. * @author Neil Dunn * @see CustomTypeSafeMatcher for a type safe variant of this class that you probably - * want to use. - * @param The type of object being matched. + * want to use. */ -public abstract class CustomMatcher extends BaseMatcher { - private final String fixedDescription; +public abstract class CustomMatcher extends BaseMatcher +{ + private final String fixedDescription; - public CustomMatcher(String description) { - if (description == null) { - throw new IllegalArgumentException("Description should be non null!"); - } - this.fixedDescription = description; + public CustomMatcher(String description) + { + if (description == null) + { + throw new IllegalArgumentException("Description should be non null!"); } + this.fixedDescription = description; + } - @Override - public final void describeTo(Description description) { - description.appendText(fixedDescription); - } + @Override + public final void describeTo(Description description) + { + description.appendText(fixedDescription); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java b/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java index 7c5c46ce..bd1d7173 100644 --- a/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java @@ -19,21 +19,26 @@ * is called the argument is guaranteed to be non-null and of the correct * type. * + * @param + * The type of object being matched * @author Neil Dunn - * @param The type of object being matched */ -public abstract class CustomTypeSafeMatcher extends TypeSafeMatcher { - private final String fixedDescription; +public abstract class CustomTypeSafeMatcher extends TypeSafeMatcher +{ + private final String fixedDescription; - public CustomTypeSafeMatcher(String description) { - if (description == null) { - throw new IllegalArgumentException("Description must be non null!"); - } - this.fixedDescription = description; + public CustomTypeSafeMatcher(String description) + { + if (description == null) + { + throw new IllegalArgumentException("Description must be non null!"); } + this.fixedDescription = description; + } - @Override - public final void describeTo(Description description) { - description.appendText(fixedDescription); - } + @Override + public final void describeTo(Description description) + { + description.appendText(fixedDescription); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/Description.java b/hamcrest/src/main/java/org/hamcrest/Description.java index 73bfa385..ce43e228 100644 --- a/hamcrest/src/main/java/org/hamcrest/Description.java +++ b/hamcrest/src/main/java/org/hamcrest/Description.java @@ -6,84 +6,93 @@ * * @see Matcher#describeTo(Description) */ -public interface Description { +public interface Description +{ /** * A description that consumes input but does nothing. */ static final Description NONE = new NullDescription(); - - /** - * Appends some plain text to the description. - */ - Description appendText(String text); - /** - * Appends the description of a {@link SelfDescribing} value to this description. - */ - Description appendDescriptionOf(SelfDescribing value); + /** + * Appends some plain text to the description. + */ + Description appendText(String text); - /** - * Appends an arbitrary value to the description. - */ - Description appendValue(Object value); + /** + * Appends the description of a {@link SelfDescribing} value to this description. + */ + Description appendDescriptionOf(SelfDescribing value); - /** - * Appends a list of values to the description. - */ - Description appendValueList(String start, String separator, String end, - T... values); + /** + * Appends an arbitrary value to the description. + */ + Description appendValue(Object value); - /** - * Appends a list of values to the description. - */ - Description appendValueList(String start, String separator, String end, - Iterable values); + /** + * Appends a list of values to the description. + */ + Description appendValueList(String start, String separator, String end, + T... values); - /** - * Appends a list of {@link org.hamcrest.SelfDescribing} objects - * to the description. - */ - Description appendList(String start, String separator, String end, - Iterable values); + /** + * Appends a list of values to the description. + */ + Description appendValueList(String start, String separator, String end, + Iterable values); + /** + * Appends a list of {@link org.hamcrest.SelfDescribing} objects + * to the description. + */ + Description appendList(String start, String separator, String end, + Iterable values); - public static final class NullDescription implements Description { - @Override - public Description appendDescriptionOf(SelfDescribing value) { - return this; - } - @Override - public Description appendList(String start, String separator, - String end, Iterable values) { - return this; - } + public static final class NullDescription implements Description + { + @Override + public Description appendDescriptionOf(SelfDescribing value) + { + return this; + } - @Override - public Description appendText(String text) { - return this; - } + @Override + public Description appendList(String start, String separator, + String end, Iterable values) + { + return this; + } - @Override - public Description appendValue(Object value) { - return this; - } + @Override + public Description appendText(String text) + { + return this; + } - @Override - public Description appendValueList(String start, String separator, - String end, T... values) { - return this; - } + @Override + public Description appendValue(Object value) + { + return this; + } + + @Override + public Description appendValueList(String start, String separator, + String end, T... values) + { + return this; + } - @Override - public Description appendValueList(String start, String separator, - String end, Iterable values) { - return this; - } + @Override + public Description appendValueList(String start, String separator, + String end, Iterable values) + { + return this; + } - @Override - public String toString() { - return ""; - } + @Override + public String toString() + { + return ""; } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java b/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java index f87de2df..515a6fe7 100644 --- a/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java @@ -2,20 +2,21 @@ /** * TODO(ngd): Document. - * - * @param */ -public abstract class DiagnosingMatcher extends BaseMatcher { +public abstract class DiagnosingMatcher extends BaseMatcher +{ - @Override - public final boolean matches(Object item) { - return matches(item, Description.NONE); - } + @Override + public final boolean matches(Object item) + { + return matches(item, Description.NONE); + } - @Override - public final void describeMismatch(Object item, Description mismatchDescription) { - matches(item, mismatchDescription); - } + @Override + public final void describeMismatch(Object item, Description mismatchDescription) + { + matches(item, mismatchDescription); + } - protected abstract boolean matches(Object item, Description mismatchDescription); + protected abstract boolean matches(Object item, Description mismatchDescription); } diff --git a/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java b/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java index 385cf999..90ef25ad 100644 --- a/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java @@ -4,51 +4,64 @@ /** * Supporting class for matching a feature of an object. Implement featureValueOf() - * in a subclass to pull out the feature to be matched against. + * in a subclass to pull out the feature to be matched against. * - * @param The type of the object to be matched - * @param The type of the feature to be matched + * @param + * The type of the object to be matched + * @param + * The type of the feature to be matched */ -public abstract class FeatureMatcher extends TypeSafeDiagnosingMatcher { - private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("featureValueOf", 1, 0); +public abstract class FeatureMatcher extends TypeSafeDiagnosingMatcher +{ + private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("featureValueOf", 1, 0); private final Matcher subMatcher; private final String featureDescription; private final String featureName; - + /** * Constructor - * @param subMatcher The matcher to apply to the feature - * @param featureDescription Descriptive text to use in describeTo - * @param featureName Identifying text for mismatch message + * + * @param subMatcher + * The matcher to apply to the feature + * @param featureDescription + * Descriptive text to use in describeTo + * @param featureName + * Identifying text for mismatch message */ - public FeatureMatcher(Matcher subMatcher, String featureDescription, String featureName) { + public FeatureMatcher(Matcher subMatcher, String featureDescription, String featureName) + { super(TYPE_FINDER); this.subMatcher = subMatcher; this.featureDescription = featureDescription; this.featureName = featureName; } - + /** * Implement this to extract the interesting feature. - * @param actual the target object + * + * @param actual + * the target object * @return the feature to be matched */ protected abstract U featureValueOf(T actual); @Override - protected boolean matchesSafely(T actual, Description mismatch) { + protected boolean matchesSafely(T actual, Description mismatch) + { final U featureValue = featureValueOf(actual); - if (!subMatcher.matches(featureValue)) { + if (!subMatcher.matches(featureValue)) + { mismatch.appendText(featureName).appendText(" "); subMatcher.describeMismatch(featureValue, mismatch); return false; } return true; } - + @Override - public final void describeTo(Description description) { + public final void describeTo(Description description) + { description.appendText(featureDescription).appendText(" ") - .appendDescriptionOf(subMatcher); + .appendDescriptionOf(subMatcher); } } diff --git a/hamcrest/src/main/java/org/hamcrest/Matcher.java b/hamcrest/src/main/java/org/hamcrest/Matcher.java index 77e09d5b..86e1839a 100644 --- a/hamcrest/src/main/java/org/hamcrest/Matcher.java +++ b/hamcrest/src/main/java/org/hamcrest/Matcher.java @@ -23,45 +23,47 @@ * * @see BaseMatcher */ -public interface Matcher extends SelfDescribing { +public interface Matcher extends SelfDescribing +{ - /** - * Evaluates the matcher for argument item. - * - * This method matches against Object, instead of the generic type T. This is - * because the caller of the Matcher does not know at runtime what the type is - * (because of type erasure with Java generics). It is down to the implementations - * to check the correct type. - * - * @param actual the object against which the matcher is evaluated. - * @return true if item matches, otherwise false. - * - * @see BaseMatcher - */ - boolean matches(Object actual); - - /** - * Generate a description of why the matcher has not accepted the item. - * The description will be part of a larger description of why a matching - * failed, so it should be concise. - * This method assumes that matches(item) is false, but - * will not check this. - * - * @param actual The item that the Matcher has rejected. - * @param mismatchDescription - * The description to be built or appended to. - */ - void describeMismatch(Object actual, Description mismatchDescription); + /** + * Evaluates the matcher for argument item. + *

+ * This method matches against Object, instead of the generic type T. This is + * because the caller of the Matcher does not know at runtime what the type is + * (because of type erasure with Java generics). It is down to the implementations + * to check the correct type. + * + * @param actual + * the object against which the matcher is evaluated. + * @return true if item matches, otherwise false. + * @see BaseMatcher + */ + boolean matches(Object actual); - /** - * This method simply acts a friendly reminder not to implement Matcher directly and - * instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore - * compile errors . - * - * @see Matcher for reasons why. - * @see BaseMatcher - * @deprecated to make - */ - @Deprecated - void _dont_implement_Matcher___instead_extend_BaseMatcher_(); + /** + * Generate a description of why the matcher has not accepted the item. + * The description will be part of a larger description of why a matching + * failed, so it should be concise. + * This method assumes that matches(item) is false, but + * will not check this. + * + * @param actual + * The item that the Matcher has rejected. + * @param mismatchDescription + * The description to be built or appended to. + */ + void describeMismatch(Object actual, Description mismatchDescription); + + /** + * This method simply acts a friendly reminder not to implement Matcher directly and + * instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore + * compile errors . + * + * @see Matcher for reasons why. + * @see BaseMatcher + * @deprecated to make + */ + @Deprecated + void _dont_implement_Matcher___instead_extend_BaseMatcher_(); } diff --git a/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java b/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java index bc001ebb..bab5e5c5 100644 --- a/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java +++ b/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java @@ -1,29 +1,35 @@ package org.hamcrest; -public class MatcherAssert { - public static void assertThat(T actual, Matcher matcher) { - assertThat("", actual, matcher); - } - - public static void assertThat(String reason, T actual, Matcher matcher) { - if (!matcher.matches(actual)) { - Description description = new StringDescription(); - description.appendText(reason) - .appendText(System.lineSeparator()) - .appendText("Expected: ") - .appendDescriptionOf(matcher) - .appendText(System.lineSeparator()) - .appendText(" but: "); - matcher.describeMismatch(actual, description); - - throw new AssertionError(description.toString()); - } +public class MatcherAssert +{ + public static void assertThat(T actual, Matcher matcher) + { + assertThat("", actual, matcher); + } + + public static void assertThat(String reason, T actual, Matcher matcher) + { + if (!matcher.matches(actual)) + { + Description description = new StringDescription(); + description.appendText(reason) + .appendText(System.lineSeparator()) + .appendText("Expected: ") + .appendDescriptionOf(matcher) + .appendText(System.lineSeparator()) + .appendText(" but: "); + matcher.describeMismatch(actual, description); + + throw new AssertionError(description.toString()); } - - public static void assertThat(String reason, boolean assertion) { - if (!assertion) { - throw new AssertionError(reason); - } + } + + public static void assertThat(String reason, boolean assertion) + { + if (!assertion) + { + throw new AssertionError(reason); } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/Matchers.java b/hamcrest/src/main/java/org/hamcrest/Matchers.java index 30064b12..f97682fe 100644 --- a/hamcrest/src/main/java/org/hamcrest/Matchers.java +++ b/hamcrest/src/main/java/org/hamcrest/Matchers.java @@ -7,15 +7,17 @@ import java.util.regex.Pattern; -@SuppressWarnings({"unused", "WeakerAccess"}) -public class Matchers { +@SuppressWarnings({ "unused", "WeakerAccess" }) +public class Matchers +{ /** * Creates a matcher that matches if the examined object matches ALL of the specified matchers. * For example: *

assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(java.lang.Iterable> matchers) { + public static org.hamcrest.Matcher allOf(java.lang.Iterable> matchers) + { return org.hamcrest.core.AllOf.allOf(matchers); } @@ -25,7 +27,8 @@ public static org.hamcrest.Matcher allOf(java.lang.IterableassertThat("myValue", allOf(startsWith("my"), containsString("Val"))) */ @SafeVarargs - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher... matchers) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher... matchers) + { return org.hamcrest.core.AllOf.allOf(matchers); } @@ -34,7 +37,8 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher. * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second) + { return org.hamcrest.core.AllOf.allOf(first, second); } @@ -43,7 +47,8 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third) + { return org.hamcrest.core.AllOf.allOf(first, second, third); } @@ -52,7 +57,8 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth) + { return org.hamcrest.core.AllOf.allOf(first, second, third, fourth); } @@ -61,7 +67,8 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth) + { return org.hamcrest.core.AllOf.allOf(first, second, third, fourth, fifth); } @@ -70,7 +77,9 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher * For example: *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
*/ - public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth, org.hamcrest.Matcher sixth) { + public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth, + org.hamcrest.Matcher sixth) + { return org.hamcrest.core.AllOf.allOf(first, second, third, fourth, fifth, sixth); } @@ -79,7 +88,8 @@ public static org.hamcrest.Matcher allOf(org.hamcrest.Matcher * For example: *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
*/ - public static org.hamcrest.core.AnyOf anyOf(java.lang.Iterable> matchers) { + public static org.hamcrest.core.AnyOf anyOf(java.lang.Iterable> matchers) + { return org.hamcrest.core.AnyOf.anyOf(matchers); } @@ -89,7 +99,8 @@ public static org.hamcrest.core.AnyOf anyOf(java.lang.IterableassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ @SafeVarargs - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher... matchers) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher... matchers) + { return org.hamcrest.core.AnyOf.anyOf(matchers); } @@ -98,7 +109,8 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second) + { return org.hamcrest.core.AnyOf.anyOf(first, second); } @@ -107,7 +119,8 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third) + { return org.hamcrest.core.AnyOf.anyOf(first, second, third); } @@ -116,7 +129,8 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth) + { return org.hamcrest.core.AnyOf.anyOf(first, second, third, fourth); } @@ -125,7 +139,8 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth) + { return org.hamcrest.core.AnyOf.anyOf(first, second, third, fourth, fifth); } @@ -134,7 +149,9 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("myValue", anyOf(startsWith("foo"), containsString("Val"))) */ - public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth, org.hamcrest.Matcher sixth) { + public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.Matcher first, org.hamcrest.Matcher second, org.hamcrest.Matcher third, org.hamcrest.Matcher fourth, org.hamcrest.Matcher fifth, + org.hamcrest.Matcher sixth) + { return org.hamcrest.core.AnyOf.anyOf(first, second, third, fourth, fifth, sixth); } @@ -143,7 +160,8 @@ public static org.hamcrest.core.AnyOf anyOf(org.hamcrest.MatcherassertThat("fab", both(containsString("a")).and(containsString("b"))) */ - public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcher both(org.hamcrest.Matcher matcher) { + public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcher both(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.CombinableMatcher.both(matcher); } @@ -152,7 +170,8 @@ public static org.hamcrest.core.CombinableMatcher.CombinableBothMatcherassertThat("fan", either(containsString("a")).or(containsString("b"))) */ - public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher either(org.hamcrest.Matcher matcher) { + public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher either(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.CombinableMatcher.either(matcher); } @@ -161,7 +180,7 @@ public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher< * delegated to the decorated matcher, including its mismatch description. * For example: *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
- * + * * @param description * the new description for the wrapped matcher * @param matcher @@ -169,7 +188,8 @@ public static org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher< * @param values * optional values to insert into the tokenized description */ - public static org.hamcrest.Matcher describedAs(java.lang.String description, org.hamcrest.Matcher matcher, java.lang.Object... values) { + public static org.hamcrest.Matcher describedAs(java.lang.String description, org.hamcrest.Matcher matcher, java.lang.Object... values) + { return org.hamcrest.core.DescribedAs.describedAs(description, matcher, values); } @@ -179,11 +199,12 @@ public static org.hamcrest.Matcher describedAs(java.lang.String descripti * itemMatcher. * For example: *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
- * + * * @param itemMatcher * the matcher to apply to every item provided by the examined {@link Iterable} */ - public static org.hamcrest.Matcher> everyItem(org.hamcrest.Matcher itemMatcher) { + public static org.hamcrest.Matcher> everyItem(org.hamcrest.Matcher itemMatcher) + { return org.hamcrest.core.Every.everyItem(itemMatcher); } @@ -195,7 +216,8 @@ public static org.hamcrest.Matcher> everyIte * instead of: *
assertThat(cheese, equalTo(smelly))
*/ - public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) { + public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.Is.is(matcher); } @@ -206,7 +228,8 @@ public static org.hamcrest.Matcher is(org.hamcrest.Matcher matcher) { * instead of: *
assertThat(cheese, is(equalTo(smelly)))
*/ - public static org.hamcrest.Matcher is(T value) { + public static org.hamcrest.Matcher is(T value) + { return org.hamcrest.core.Is.is(value); } @@ -217,25 +240,28 @@ public static org.hamcrest.Matcher is(T value) { * instead of: *
assertThat(cheese, is(instanceOf(Cheddar.class)))
*/ - public static org.hamcrest.Matcher isA(java.lang.Class type) { + public static org.hamcrest.Matcher isA(java.lang.Class type) + { return org.hamcrest.core.Is.isA(type); } /** * Creates a matcher that always matches, regardless of the examined object. */ - public static org.hamcrest.Matcher anything() { + public static org.hamcrest.Matcher anything() + { return org.hamcrest.core.IsAnything.anything(); } /** * Creates a matcher that always matches, regardless of the examined object, but describes * itself with the specified {@link String}. - * + * * @param description * a meaningful {@link String} used when describing itself */ - public static org.hamcrest.Matcher anything(java.lang.String description) { + public static org.hamcrest.Matcher anything(java.lang.String description) + { return org.hamcrest.core.IsAnything.anything(description); } @@ -246,11 +272,12 @@ public static org.hamcrest.Matcher anything(java.lang.String d * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
- * + * * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ - public static org.hamcrest.Matcher> hasItem(org.hamcrest.Matcher itemMatcher) { + public static org.hamcrest.Matcher> hasItem(org.hamcrest.Matcher itemMatcher) + { return IsIterableContaining.hasItem(itemMatcher); } @@ -261,11 +288,12 @@ public static org.hamcrest.Matcher> hasItem(or * will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
- * + * * @param item * the item to compare against the items provided by the examined {@link Iterable} */ - public static org.hamcrest.Matcher> hasItem(T item) { + public static org.hamcrest.Matcher> hasItem(T item) + { return IsIterableContaining.hasItem(item); } @@ -276,12 +304,13 @@ public static org.hamcrest.Matcher> hasItem(T * the examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
- * + * * @param itemMatchers * the matchers to apply to items provided by the examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> hasItems(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher> hasItems(org.hamcrest.Matcher... itemMatchers) + { return IsIterableContaining.hasItems(itemMatchers); } @@ -292,12 +321,13 @@ public static org.hamcrest.Matcher> hasItems(org.hamcr * examined {@link Iterable} will stop as soon as a matching item is found. * For example: *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
- * + * * @param items * the items to compare against the items provided by the examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> hasItems(T... items) { + public static org.hamcrest.Matcher> hasItems(T... items) + { return IsIterableContaining.hasItems(items); } @@ -305,24 +335,25 @@ public static org.hamcrest.Matcher> hasItems(T... item * Creates a matcher that matches when the examined object is logically equal to the specified * operand, as determined by calling the {@link java.lang.Object#equals} method on * the examined object. - * + * *

If the specified operand is null then the created matcher will only match if * the examined object's equals method returns true when passed a * null (which would be a violation of the equals contract), unless the * examined object itself is null, in which case the matcher will return a positive * match.

- * + * *

The created matcher provides a special behaviour when examining Arrays, whereby * it will match if both the operand and the examined object are arrays of the same length and * contain items that are equal to each other (according to the above rules) in the same - * indexes.

+ * indexes.

* For example: *
    * assertThat("foo", equalTo("foo"));
    * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
    * 
*/ - public static org.hamcrest.Matcher equalTo(T operand) { + public static org.hamcrest.Matcher equalTo(T operand) + { return org.hamcrest.core.IsEqual.equalTo(operand); } @@ -330,7 +361,8 @@ public static org.hamcrest.Matcher equalTo(T operand) { * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being * compared to be of the same static type. */ - public static org.hamcrest.Matcher equalToObject(java.lang.Object operand) { + public static org.hamcrest.Matcher equalToObject(java.lang.Object operand) + { return org.hamcrest.core.IsEqual.equalToObject(operand); } @@ -338,14 +370,15 @@ public static org.hamcrest.Matcher equalToObject(java.lang.Obj * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. - * + * *

The created matcher forces a relationship between specified type and the examined object, and should be * used when it is necessary to make generics conform, for example in the JMock clause * with(any(Thing.class))

* For example: *
assertThat(new Canoe(), instanceOf(Canoe.class));
*/ - public static org.hamcrest.Matcher any(java.lang.Class type) { + public static org.hamcrest.Matcher any(java.lang.Class type) + { return org.hamcrest.core.IsInstanceOf.any(type); } @@ -353,12 +386,13 @@ public static org.hamcrest.Matcher any(java.lang.Class type) { * Creates a matcher that matches when the examined object is an instance of the specified type, * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the * the examined object. - * + * *

The created matcher assumes no relationship between specified type and the examined object.

* For example: *
assertThat(new Canoe(), instanceOf(Paddlable.class));
*/ - public static org.hamcrest.Matcher instanceOf(java.lang.Class type) { + public static org.hamcrest.Matcher instanceOf(java.lang.Class type) + { return org.hamcrest.core.IsInstanceOf.instanceOf(type); } @@ -367,11 +401,12 @@ public static org.hamcrest.Matcher instanceOf(java.lang.Class type) { * it will match. * For example: *
assertThat(cheese, is(not(equalTo(smelly))))
- * + * * @param matcher * the matcher whose sense should be inverted */ - public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) { + public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) + { return org.hamcrest.core.IsNot.not(matcher); } @@ -381,11 +416,12 @@ public static org.hamcrest.Matcher not(org.hamcrest.Matcher matcher) { *
assertThat(cheese, is(not(smelly)))
* instead of: *
assertThat(cheese, is(not(equalTo(smelly))))
- * + * * @param value * the value that any examined object should not equal */ - public static org.hamcrest.Matcher not(T value) { + public static org.hamcrest.Matcher not(T value) + { return org.hamcrest.core.IsNot.not(value); } @@ -396,7 +432,8 @@ public static org.hamcrest.Matcher not(T value) { * instead of: *
assertThat(cheese, is(not(nullValue())))
*/ - public static org.hamcrest.Matcher notNullValue() { + public static org.hamcrest.Matcher notNullValue() + { return org.hamcrest.core.IsNull.notNullValue(); } @@ -407,11 +444,12 @@ public static org.hamcrest.Matcher notNullValue() { *
assertThat(cheese, is(notNullValue(X.class)))
* instead of: *
assertThat(cheese, is(not(nullValue(X.class))))
- * + * * @param type * dummy parameter used to infer the generic type of the returned matcher */ - public static org.hamcrest.Matcher notNullValue(java.lang.Class type) { + public static org.hamcrest.Matcher notNullValue(java.lang.Class type) + { return org.hamcrest.core.IsNull.notNullValue(type); } @@ -420,7 +458,8 @@ public static org.hamcrest.Matcher notNullValue(java.lang.Class type) * For example: *
assertThat(cheese, is(nullValue())
*/ - public static org.hamcrest.Matcher nullValue() { + public static org.hamcrest.Matcher nullValue() + { return org.hamcrest.core.IsNull.nullValue(); } @@ -429,46 +468,50 @@ public static org.hamcrest.Matcher nullValue() { * single dummy argument to facilitate type inference. * For example: *
assertThat(cheese, is(nullValue(Cheese.class))
- * + * * @param type * dummy parameter used to infer the generic type of the returned matcher */ - public static org.hamcrest.Matcher nullValue(java.lang.Class type) { + public static org.hamcrest.Matcher nullValue(java.lang.Class type) + { return org.hamcrest.core.IsNull.nullValue(type); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. - * + * * @param target * the target instance against which others should be assessed */ - public static org.hamcrest.Matcher sameInstance(T target) { + public static org.hamcrest.Matcher sameInstance(T target) + { return org.hamcrest.core.IsSame.sameInstance(target); } /** * Creates a matcher that matches only when the examined object is the same instance as * the specified target object. - * + * * @param target * the target instance against which others should be assessed */ - public static org.hamcrest.Matcher theInstance(T target) { + public static org.hamcrest.Matcher theInstance(T target) + { return org.hamcrest.core.IsSame.theInstance(target); } - + /** * Creates a matcher that matches if the examined {@link String} contains the specified * {@link String} anywhere. * For example: *
assertThat("myStringOfNote", containsString("ring"))
- * + * * @param substring * the substring that the returned matcher will expect to find within any examined string */ - public static Matcher containsString(java.lang.String substring) { + public static Matcher containsString(java.lang.String substring) + { return org.hamcrest.core.StringContains.containsString(substring); } @@ -477,11 +520,12 @@ public static Matcher containsString(java.lang.String substrin * {@link String} anywhere, ignoring case. * For example: *
assertThat("myStringOfNote", containsStringIgnoringCase("Ring"))
- * + * * @param substring * the substring that the returned matcher will expect to find within any examined string */ - public static Matcher containsStringIgnoringCase(java.lang.String substring) { + public static Matcher containsStringIgnoringCase(java.lang.String substring) + { return org.hamcrest.core.StringContains.containsStringIgnoringCase(substring); } @@ -492,11 +536,12 @@ public static Matcher containsStringIgnoringCase(java.lang.Str *

* For example: *
assertThat("myStringOfNote", startsWith("my"))
- * + * * @param prefix - * the substring that the returned matcher will expect at the start of any examined string + * the substring that the returned matcher will expect at the start of any examined string */ - public static Matcher startsWith(java.lang.String prefix) { + public static Matcher startsWith(java.lang.String prefix) + { return org.hamcrest.core.StringStartsWith.startsWith(prefix); } @@ -507,11 +552,12 @@ public static Matcher startsWith(java.lang.String prefix) { *

* For example: *
assertThat("myStringOfNote", startsWithIgnoringCase("My"))
- * + * * @param prefix - * the substring that the returned matcher will expect at the start of any examined string + * the substring that the returned matcher will expect at the start of any examined string */ - public static Matcher startsWithIgnoringCase(java.lang.String prefix) { + public static Matcher startsWithIgnoringCase(java.lang.String prefix) + { return org.hamcrest.core.StringStartsWith.startsWithIgnoringCase(prefix); } @@ -520,11 +566,12 @@ public static Matcher startsWithIgnoringCase(java.lang.String * {@link String}. * For example: *
assertThat("myStringOfNote", endsWith("Note"))
- * + * * @param suffix - * the substring that the returned matcher will expect at the end of any examined string + * the substring that the returned matcher will expect at the end of any examined string */ - public static Matcher endsWith(java.lang.String suffix) { + public static Matcher endsWith(java.lang.String suffix) + { return org.hamcrest.core.StringEndsWith.endsWith(suffix); } @@ -533,11 +580,12 @@ public static Matcher endsWith(java.lang.String suffix) { * {@link String}, ignoring case. * For example: *
assertThat("myStringOfNote", endsWithIgnoringCase("note"))
- * + * * @param suffix - * the substring that the returned matcher will expect at the end of any examined string + * the substring that the returned matcher will expect at the end of any examined string */ - public static Matcher endsWithIgnoringCase(java.lang.String suffix) { + public static Matcher endsWithIgnoringCase(java.lang.String suffix) + { return org.hamcrest.core.StringEndsWith.endsWithIgnoringCase(suffix); } @@ -549,10 +597,11 @@ public static Matcher endsWithIgnoringCase(java.lang.String su * * * @param pattern - * the pattern to be used. + * the pattern to be used. * @return The matcher. */ - public static Matcher matchesRegex(Pattern pattern) { + public static Matcher matchesRegex(Pattern pattern) + { return StringRegularExpression.matchesRegex(pattern); } @@ -564,10 +613,11 @@ public static Matcher matchesRegex(Pattern pattern) { * * * @param regex - * The regex to be used for the validation. + * The regex to be used for the validation. * @return The matcher. */ - public static Matcher matchesRegex(String regex) { + public static Matcher matchesRegex(String regex) + { return StringRegularExpression.matchesRegex(Pattern.compile(regex)); } @@ -577,12 +627,13 @@ public static Matcher matchesRegex(String regex) { * each matcher[i] is satisfied by array[i]. * For example: *
assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))
- * + * * @param elementMatchers * the matchers that the elements of examined arrays should satisfy */ @SafeVarargs - public static org.hamcrest.collection.IsArray array(org.hamcrest.Matcher... elementMatchers) { + public static org.hamcrest.collection.IsArray array(org.hamcrest.Matcher... elementMatchers) + { return org.hamcrest.collection.IsArray.array(elementMatchers); } @@ -592,11 +643,12 @@ public static org.hamcrest.collection.IsArray array(org.hamcrest.Matcher< * of the examined array will stop as soon as a matching element is found. * For example: *
assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))
- * + * * @param elementMatcher * the matcher to apply to elements in examined arrays */ - public static org.hamcrest.Matcher hasItemInArray(org.hamcrest.Matcher elementMatcher) { + public static org.hamcrest.Matcher hasItemInArray(org.hamcrest.Matcher elementMatcher) + { return ArrayMatching.hasItemInArray(elementMatcher); } @@ -606,11 +658,12 @@ public static org.hamcrest.Matcher hasItemInArray(org.hamcrest.Matcher< *
assertThat(hasItemInArray(x))
* instead of: *
assertThat(hasItemInArray(equalTo(x)))
- * + * * @param element * the element that should be present in examined arrays */ - public static org.hamcrest.Matcher hasItemInArray(T element) { + public static org.hamcrest.Matcher hasItemInArray(T element) + { return ArrayMatching.hasItemInArray(element); } @@ -620,12 +673,13 @@ public static org.hamcrest.Matcher hasItemInArray(T element) { * the examined array must be of the same length as the number of specified items. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining("foo", "bar"))
- * + * * @param items * the items that must equal the items within an examined array */ @SafeVarargs - public static org.hamcrest.Matcher arrayContaining(E... items) { + public static org.hamcrest.Matcher arrayContaining(E... items) + { return ArrayMatching.arrayContaining(items); } @@ -635,12 +689,13 @@ public static org.hamcrest.Matcher arrayContaining(E... items) { * must be of the same length as the number of specified matchers. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining(equalTo("foo"), equalTo("bar")))
- * + * * @param itemMatchers * the matchers that must be satisfied by the items in the examined array */ @SafeVarargs - public static org.hamcrest.Matcher arrayContaining(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher arrayContaining(org.hamcrest.Matcher... itemMatchers) + { return ArrayMatching.arrayContaining(itemMatchers); } @@ -650,11 +705,12 @@ public static org.hamcrest.Matcher arrayContaining(org.hamcrest.Matcher * must be of the same length as the specified list of matchers. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayContaining(Arrays.asList(equalTo("foo"), equalTo("bar"))))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item in an examined array */ - public static org.hamcrest.Matcher arrayContaining(java.util.List> itemMatchers) { + public static org.hamcrest.Matcher arrayContaining(java.util.List> itemMatchers) + { return ArrayMatching.arrayContaining(itemMatchers); } @@ -674,12 +730,13 @@ public static org.hamcrest.Matcher arrayContaining(java.util.List *
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by an entry in an examined array */ @SafeVarargs - public static org.hamcrest.Matcher arrayContainingInAnyOrder(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher arrayContainingInAnyOrder(org.hamcrest.Matcher... itemMatchers) + { return ArrayMatching.arrayContainingInAnyOrder(itemMatchers); } @@ -699,11 +756,12 @@ public static org.hamcrest.Matcher arrayContainingInAnyOrder(org.hamcre * For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined array */ - public static org.hamcrest.Matcher arrayContainingInAnyOrder(java.util.Collection> itemMatchers) { + public static org.hamcrest.Matcher arrayContainingInAnyOrder(java.util.Collection> itemMatchers) + { return ArrayMatching.arrayContainingInAnyOrder(itemMatchers); } @@ -721,12 +779,13 @@ public static org.hamcrest.Matcher arrayContainingInAnyOrder(java.util. * For example: *

*
assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder("bar", "foo"))
- * + * * @param items * the items that must equal the entries of an examined array, in any order */ @SafeVarargs - public static org.hamcrest.Matcher arrayContainingInAnyOrder(E... items) { + public static org.hamcrest.Matcher arrayContainingInAnyOrder(E... items) + { return ArrayMatching.arrayContainingInAnyOrder(items); } @@ -735,11 +794,12 @@ public static org.hamcrest.Matcher arrayContainingInAnyOrder(E... items * satisfies the specified matcher. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))
- * + * * @param sizeMatcher * a matcher for the length of an examined array */ - public static org.hamcrest.Matcher arrayWithSize(org.hamcrest.Matcher sizeMatcher) { + public static org.hamcrest.Matcher arrayWithSize(org.hamcrest.Matcher sizeMatcher) + { return org.hamcrest.collection.IsArrayWithSize.arrayWithSize(sizeMatcher); } @@ -748,11 +808,12 @@ public static org.hamcrest.Matcher arrayWithSize(org.hamcrest.Matchersize. * For example: *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))
- * + * * @param size * the length that an examined array must have for a positive match */ - public static org.hamcrest.Matcher arrayWithSize(int size) { + public static org.hamcrest.Matcher arrayWithSize(int size) + { return org.hamcrest.collection.IsArrayWithSize.arrayWithSize(size); } @@ -762,7 +823,8 @@ public static org.hamcrest.Matcher arrayWithSize(int size) { * For example: *
assertThat(new String[0], emptyArray())
*/ - public static org.hamcrest.Matcher emptyArray() { + public static org.hamcrest.Matcher emptyArray() + { return org.hamcrest.collection.IsArrayWithSize.emptyArray(); } @@ -771,11 +833,12 @@ public static org.hamcrest.Matcher emptyArray() { * a value that satisfies the specified matcher. * For example: *
assertThat(myMap, is(aMapWithSize(equalTo(2))))
- * + * * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Map} */ - public static org.hamcrest.Matcher> aMapWithSize(org.hamcrest.Matcher sizeMatcher) { + public static org.hamcrest.Matcher> aMapWithSize(org.hamcrest.Matcher sizeMatcher) + { return org.hamcrest.collection.IsMapWithSize.aMapWithSize(sizeMatcher); } @@ -784,11 +847,12 @@ public static org.hamcrest.Matcher * a value equal to the specified size. * For example: *
assertThat(myMap, is(aMapWithSize(2)))
- * + * * @param size * the expected size of an examined {@link java.util.Map} */ - public static org.hamcrest.Matcher> aMapWithSize(int size) { + public static org.hamcrest.Matcher> aMapWithSize(int size) + { return org.hamcrest.collection.IsMapWithSize.aMapWithSize(size); } @@ -798,7 +862,8 @@ public static org.hamcrest.Matcher * For example: *
assertThat(myMap, is(anEmptyMap()))
*/ - public static org.hamcrest.Matcher> anEmptyMap() { + public static org.hamcrest.Matcher> anEmptyMap() + { return org.hamcrest.collection.IsMapWithSize.anEmptyMap(); } @@ -807,11 +872,12 @@ public static org.hamcrest.Matcher * a value that satisfies the specified matcher. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))
- * + * * @param sizeMatcher * a matcher for the size of an examined {@link java.util.Collection} */ - public static org.hamcrest.Matcher> hasSize(org.hamcrest.Matcher sizeMatcher) { + public static org.hamcrest.Matcher> hasSize(org.hamcrest.Matcher sizeMatcher) + { return org.hamcrest.collection.IsCollectionWithSize.hasSize(sizeMatcher); } @@ -820,11 +886,12 @@ public static org.hamcrest.Matcher> hasSiz * a value equal to the specified size. * For example: *
assertThat(Arrays.asList("foo", "bar"), hasSize(2))
- * + * * @param size * the expected size of an examined {@link java.util.Collection} */ - public static org.hamcrest.Matcher> hasSize(int size) { + public static org.hamcrest.Matcher> hasSize(int size) + { return org.hamcrest.collection.IsCollectionWithSize.hasSize(size); } @@ -834,7 +901,8 @@ public static org.hamcrest.Matcher> hasSiz * For example: *
assertThat(new ArrayList<String>(), is(empty()))
*/ - public static org.hamcrest.Matcher> empty() { + public static org.hamcrest.Matcher> empty() + { return org.hamcrest.collection.IsEmptyCollection.empty(); } @@ -843,11 +911,12 @@ public static org.hamcrest.Matcher> empty( * method returns true. * For example: *
assertThat(new ArrayList<String>(), is(emptyCollectionOf(String.class)))
- * + * * @param unusedToForceReturnType * the type of the collection's content */ - public static org.hamcrest.Matcher> emptyCollectionOf(java.lang.Class unusedToForceReturnType) { + public static org.hamcrest.Matcher> emptyCollectionOf(java.lang.Class unusedToForceReturnType) + { return org.hamcrest.collection.IsEmptyCollection.emptyCollectionOf(unusedToForceReturnType); } @@ -856,7 +925,8 @@ public static org.hamcrest.Matcher> emptyCollectionO * For example: *
assertThat(new ArrayList<String>(), is(emptyIterable()))
*/ - public static org.hamcrest.Matcher> emptyIterable() { + public static org.hamcrest.Matcher> emptyIterable() + { return org.hamcrest.collection.IsEmptyIterable.emptyIterable(); } @@ -864,11 +934,12 @@ public static org.hamcrest.Matcher> emptyIte * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. * For example: *
assertThat(new ArrayList<String>(), is(emptyIterableOf(String.class)))
- * + * * @param unusedToForceReturnType * the type of the iterable's content */ - public static org.hamcrest.Matcher> emptyIterableOf(java.lang.Class unusedToForceReturnType) { + public static org.hamcrest.Matcher> emptyIterableOf(java.lang.Class unusedToForceReturnType) + { return org.hamcrest.collection.IsEmptyIterable.emptyIterableOf(unusedToForceReturnType); } @@ -879,12 +950,13 @@ public static org.hamcrest.Matcher> emptyIterableOf(ja * must be of the same length as the number of specified items. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains("foo", "bar"))
- * + * * @param items * the items that must equal the items provided by an examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> contains(E... items) { + public static org.hamcrest.Matcher> contains(E... items) + { return org.hamcrest.collection.IsIterableContainingInOrder.contains(items); } @@ -894,12 +966,13 @@ public static org.hamcrest.Matcher> contains * For a positive match, the examined iterable must only yield one item. * For example: *
assertThat(Arrays.asList("foo"), contains(equalTo("foo")))
- * + * * @param itemMatcher * the matcher that must be satisfied by the single item provided by an * examined {@link Iterable} */ - public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher itemMatcher) { + public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher itemMatcher) + { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatcher); } @@ -910,12 +983,13 @@ public static org.hamcrest.Matcher> contains * must be of the same length as the number of specified matchers. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains(equalTo("foo"), equalTo("bar")))
- * + * * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher... itemMatchers) + { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatchers); } @@ -926,12 +1000,13 @@ public static org.hamcrest.Matcher> contains * must be of the same length as the specified list of matchers. * For example: *
assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item provided by * an examined {@link Iterable} */ - public static org.hamcrest.Matcher> contains(java.util.List> itemMatchers) { + public static org.hamcrest.Matcher> contains(java.util.List> itemMatchers) + { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatchers); } @@ -951,12 +1026,13 @@ public static org.hamcrest.Matcher> contains * For example: *

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(equalTo("bar"), equalTo("foo")))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ @SafeVarargs - public static org.hamcrest.Matcher> containsInAnyOrder(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher> containsInAnyOrder(org.hamcrest.Matcher... itemMatchers) + { return org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder(itemMatchers); } @@ -976,12 +1052,13 @@ public static org.hamcrest.Matcher> contains * For example: *

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder("bar", "foo"))
- * + * * @param items * the items that must equal the items provided by an examined {@link Iterable} in any order */ @SafeVarargs - public static org.hamcrest.Matcher> containsInAnyOrder(T... items) { + public static org.hamcrest.Matcher> containsInAnyOrder(T... items) + { return org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder(items); } @@ -999,11 +1076,12 @@ public static org.hamcrest.Matcher> contains *

*

For example:

*
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} */ - public static org.hamcrest.Matcher> containsInAnyOrder(java.util.Collection> itemMatchers) { + public static org.hamcrest.Matcher> containsInAnyOrder(java.util.Collection> itemMatchers) + { return org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder(itemMatchers); } @@ -1013,12 +1091,13 @@ public static org.hamcrest.Matcher> contains * corresponding item in the specified items, in the same relative order * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder("b", "d"))
- * + * * @param items * the items that must be contained within items provided by an examined {@link Iterable} in the same relative order */ @SafeVarargs - public static org.hamcrest.Matcher> containsInRelativeOrder(E... items) { + public static org.hamcrest.Matcher> containsInRelativeOrder(E... items) + { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(items); } @@ -1028,12 +1107,13 @@ public static org.hamcrest.Matcher> contains * matcher in the specified matchers, in the same relative order. * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
- * + * * @param itemMatchers * the matchers that must be satisfied by the items provided by an examined {@link Iterable} in the same relative order */ @SafeVarargs - public static org.hamcrest.Matcher> containsInRelativeOrder(org.hamcrest.Matcher... itemMatchers) { + public static org.hamcrest.Matcher> containsInRelativeOrder(org.hamcrest.Matcher... itemMatchers) + { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(itemMatchers); } @@ -1043,12 +1123,13 @@ public static org.hamcrest.Matcher> contains * matcher in the specified list of matchers, in the same relative order. * For example: *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), contains(Arrays.asList(equalTo("b"), equalTo("d"))))
- * + * * @param itemMatchers * a list of matchers, each of which must be satisfied by the items provided by * an examined {@link Iterable} in the same relative order */ - public static org.hamcrest.Matcher> containsInRelativeOrder(java.util.List> itemMatchers) { + public static org.hamcrest.Matcher> containsInRelativeOrder(java.util.List> itemMatchers) + { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(itemMatchers); } @@ -1058,11 +1139,12 @@ public static org.hamcrest.Matcher> contains * matcher. * For example: *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(equalTo(2)))
- * + * * @param sizeMatcher * a matcher for the number of items that should be yielded by an examined {@link Iterable} */ - public static org.hamcrest.Matcher> iterableWithSize(org.hamcrest.Matcher sizeMatcher) { + public static org.hamcrest.Matcher> iterableWithSize(org.hamcrest.Matcher sizeMatcher) + { return org.hamcrest.collection.IsIterableWithSize.iterableWithSize(sizeMatcher); } @@ -1072,11 +1154,12 @@ public static org.hamcrest.Matcher> iterableWithSize(o * size argument. * For example: *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(2))
- * + * * @param size * the number of items that should be yielded by an examined {@link Iterable} */ - public static org.hamcrest.Matcher> iterableWithSize(int size) { + public static org.hamcrest.Matcher> iterableWithSize(int size) + { return org.hamcrest.collection.IsIterableWithSize.iterableWithSize(size); } @@ -1086,13 +1169,14 @@ public static org.hamcrest.Matcher> iterableWithSize(i * value satisfies the specified valueMatcher. * For example: *
assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))
- * + * * @param keyMatcher * the key matcher that, in combination with the valueMatcher, must be satisfied by at least one entry * @param valueMatcher * the value matcher that, in combination with the keyMatcher, must be satisfied by at least one entry */ - public static org.hamcrest.Matcher> hasEntry(org.hamcrest.Matcher keyMatcher, org.hamcrest.Matcher valueMatcher) { + public static org.hamcrest.Matcher> hasEntry(org.hamcrest.Matcher keyMatcher, org.hamcrest.Matcher valueMatcher) + { return org.hamcrest.collection.IsMapContaining.hasEntry(keyMatcher, valueMatcher); } @@ -1102,13 +1186,14 @@ public static org.hamcrest.Matcher * specified value. * For example: *
assertThat(myMap, hasEntry("bar", "foo"))
- * + * * @param key * the key that, in combination with the value, must be describe at least one entry * @param value * the value that, in combination with the key, must be describe at least one entry */ - public static org.hamcrest.Matcher> hasEntry(K key, V value) { + public static org.hamcrest.Matcher> hasEntry(K key, V value) + { return org.hamcrest.collection.IsMapContaining.hasEntry(key, value); } @@ -1117,11 +1202,12 @@ public static org.hamcrest.Matcher * at least one key that satisfies the specified matcher. * For example: *
assertThat(myMap, hasKey(equalTo("bar")))
- * + * * @param keyMatcher * the matcher that must be satisfied by at least one key */ - public static org.hamcrest.Matcher> hasKey(org.hamcrest.Matcher keyMatcher) { + public static org.hamcrest.Matcher> hasKey(org.hamcrest.Matcher keyMatcher) + { return org.hamcrest.collection.IsMapContaining.hasKey(keyMatcher); } @@ -1130,11 +1216,12 @@ public static org.hamcrest.Matcher> hasKey(org. * at least one key that is equal to the specified key. * For example: *
assertThat(myMap, hasKey("bar"))
- * + * * @param key * the key that satisfying maps must contain */ - public static org.hamcrest.Matcher> hasKey(K key) { + public static org.hamcrest.Matcher> hasKey(K key) + { return org.hamcrest.collection.IsMapContaining.hasKey(key); } @@ -1143,11 +1230,12 @@ public static org.hamcrest.Matcher> hasKey(K ke * at least one value that satisfies the specified valueMatcher. * For example: *
assertThat(myMap, hasValue(equalTo("foo")))
- * + * * @param valueMatcher * the matcher that must be satisfied by at least one value */ - public static org.hamcrest.Matcher> hasValue(org.hamcrest.Matcher valueMatcher) { + public static org.hamcrest.Matcher> hasValue(org.hamcrest.Matcher valueMatcher) + { return org.hamcrest.collection.IsMapContaining.hasValue(valueMatcher); } @@ -1156,11 +1244,12 @@ public static org.hamcrest.Matcher> hasValue(or * at least one value that is equal to the specified value. * For example: *
assertThat(myMap, hasValue("foo"))
- * + * * @param value * the value that satisfying maps must contain */ - public static org.hamcrest.Matcher> hasValue(V value) { + public static org.hamcrest.Matcher> hasValue(V value) + { return org.hamcrest.collection.IsMapContaining.hasValue(value); } @@ -1169,11 +1258,12 @@ public static org.hamcrest.Matcher> hasValue(V * specified collection. * For example: *
assertThat("foo", is(in(Arrays.asList("bar", "foo"))))
- * + * * @param collection * the collection in which matching items must be found */ - public static org.hamcrest.Matcher in(java.util.Collection collection) { + public static org.hamcrest.Matcher in(java.util.Collection collection) + { return org.hamcrest.collection.IsIn.in(collection); } @@ -1182,11 +1272,12 @@ public static org.hamcrest.Matcher in(java.util.Collection collection) * specified array. * For example: *
assertThat("foo", is(in(new String[]{"bar", "foo"})))
- * + * * @param elements * the array in which matching items must be found */ - public static org.hamcrest.Matcher in(T[] elements) { + public static org.hamcrest.Matcher in(T[] elements) + { return org.hamcrest.collection.IsIn.in(elements); } @@ -1195,13 +1286,14 @@ public static org.hamcrest.Matcher in(T[] elements) { * specified collection. * For example: *
assertThat("foo", isIn(Arrays.asList("bar", "foo")))
- * - * @deprecated use is(in(...)) instead + * * @param collection * the collection in which matching items must be found + * @deprecated use is(in(...)) instead */ @SuppressWarnings("deprecation") - public static org.hamcrest.Matcher isIn(java.util.Collection collection) { + public static org.hamcrest.Matcher isIn(java.util.Collection collection) + { return org.hamcrest.collection.IsIn.isIn(collection); } @@ -1210,13 +1302,14 @@ public static org.hamcrest.Matcher isIn(java.util.Collection collectio * specified array. * For example: *
assertThat("foo", isIn(new String[]{"bar", "foo"}))
- * - * @deprecated use is(in(...)) instead + * * @param elements * the array in which matching items must be found + * @deprecated use is(in(...)) instead */ @SuppressWarnings("deprecation") - public static org.hamcrest.Matcher isIn(T[] elements) { + public static org.hamcrest.Matcher isIn(T[] elements) + { return org.hamcrest.collection.IsIn.isIn(elements); } @@ -1225,14 +1318,15 @@ public static org.hamcrest.Matcher isIn(T[] elements) { * specified elements. * For example: *
assertThat("foo", isOneOf("bar", "foo"))
- * - * @deprecated use is(oneOf(...)) instead + * * @param elements * the elements amongst which matching items will be found + * @deprecated use is(oneOf(...)) instead */ @SuppressWarnings("deprecation") @SafeVarargs - public static org.hamcrest.Matcher isOneOf(T... elements) { + public static org.hamcrest.Matcher isOneOf(T... elements) + { return org.hamcrest.collection.IsIn.isOneOf(elements); } @@ -1241,12 +1335,13 @@ public static org.hamcrest.Matcher isOneOf(T... elements) { * specified elements. * For example: *
assertThat("foo", is(oneOf("bar", "foo")))
- * + * * @param elements * the elements amongst which matching items will be found */ @SafeVarargs - public static org.hamcrest.Matcher oneOf(T... elements) { + public static org.hamcrest.Matcher oneOf(T... elements) + { return org.hamcrest.collection.IsIn.oneOf(elements); } @@ -1255,13 +1350,14 @@ public static org.hamcrest.Matcher oneOf(T... elements) { * to the specified operand, within a range of +/- error. * For example: *
assertThat(1.03, is(closeTo(1.0, 0.03)))
- * + * * @param operand * the expected value of matching doubles * @param error * the delta (+/-) within which matches will be allowed */ - public static org.hamcrest.Matcher closeTo(double operand, double error) { + public static org.hamcrest.Matcher closeTo(double operand, double error) + { return org.hamcrest.number.IsCloseTo.closeTo(operand, error); } @@ -1270,7 +1366,8 @@ public static org.hamcrest.Matcher closeTo(double operand, dou * For example: *
assertThat(Double.NaN, is(notANumber()))
*/ - public static org.hamcrest.Matcher notANumber() { + public static org.hamcrest.Matcher notANumber() + { return org.hamcrest.number.IsNaN.notANumber(); } @@ -1280,13 +1377,14 @@ public static org.hamcrest.Matcher notANumber() { * is done by BigDecimals {@link java.math.BigDecimal#compareTo(java.math.BigDecimal)} method. * For example: *
assertThat(new BigDecimal("1.03"), is(closeTo(new BigDecimal("1.0"), new BigDecimal("0.03"))))
- * + * * @param operand * the expected value of matching BigDecimals * @param error * the delta (+/-) within which matches will be allowed */ - public static org.hamcrest.Matcher closeTo(java.math.BigDecimal operand, java.math.BigDecimal error) { + public static org.hamcrest.Matcher closeTo(java.math.BigDecimal operand, java.math.BigDecimal error) + { return org.hamcrest.number.BigDecimalCloseTo.closeTo(operand, error); } @@ -1296,10 +1394,12 @@ public static org.hamcrest.Matcher closeTo(java.math.BigDe * examined object. * For example: *
assertThat(1, comparesEqualTo(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return zero + * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return zero */ - public static > org.hamcrest.Matcher comparesEqualTo(T value) { + public static > org.hamcrest.Matcher comparesEqualTo(T value) + { return org.hamcrest.number.OrderingComparison.comparesEqualTo(value); } @@ -1309,11 +1409,13 @@ public static > org.hamcrest.Matcher compar * examined object. * For example: *
assertThat(2, greaterThan(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return greater - * than zero + * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return greater + * than zero */ - public static > org.hamcrest.Matcher greaterThan(T value) { + public static > org.hamcrest.Matcher greaterThan(T value) + { return org.hamcrest.number.OrderingComparison.greaterThan(value); } @@ -1323,11 +1425,13 @@ public static > org.hamcrest.Matcher greate * of the examined object. * For example: *
assertThat(1, greaterThanOrEqualTo(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return greater - * than or equal to zero + * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return greater + * than or equal to zero */ - public static > org.hamcrest.Matcher greaterThanOrEqualTo(T value) { + public static > org.hamcrest.Matcher greaterThanOrEqualTo(T value) + { return org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo(value); } @@ -1337,11 +1441,13 @@ public static > org.hamcrest.Matcher greate * examined object. * For example: *
assertThat(1, lessThan(2))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return less - * than zero + * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return less + * than zero */ - public static > org.hamcrest.Matcher lessThan(T value) { + public static > org.hamcrest.Matcher lessThan(T value) + { return org.hamcrest.number.OrderingComparison.lessThan(value); } @@ -1351,11 +1457,13 @@ public static > org.hamcrest.Matcher lessTh * of the examined object. * For example: *
assertThat(1, lessThanOrEqualTo(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return less - * than or equal to zero + * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return less + * than or equal to zero */ - public static > org.hamcrest.Matcher lessThanOrEqualTo(T value) { + public static > org.hamcrest.Matcher lessThanOrEqualTo(T value) + { return org.hamcrest.number.OrderingComparison.lessThanOrEqualTo(value); } @@ -1364,20 +1472,22 @@ public static > org.hamcrest.Matcher lessTh * the specified expectedString, ignoring case. * For example: *
assertThat("Foo", equalToIgnoringCase("FOO"))
- * + * * @param expectedString * the expected value of matched strings */ - public static Matcher equalToIgnoringCase(java.lang.String expectedString) { + public static Matcher equalToIgnoringCase(java.lang.String expectedString) + { return org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase(expectedString); } /** - * @deprecated {@link #equalToCompressingWhiteSpace(String)} * @param expectedString * the expected value of matched strings + * @deprecated {@link #equalToCompressingWhiteSpace(String)} */ - public static Matcher equalToIgnoringWhiteSpace(java.lang.String expectedString) { + public static Matcher equalToIgnoringWhiteSpace(java.lang.String expectedString) + { return equalToCompressingWhiteSpace(expectedString); } @@ -1395,7 +1505,8 @@ public static Matcher equalToIgnoringWhiteSpace(java.lang.Stri * @param expectedString * the expected value of matched strings */ - public static Matcher equalToCompressingWhiteSpace(java.lang.String expectedString) { + public static Matcher equalToCompressingWhiteSpace(java.lang.String expectedString) + { return IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace(expectedString); } @@ -1405,7 +1516,8 @@ public static Matcher equalToCompressingWhiteSpace(java.lang.S * For example: *
assertThat(((String)null), is(emptyOrNullString()))
*/ - public static Matcher emptyOrNullString() { + public static Matcher emptyOrNullString() + { return org.hamcrest.text.IsEmptyString.emptyOrNullString(); } @@ -1414,7 +1526,8 @@ public static Matcher emptyOrNullString() { * For example: *
assertThat("", is(emptyString()))
*/ - public static Matcher emptyString() { + public static Matcher emptyString() + { return org.hamcrest.text.IsEmptyString.emptyString(); } @@ -1423,11 +1536,12 @@ public static Matcher emptyString() { * has zero length. * For example: *
assertThat(((String)null), isEmptyOrNullString())
- * + * * @deprecated use is(emptyOrNullString()) instead */ @SuppressWarnings("deprecation") - public static Matcher isEmptyOrNullString() { + public static Matcher isEmptyOrNullString() + { return org.hamcrest.text.IsEmptyString.isEmptyOrNullString(); } @@ -1435,11 +1549,12 @@ public static Matcher isEmptyOrNullString() { * Creates a matcher of {@link String} that matches when the examined string has zero length. * For example: *
assertThat("", isEmptyString())
- * + * * @deprecated use is(emptyString()) instead */ @SuppressWarnings("deprecation") - public static Matcher isEmptyString() { + public static Matcher isEmptyString() + { return org.hamcrest.text.IsEmptyString.isEmptyString(); } @@ -1449,7 +1564,8 @@ public static Matcher isEmptyString() { * For example: *
assertThat(((String)null), is(blankOrNullString()))
*/ - public static Matcher blankOrNullString() { + public static Matcher blankOrNullString() + { return org.hamcrest.text.IsBlankString.blankOrNullString(); } @@ -1459,7 +1575,8 @@ public static Matcher blankOrNullString() { * For example: *
assertThat("  ", is(blankString()))
*/ - public static Matcher blankString() { + public static Matcher blankString() + { return org.hamcrest.text.IsBlankString.blankString(); } @@ -1467,7 +1584,8 @@ public static Matcher blankString() { * Creates a matcher of {@link java.lang.String} that matches when the examined string * exactly matches the given {@link java.util.regex.Pattern}. */ - public static Matcher matchesPattern(java.util.regex.Pattern pattern) { + public static Matcher matchesPattern(java.util.regex.Pattern pattern) + { return org.hamcrest.text.MatchesPattern.matchesPattern(pattern); } @@ -1475,7 +1593,8 @@ public static Matcher matchesPattern(java.util.regex.Pattern p * Creates a matcher of {@link java.lang.String} that matches when the examined string * exactly matches the given regular expression, treated as a {@link java.util.regex.Pattern}. */ - public static Matcher matchesPattern(java.lang.String regex) { + public static Matcher matchesPattern(java.lang.String regex) + { return org.hamcrest.text.MatchesPattern.matchesPattern(regex); } @@ -1485,11 +1604,12 @@ public static Matcher matchesPattern(java.lang.String regex) { * For example: *
assertThat("myfoobarbaz", stringContainsInOrder(Arrays.asList("bar", "foo")))
* fails as "foo" occurs before "bar" in the string "myfoobarbaz" - * + * * @param substrings * the substrings that must be contained within matching strings */ - public static Matcher stringContainsInOrder(java.lang.Iterable substrings) { + public static Matcher stringContainsInOrder(java.lang.Iterable substrings) + { return org.hamcrest.text.StringContainsInOrder.stringContainsInOrder(substrings); } @@ -1499,39 +1619,43 @@ public static Matcher stringContainsInOrder(java.lang.Iterable * For example: *
assertThat("myfoobarbaz", stringContainsInOrder("bar", "foo"))
* fails as "foo" occurs before "bar" in the string "myfoobarbaz" - * + * * @param substrings * the substrings that must be contained within matching strings */ - public static Matcher stringContainsInOrder(java.lang.String... substrings) { + public static Matcher stringContainsInOrder(java.lang.String... substrings) + { return org.hamcrest.text.StringContainsInOrder.stringContainsInOrder(substrings); } - /** - * Creates a matcher of {@link CharSequence} that matches when a char sequence has the length - * of the specified argument. - * For example: - * - *
-     * assertThat("text", length(4))
-     * 
- * - * @param length the expected length of the string - */ - public static Matcher hasLength(int length) { - return org.hamcrest.text.CharSequenceLength.hasLength(length); - } + /** + * Creates a matcher of {@link CharSequence} that matches when a char sequence has the length + * of the specified argument. + * For example: + * + *
+   * assertThat("text", length(4))
+   * 
+ * + * @param length + * the expected length of the string + */ + public static Matcher hasLength(int length) + { + return org.hamcrest.text.CharSequenceLength.hasLength(length); + } /** * Creates a matcher that matches any examined object whose toString method * returns a value that satisfies the specified matcher. * For example: *
assertThat(true, hasToString(equalTo("TRUE")))
- * + * * @param toStringMatcher * the matcher used to verify the toString result */ - public static org.hamcrest.Matcher hasToString(org.hamcrest.Matcher toStringMatcher) { + public static org.hamcrest.Matcher hasToString(org.hamcrest.Matcher toStringMatcher) + { return org.hamcrest.object.HasToString.hasToString(toStringMatcher); } @@ -1540,11 +1664,12 @@ public static org.hamcrest.Matcher hasToString(org.hamcrest.MatcherassertThat(true, hasToString("TRUE")) - * + * * @param expectedToString * the expected toString result */ - public static org.hamcrest.Matcher hasToString(java.lang.String expectedToString) { + public static org.hamcrest.Matcher hasToString(java.lang.String expectedToString) + { return org.hamcrest.object.HasToString.hasToString(expectedToString); } @@ -1553,11 +1678,12 @@ public static org.hamcrest.Matcher hasToString(java.lang.String expectedT * assignable from the examined class. * For example: *
assertThat(Integer.class, typeCompatibleWith(Number.class))
- * + * * @param baseType * the base class to examine classes against */ - public static org.hamcrest.Matcher> typeCompatibleWith(java.lang.Class baseType) { + public static org.hamcrest.Matcher> typeCompatibleWith(java.lang.Class baseType) + { return org.hamcrest.object.IsCompatibleType.typeCompatibleWith(baseType); } @@ -1566,13 +1692,14 @@ public static org.hamcrest.Matcher> typeCompatibleWith(ja * derived from eventClass announced by source. * For example: *
assertThat(myEvent, is(eventFrom(PropertyChangeEvent.class, myBean)))
- * + * * @param eventClass * the class of the event to match on * @param source * the source of the event */ - public static org.hamcrest.Matcher eventFrom(java.lang.Class eventClass, java.lang.Object source) { + public static org.hamcrest.Matcher eventFrom(java.lang.Class eventClass, java.lang.Object source) + { return org.hamcrest.object.IsEventFrom.eventFrom(eventClass, source); } @@ -1581,11 +1708,12 @@ public static org.hamcrest.Matcher eventFrom(java.lang.Cl * announced by source. * For example: *
assertThat(myEvent, is(eventFrom(myBean)))
- * + * * @param source * the source of the event */ - public static org.hamcrest.Matcher eventFrom(java.lang.Object source) { + public static org.hamcrest.Matcher eventFrom(java.lang.Object source) + { return org.hamcrest.object.IsEventFrom.eventFrom(source); } @@ -1594,11 +1722,12 @@ public static org.hamcrest.Matcher eventFrom(java.lang.Ob * with the specified name. * For example: *
assertThat(myBean, hasProperty("foo"))
- * + * * @param propertyName * the name of the JavaBean property that examined beans should possess */ - public static org.hamcrest.Matcher hasProperty(java.lang.String propertyName) { + public static org.hamcrest.Matcher hasProperty(java.lang.String propertyName) + { return org.hamcrest.beans.HasProperty.hasProperty(propertyName); } @@ -1607,13 +1736,14 @@ public static org.hamcrest.Matcher hasProperty(java.lang.String propertyN * with the specified name whose value satisfies the specified matcher. * For example: *
assertThat(myBean, hasProperty("foo", equalTo("bar"))
- * + * * @param propertyName * the name of the JavaBean property that examined beans should possess * @param valueMatcher * a matcher for the value of the specified property of the examined bean */ - public static org.hamcrest.Matcher hasProperty(java.lang.String propertyName, org.hamcrest.Matcher valueMatcher) { + public static org.hamcrest.Matcher hasProperty(java.lang.String propertyName, org.hamcrest.Matcher valueMatcher) + { return org.hamcrest.beans.HasPropertyWithValue.hasProperty(propertyName, valueMatcher); } @@ -1632,7 +1762,8 @@ public static org.hamcrest.Matcher hasProperty(java.lang.String propertyN * @param ignoredProperties * do not check any of these named properties. */ - public static Matcher samePropertyValuesAs(B expectedBean, String... ignoredProperties) { + public static Matcher samePropertyValuesAs(B expectedBean, String... ignoredProperties) + { return org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs(expectedBean, ignoredProperties); } @@ -1641,13 +1772,14 @@ public static Matcher samePropertyValuesAs(B expectedBean, String... igno * specified xPath that satisfies the specified valueMatcher. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar")))
- * + * * @param xPath * the target xpath * @param valueMatcher * matcher for the value at the specified xpath */ - public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, Matcher valueMatcher) { + public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, Matcher valueMatcher) + { return org.hamcrest.xml.HasXPath.hasXPath(xPath, valueMatcher); } @@ -1657,7 +1789,7 @@ public static org.hamcrest.Matcher hasXPath(java.lang.String x * the specified valueMatcher. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs, equalTo("Cheddar")))
- * + * * @param xPath * the target xpath * @param namespaceContext @@ -1665,7 +1797,8 @@ public static org.hamcrest.Matcher hasXPath(java.lang.String x * @param valueMatcher * matcher for the value at the specified xpath */ - public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, javax.xml.namespace.NamespaceContext namespaceContext, Matcher valueMatcher) { + public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, javax.xml.namespace.NamespaceContext namespaceContext, Matcher valueMatcher) + { return org.hamcrest.xml.HasXPath.hasXPath(xPath, namespaceContext, valueMatcher); } @@ -1674,11 +1807,12 @@ public static org.hamcrest.Matcher hasXPath(java.lang.String x * at the specified xPath, with any content. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese"))
- * + * * @param xPath * the target xpath */ - public static org.hamcrest.Matcher hasXPath(java.lang.String xPath) { + public static org.hamcrest.Matcher hasXPath(java.lang.String xPath) + { return org.hamcrest.xml.HasXPath.hasXPath(xPath); } @@ -1687,13 +1821,14 @@ public static org.hamcrest.Matcher hasXPath(java.lang.String x * at the specified xPath within the specified namespace context, with any content. * For example: *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs))
- * + * * @param xPath * the target xpath * @param namespaceContext * the namespace for matching nodes */ - public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, javax.xml.namespace.NamespaceContext namespaceContext) { + public static org.hamcrest.Matcher hasXPath(java.lang.String xPath, javax.xml.namespace.NamespaceContext namespaceContext) + { return org.hamcrest.xml.HasXPath.hasXPath(xPath, namespaceContext); } diff --git a/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java b/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java index 06b361d2..7b5dad96 100644 --- a/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java +++ b/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java @@ -3,14 +3,15 @@ /** * The ability of an object to describe itself. */ -public interface SelfDescribing { - /** - * Generates a description of the object. The description may be part of a - * a description of a larger object of which this is just a component, so it - * should be worded appropriately. - * - * @param description - * The description to be built or appended to. - */ - void describeTo(Description description); +public interface SelfDescribing +{ + /** + * Generates a description of the object. The description may be part of a + * a description of a larger object of which this is just a component, so it + * should be worded appropriately. + * + * @param description + * The description to be built or appended to. + */ + void describeTo(Description description); } \ No newline at end of file diff --git a/hamcrest/src/main/java/org/hamcrest/StringDescription.java b/hamcrest/src/main/java/org/hamcrest/StringDescription.java index 813c1782..97238b4c 100644 --- a/hamcrest/src/main/java/org/hamcrest/StringDescription.java +++ b/hamcrest/src/main/java/org/hamcrest/StringDescription.java @@ -5,59 +5,72 @@ /** * A {@link Description} that is stored as a string. */ -public class StringDescription extends BaseDescription { - private final Appendable out; +public class StringDescription extends BaseDescription +{ + private final Appendable out; - public StringDescription() { - this(new StringBuilder()); - } + public StringDescription() + { + this(new StringBuilder()); + } - public StringDescription(Appendable out) { - this.out = out; - } - - /** - * Return the description of a {@link SelfDescribing} object as a String. - * - * @param selfDescribing - * The object to be described. - * @return - * The description of the object. - */ - public static String toString(SelfDescribing selfDescribing) { - return new StringDescription().appendDescriptionOf(selfDescribing).toString(); - } + public StringDescription(Appendable out) + { + this.out = out; + } - /** - * Alias for {@link #toString(SelfDescribing)}. - */ - public static String asString(SelfDescribing selfDescribing) { - return toString(selfDescribing); - } + /** + * Return the description of a {@link SelfDescribing} object as a String. + * + * @param selfDescribing + * The object to be described. + * @return The description of the object. + */ + public static String toString(SelfDescribing selfDescribing) + { + return new StringDescription().appendDescriptionOf(selfDescribing).toString(); + } - @Override - protected void append(String str) { - try { - out.append(str); - } catch (IOException e) { - throw new RuntimeException("Could not write description", e); - } + /** + * Alias for {@link #toString(SelfDescribing)}. + */ + public static String asString(SelfDescribing selfDescribing) + { + return toString(selfDescribing); + } + + @Override + protected void append(String str) + { + try + { + out.append(str); + } + catch (IOException e) + { + throw new RuntimeException("Could not write description", e); } + } - @Override - protected void append(char c) { - try { - out.append(c); - } catch (IOException e) { - throw new RuntimeException("Could not write description", e); - } + @Override + protected void append(char c) + { + try + { + out.append(c); } - - /** - * Returns the description as a string. - */ - @Override - public String toString() { - return out.toString(); + catch (IOException e) + { + throw new RuntimeException("Could not write description", e); } + } + + /** + * Returns the description as a string. + */ + @Override + public String toString() + { + return out.toString(); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java b/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java index 03efa9db..232f5ec8 100644 --- a/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java @@ -6,69 +6,83 @@ /** * Convenient base class for Matchers that require a non-null value of a specific type * and that will report why the received value has been rejected. - * This implements the null check, checks the type and then casts. - * To use, implement
matchesSafely()
. + * This implements the null check, checks the type and then casts. + * To use, implement
matchesSafely()
. * - * @param * @author Neil Dunn * @author Nat Pryce * @author Steve Freeman */ -public abstract class TypeSafeDiagnosingMatcher extends BaseMatcher { - private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 2, 0); - private final Class expectedType; +public abstract class TypeSafeDiagnosingMatcher extends BaseMatcher +{ + private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 2, 0); + private final Class expectedType; - /** - * Subclasses should implement this. The item will already have been checked - * for the specific type and will never be null. - */ - protected abstract boolean matchesSafely(T item, Description mismatchDescription); + /** + * Subclasses should implement this. The item will already have been checked + * for the specific type and will never be null. + */ + protected abstract boolean matchesSafely(T item, Description mismatchDescription); - /** - * Use this constructor if the subclass that implements matchesSafely - * is not the class that binds <T> to a type. - * @param expectedType The expectedType of the actual value. - */ - protected TypeSafeDiagnosingMatcher(Class expectedType) { - this.expectedType = expectedType; - } + /** + * Use this constructor if the subclass that implements matchesSafely + * is not the class that binds <T> to a type. + * + * @param expectedType + * The expectedType of the actual value. + */ + protected TypeSafeDiagnosingMatcher(Class expectedType) + { + this.expectedType = expectedType; + } - /** - * Use this constructor if the subclass that implements matchesSafely - * is not the class that binds <T> to a type. - * @param typeFinder A type finder to extract the type - */ - protected TypeSafeDiagnosingMatcher(ReflectiveTypeFinder typeFinder) { - this.expectedType = typeFinder.findExpectedType(getClass()); - } + /** + * Use this constructor if the subclass that implements matchesSafely + * is not the class that binds <T> to a type. + * + * @param typeFinder + * A type finder to extract the type + */ + protected TypeSafeDiagnosingMatcher(ReflectiveTypeFinder typeFinder) + { + this.expectedType = typeFinder.findExpectedType(getClass()); + } - /** - * The default constructor for simple sub types - */ - protected TypeSafeDiagnosingMatcher() { - this(TYPE_FINDER); - } + /** + * The default constructor for simple sub types + */ + protected TypeSafeDiagnosingMatcher() + { + this(TYPE_FINDER); + } - @Override - @SuppressWarnings("unchecked") - public final boolean matches(Object item) { - return item != null + @Override + @SuppressWarnings("unchecked") + public final boolean matches(Object item) + { + return item != null && expectedType.isInstance(item) && matchesSafely((T) item, new Description.NullDescription()); - } + } - @SuppressWarnings("unchecked") - @Override - public final void describeMismatch(Object item, Description mismatchDescription) { - if (item == null) { - mismatchDescription.appendText("was null"); - } else if (!expectedType.isInstance(item)) { + @SuppressWarnings("unchecked") + @Override + public final void describeMismatch(Object item, Description mismatchDescription) + { + if (item == null) + { + mismatchDescription.appendText("was null"); + } + else if (!expectedType.isInstance(item)) + { mismatchDescription.appendText("was ") - .appendText(item.getClass().getSimpleName()) - .appendText(" ") - .appendValue(item); - } else { - matchesSafely((T) item, mismatchDescription); - } + .appendText(item.getClass().getSimpleName()) + .appendText(" ") + .appendValue(item); + } + else + { + matchesSafely((T) item, mismatchDescription); } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java b/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java index 08dfce8b..6d304be1 100644 --- a/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java @@ -10,76 +10,91 @@ * @author Steve Freeman * @author Nat Pryce */ -public abstract class TypeSafeMatcher extends BaseMatcher { - private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 1, 0); - - final private Class expectedType; +public abstract class TypeSafeMatcher extends BaseMatcher +{ + private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 1, 0); - /** - * The default constructor for simple sub types - */ - protected TypeSafeMatcher() { - this(TYPE_FINDER); - } - - /** - * Use this constructor if the subclass that implements matchesSafely - * is not the class that binds <T> to a type. - * @param expectedType The expectedType of the actual value. - */ - protected TypeSafeMatcher(Class expectedType) { - this.expectedType = expectedType; - } - - /** - * Use this constructor if the subclass that implements matchesSafely - * is not the class that binds <T> to a type. - * @param typeFinder A type finder to extract the type - */ - protected TypeSafeMatcher(ReflectiveTypeFinder typeFinder) { - this.expectedType = typeFinder.findExpectedType(getClass()); - } - - /** - * Subclasses should implement this. The item will already have been checked for - * the specific type and will never be null. - */ - protected abstract boolean matchesSafely(T item); - - /** - * Subclasses should override this. The item will already have been checked for - * the specific type and will never be null. - */ - protected void describeMismatchSafely(T item, Description mismatchDescription) { - super.describeMismatch(item, mismatchDescription); + final private Class expectedType; + + /** + * The default constructor for simple sub types + */ + protected TypeSafeMatcher() + { + this(TYPE_FINDER); + } + + /** + * Use this constructor if the subclass that implements matchesSafely + * is not the class that binds <T> to a type. + * + * @param expectedType + * The expectedType of the actual value. + */ + protected TypeSafeMatcher(Class expectedType) + { + this.expectedType = expectedType; + } + + /** + * Use this constructor if the subclass that implements matchesSafely + * is not the class that binds <T> to a type. + * + * @param typeFinder + * A type finder to extract the type + */ + protected TypeSafeMatcher(ReflectiveTypeFinder typeFinder) + { + this.expectedType = typeFinder.findExpectedType(getClass()); + } + + /** + * Subclasses should implement this. The item will already have been checked for + * the specific type and will never be null. + */ + protected abstract boolean matchesSafely(T item); + + /** + * Subclasses should override this. The item will already have been checked for + * the specific type and will never be null. + */ + protected void describeMismatchSafely(T item, Description mismatchDescription) + { + super.describeMismatch(item, mismatchDescription); + } + + /** + * Methods made final to prevent accidental override. + * If you need to override this, there's no point on extending TypeSafeMatcher. + * Instead, extend the {@link BaseMatcher}. + */ + @Override + @SuppressWarnings({ "unchecked" }) + public final boolean matches(Object item) + { + return item != null + && expectedType.isInstance(item) + && matchesSafely((T) item); + } + + @SuppressWarnings("unchecked") + @Override final public void describeMismatch(Object item, Description description) + { + if (item == null) + { + super.describeMismatch(null, description); } - - /** - * Methods made final to prevent accidental override. - * If you need to override this, there's no point on extending TypeSafeMatcher. - * Instead, extend the {@link BaseMatcher}. - */ - @Override - @SuppressWarnings({"unchecked"}) - public final boolean matches(Object item) { - return item != null - && expectedType.isInstance(item) - && matchesSafely((T) item); + else if (!expectedType.isInstance(item)) + { + description.appendText("was a ") + .appendText(item.getClass().getName()) + .appendText(" (") + .appendValue(item) + .appendText(")"); } - - @SuppressWarnings("unchecked") - @Override - final public void describeMismatch(Object item, Description description) { - if (item == null) { - super.describeMismatch(null, description); - } else if (! expectedType.isInstance(item)) { - description.appendText("was a ") - .appendText(item.getClass().getName()) - .appendText(" (") - .appendValue(item) - .appendText(")"); - } else { - describeMismatchSafely((T)item, description); - } + else + { + describeMismatchSafely((T) item, description); } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java b/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java index 320a49ef..4b0c4cd0 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java @@ -13,44 +13,53 @@ * @author Nat Pryce * @author Steve Freeman */ -public class HasProperty extends TypeSafeMatcher { +public class HasProperty extends TypeSafeMatcher +{ - private final String propertyName; + private final String propertyName; - public HasProperty(String propertyName) { - this.propertyName = propertyName; - } + public HasProperty(String propertyName) + { + this.propertyName = propertyName; + } - @Override - public boolean matchesSafely(T obj) { - try { - return PropertyUtil.getPropertyDescriptor(propertyName, obj) != null; - } catch (IllegalArgumentException e) { - return false; - } + @Override + public boolean matchesSafely(T obj) + { + try + { + return PropertyUtil.getPropertyDescriptor(propertyName, obj) != null; } - - @Override - public void describeMismatchSafely(T item, Description mismatchDescription) { - mismatchDescription.appendText("no ").appendValue(propertyName).appendText(" in ").appendValue(item); + catch (IllegalArgumentException e) + { + return false; } + } - @Override - public void describeTo(Description description) { - description.appendText("hasProperty(").appendValue(propertyName).appendText(")"); - } + @Override + public void describeMismatchSafely(T item, Description mismatchDescription) + { + mismatchDescription.appendText("no ").appendValue(propertyName).appendText(" in ").appendValue(item); + } - /** - * Creates a matcher that matches when the examined object has a JavaBean property - * with the specified name. - * For example: - *
assertThat(myBean, hasProperty("foo"))
- * - * @param propertyName - * the name of the JavaBean property that examined beans should possess - */ - public static Matcher hasProperty(String propertyName) { - return new HasProperty(propertyName); - } + @Override + public void describeTo(Description description) + { + description.appendText("hasProperty(").appendValue(propertyName).appendText(")"); + } + + /** + * Creates a matcher that matches when the examined object has a JavaBean property + * with the specified name. + * For example: + *
assertThat(myBean, hasProperty("foo"))
+ * + * @param propertyName + * the name of the JavaBean property that examined beans should possess + */ + public static Matcher hasProperty(String propertyName) + { + return new HasProperty(propertyName); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/beans/HasPropertyWithValue.java b/hamcrest/src/main/java/org/hamcrest/beans/HasPropertyWithValue.java index 29b299b8..74c04091 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/HasPropertyWithValue.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/HasPropertyWithValue.java @@ -37,7 +37,7 @@ * return name; * } * } - * + *

* And that these person objects are generated within a piece of code under test * (a class named PersonGenerator). This object is sent to one of our mock objects * which overrides the PersonGenerationListener interface: @@ -45,14 +45,14 @@ * public interface PersonGenerationListener { * public void personGenerated(Person person); * } - * + *

* In order to check that the code under test generates a person with name * "Iain" we would do the following: *

  * Mock personGenListenerMock = mock(PersonGenerationListener.class);
  * personGenListenerMock.expects(once()).method("personGenerated").with(and(isA(Person.class), hasProperty("Name", eq("Iain")));
  * PersonGenerationListener listener = (PersonGenerationListener)personGenListenerMock.proxy();
- * + * *

If an exception is thrown by the getter method for a property, the property * does not exist, is not readable, or a reflection related exception is thrown * when trying to invoke it then this is treated as an evaluation failure and @@ -69,124 +69,147 @@ * @author Steve Freeman * @author cristcost at github */ -public class HasPropertyWithValue extends TypeSafeDiagnosingMatcher { - private static final Condition.Step WITH_READ_METHOD = withReadMethod(); - private final String propertyName; - private final Matcher valueMatcher; - private final String messageFormat; - - public HasPropertyWithValue(String propertyName, Matcher valueMatcher) { - this(propertyName, valueMatcher, " property '%s' "); - } - - public HasPropertyWithValue(String propertyName, Matcher valueMatcher, String messageFormat) { - this.propertyName = propertyName; - this.valueMatcher = nastyGenericsWorkaround(valueMatcher); - this.messageFormat = messageFormat; +public class HasPropertyWithValue extends TypeSafeDiagnosingMatcher +{ + private static final Condition.Step WITH_READ_METHOD = withReadMethod(); + private final String propertyName; + private final Matcher valueMatcher; + private final String messageFormat; + + public HasPropertyWithValue(String propertyName, Matcher valueMatcher) + { + this(propertyName, valueMatcher, " property '%s' "); + } + + public HasPropertyWithValue(String propertyName, Matcher valueMatcher, String messageFormat) + { + this.propertyName = propertyName; + this.valueMatcher = nastyGenericsWorkaround(valueMatcher); + this.messageFormat = messageFormat; + } + + @Override + public boolean matchesSafely(T bean, Description mismatch) + { + return propertyOn(bean, mismatch) + .and(WITH_READ_METHOD) + .and(withPropertyValue(bean)) + .matching(valueMatcher, String.format(messageFormat, propertyName)); + } + + @Override + public void describeTo(Description description) + { + description.appendText("hasProperty(").appendValue(propertyName).appendText(", ") + .appendDescriptionOf(valueMatcher).appendText(")"); + } + + private Condition propertyOn(T bean, Description mismatch) + { + PropertyDescriptor property = PropertyUtil.getPropertyDescriptor(propertyName, bean); + if (property == null) + { + mismatch.appendText("No property \"" + propertyName + "\""); + return notMatched(); } - @Override - public boolean matchesSafely(T bean, Description mismatch) { - return propertyOn(bean, mismatch) - .and(WITH_READ_METHOD) - .and(withPropertyValue(bean)) - .matching(valueMatcher, String.format(messageFormat, propertyName)); - } - - @Override - public void describeTo(Description description) { - description.appendText("hasProperty(").appendValue(propertyName).appendText(", ") - .appendDescriptionOf(valueMatcher).appendText(")"); - } - - private Condition propertyOn(T bean, Description mismatch) { - PropertyDescriptor property = PropertyUtil.getPropertyDescriptor(propertyName, bean); - if (property == null) { - mismatch.appendText("No property \"" + propertyName + "\""); - return notMatched(); + return matched(property, mismatch); + } + + private Condition.Step withPropertyValue(final T bean) + { + return new Condition.Step() + { + @Override + public Condition apply(Method readMethod, Description mismatch) + { + try + { + return matched(readMethod.invoke(bean, NO_ARGUMENTS), mismatch); } - - return matched(property, mismatch); - } - - private Condition.Step withPropertyValue(final T bean) { - return new Condition.Step() { - @Override - public Condition apply(Method readMethod, Description mismatch) { - try { - return matched(readMethod.invoke(bean, NO_ARGUMENTS), mismatch); - } catch (InvocationTargetException e) { - mismatch - .appendText("Calling '") - .appendText(readMethod.toString()) - .appendText("': ") - .appendValue(e.getTargetException().getMessage()); - return notMatched(); - } catch (Exception e) { - throw new IllegalStateException( - "Calling: '" + readMethod + "' should not have thrown " + e); - } - } - }; - } - - @SuppressWarnings("unchecked") - private static Matcher nastyGenericsWorkaround(Matcher valueMatcher) { - return (Matcher) valueMatcher; - } - - private static Condition.Step withReadMethod() { - return new Condition.Step() { - @Override - public Condition apply(PropertyDescriptor property, Description mismatch) { - final Method readMethod = property.getReadMethod(); - if (null == readMethod) { - mismatch.appendText("property \"" + property.getName() + "\" is not readable"); - return notMatched(); - } - return matched(readMethod, mismatch); - } - }; - } - - /** - * Creates a matcher that matches when the examined object has a JavaBean property - * with the specified name whose value satisfies the specified matcher. - * For example: - *
assertThat(myBean, hasProperty("foo", equalTo("bar"))
- * - * @param propertyName - * the name of the JavaBean property that examined beans should possess - * @param valueMatcher - * a matcher for the value of the specified property of the examined bean - */ - public static Matcher hasProperty(String propertyName, Matcher valueMatcher) { - return new HasPropertyWithValue<>(propertyName, valueMatcher); - } - - /** - * Creates a matcher that matches when the examined object is a graph of - * JavaBean objects that can be navigated along the declared dot-separated path - * and the final element of that path is a JavaBean property whose value satisfies the - * specified matcher. - * For example: - *
assertThat(myBean, hasProperty("foo.bar.baz", equalTo("a property value"))
- * - * @param path - * the dot-separated path from the examined object to the JavaBean property - * @param valueMatcher - * a matcher for the value of the specified property of the examined bean - */ - public static Matcher hasPropertyAtPath(String path, Matcher valueMatcher) { - List properties = Arrays.asList(path.split("\\.")); - ListIterator iterator = - properties.listIterator(properties.size()); - - Matcher ret = valueMatcher; - while (iterator.hasPrevious()) { - ret = new HasPropertyWithValue<>(iterator.previous(), ret, "%s."); - } - return ret; + catch (InvocationTargetException e) + { + mismatch + .appendText("Calling '") + .appendText(readMethod.toString()) + .appendText("': ") + .appendValue(e.getTargetException().getMessage()); + return notMatched(); + } + catch (Exception e) + { + throw new IllegalStateException( + "Calling: '" + readMethod + "' should not have thrown " + e); + } + } + }; + } + + @SuppressWarnings("unchecked") + private static Matcher nastyGenericsWorkaround(Matcher valueMatcher) + { + return (Matcher) valueMatcher; + } + + private static Condition.Step withReadMethod() + { + return new Condition.Step() + { + @Override + public Condition apply(PropertyDescriptor property, Description mismatch) + { + final Method readMethod = property.getReadMethod(); + if (null == readMethod) + { + mismatch.appendText("property \"" + property.getName() + "\" is not readable"); + return notMatched(); + } + return matched(readMethod, mismatch); + } + }; + } + + /** + * Creates a matcher that matches when the examined object has a JavaBean property + * with the specified name whose value satisfies the specified matcher. + * For example: + *
assertThat(myBean, hasProperty("foo", equalTo("bar"))
+ * + * @param propertyName + * the name of the JavaBean property that examined beans should possess + * @param valueMatcher + * a matcher for the value of the specified property of the examined bean + */ + public static Matcher hasProperty(String propertyName, Matcher valueMatcher) + { + return new HasPropertyWithValue<>(propertyName, valueMatcher); + } + + /** + * Creates a matcher that matches when the examined object is a graph of + * JavaBean objects that can be navigated along the declared dot-separated path + * and the final element of that path is a JavaBean property whose value satisfies the + * specified matcher. + * For example: + *
assertThat(myBean, hasProperty("foo.bar.baz", equalTo("a property value"))
+ * + * @param path + * the dot-separated path from the examined object to the JavaBean property + * @param valueMatcher + * a matcher for the value of the specified property of the examined bean + */ + public static Matcher hasPropertyAtPath(String path, Matcher valueMatcher) + { + List properties = Arrays.asList(path.split("\\.")); + ListIterator iterator = + properties.listIterator(properties.size()); + + Matcher ret = valueMatcher; + while (iterator.hasPrevious()) + { + ret = new HasPropertyWithValue<>(iterator.previous(), ret, "%s."); } + return ret; + } } diff --git a/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java b/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java index 946c4f84..475c4d21 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java @@ -13,39 +13,51 @@ * @author Steve Freeman * @since 1.1.0 */ -public class PropertyUtil { - /** - * Returns the description of the property with the provided - * name on the provided object's interface. - * - * @return the descriptor of the property, or null if the property does not exist. - * @throws IllegalArgumentException if there's a introspection failure - */ - public static PropertyDescriptor getPropertyDescriptor(String propertyName, Object fromObj) throws IllegalArgumentException { - for (PropertyDescriptor property : propertyDescriptorsFor(fromObj, null)) { - if (property.getName().equals(propertyName)) { - return property; - } - } - - return null; +public class PropertyUtil +{ + /** + * Returns the description of the property with the provided + * name on the provided object's interface. + * + * @return the descriptor of the property, or null if the property does not exist. + * @throws IllegalArgumentException + * if there's a introspection failure + */ + public static PropertyDescriptor getPropertyDescriptor(String propertyName, Object fromObj) throws IllegalArgumentException + { + for (PropertyDescriptor property : propertyDescriptorsFor(fromObj, null)) + { + if (property.getName().equals(propertyName)) + { + return property; + } } - /** - * Returns all the property descriptors for the class associated with the given object - * - * @param fromObj Use the class of this object - * @param stopClass Don't include any properties from this ancestor class upwards. - * @return Property descriptors - * @throws IllegalArgumentException if there's a introspection failure - */ - public static PropertyDescriptor[] propertyDescriptorsFor(Object fromObj, Class stopClass) throws IllegalArgumentException { - try { - return Introspector.getBeanInfo(fromObj.getClass(), stopClass).getPropertyDescriptors(); - } catch (IntrospectionException e) { - throw new IllegalArgumentException("Could not get property descriptors for " + fromObj.getClass(), e); - } + return null; + } + + /** + * Returns all the property descriptors for the class associated with the given object + * + * @param fromObj + * Use the class of this object + * @param stopClass + * Don't include any properties from this ancestor class upwards. + * @return Property descriptors + * @throws IllegalArgumentException + * if there's a introspection failure + */ + public static PropertyDescriptor[] propertyDescriptorsFor(Object fromObj, Class stopClass) throws IllegalArgumentException + { + try + { + return Introspector.getBeanInfo(fromObj.getClass(), stopClass).getPropertyDescriptors(); + } + catch (IntrospectionException e) + { + throw new IllegalArgumentException("Could not get property descriptors for " + fromObj.getClass(), e); } + } - public static final Object[] NO_ARGUMENTS = new Object[0]; + public static final Object[] NO_ARGUMENTS = new Object[0]; } diff --git a/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java b/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java index 4799aeaa..30e23500 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java @@ -13,147 +13,176 @@ import static org.hamcrest.beans.PropertyUtil.propertyDescriptorsFor; import static org.hamcrest.core.IsEqual.equalTo; -public class SamePropertyValuesAs extends DiagnosingMatcher { - private final T expectedBean; - private final Set propertyNames; - private final List propertyMatchers; - private final List ignoredFields; - - @SuppressWarnings("WeakerAccess") - public SamePropertyValuesAs(T expectedBean, List ignoredProperties) { - PropertyDescriptor[] descriptors = propertyDescriptorsFor(expectedBean, Object.class); - this.expectedBean = expectedBean; - this.ignoredFields = ignoredProperties; - this.propertyNames = propertyNamesFrom(descriptors, ignoredProperties); - this.propertyMatchers = propertyMatchersFor(expectedBean, descriptors, ignoredProperties); +public class SamePropertyValuesAs extends DiagnosingMatcher +{ + private final T expectedBean; + private final Set propertyNames; + private final List propertyMatchers; + private final List ignoredFields; + + @SuppressWarnings("WeakerAccess") + public SamePropertyValuesAs(T expectedBean, List ignoredProperties) + { + PropertyDescriptor[] descriptors = propertyDescriptorsFor(expectedBean, Object.class); + this.expectedBean = expectedBean; + this.ignoredFields = ignoredProperties; + this.propertyNames = propertyNamesFrom(descriptors, ignoredProperties); + this.propertyMatchers = propertyMatchersFor(expectedBean, descriptors, ignoredProperties); + } + + @Override + protected boolean matches(Object actual, Description mismatch) + { + return isNotNull(actual, mismatch) + && isCompatibleType(actual, mismatch) + && hasNoExtraProperties(actual, mismatch) + && hasMatchingValues(actual, mismatch); + } + + @Override + public void describeTo(Description description) + { + description.appendText("same property values as " + expectedBean.getClass().getSimpleName()) + .appendList(" [", ", ", "]", propertyMatchers); + if (!ignoredFields.isEmpty()) + { + description.appendText(" ignoring ") + .appendValueList("[", ", ", "]", ignoredFields); } + } - @Override - protected boolean matches(Object actual, Description mismatch) { - return isNotNull(actual, mismatch) - && isCompatibleType(actual, mismatch) - && hasNoExtraProperties(actual, mismatch) - && hasMatchingValues(actual, mismatch); - } - @Override - public void describeTo(Description description) { - description.appendText("same property values as " + expectedBean.getClass().getSimpleName()) - .appendList(" [", ", ", "]", propertyMatchers); - if (! ignoredFields.isEmpty()) { - description.appendText(" ignoring ") - .appendValueList("[", ", ", "]", ignoredFields); - } + private boolean isCompatibleType(Object actual, Description mismatchDescription) + { + if (expectedBean.getClass().isAssignableFrom(actual.getClass())) + { + return true; } - - private boolean isCompatibleType(Object actual, Description mismatchDescription) { - if (expectedBean.getClass().isAssignableFrom(actual.getClass())) { - return true; - } - - mismatchDescription.appendText("is incompatible type: " + actual.getClass().getSimpleName()); + mismatchDescription.appendText("is incompatible type: " + actual.getClass().getSimpleName()); + return false; + } + + private boolean hasNoExtraProperties(Object actual, Description mismatchDescription) + { + Set actualPropertyNames = propertyNamesFrom(propertyDescriptorsFor(actual, Object.class), ignoredFields); + actualPropertyNames.removeAll(propertyNames); + if (!actualPropertyNames.isEmpty()) + { + mismatchDescription.appendText("has extra properties called " + actualPropertyNames); + return false; + } + return true; + } + + private boolean hasMatchingValues(Object actual, Description mismatchDescription) + { + for (PropertyMatcher propertyMatcher : propertyMatchers) + { + if (!propertyMatcher.matches(actual)) + { + propertyMatcher.describeMismatch(actual, mismatchDescription); return false; + } } - - private boolean hasNoExtraProperties(Object actual, Description mismatchDescription) { - Set actualPropertyNames = propertyNamesFrom(propertyDescriptorsFor(actual, Object.class), ignoredFields); - actualPropertyNames.removeAll(propertyNames); - if (!actualPropertyNames.isEmpty()) { - mismatchDescription.appendText("has extra properties called " + actualPropertyNames); - return false; - } - return true; + return true; + } + + private static List propertyMatchersFor(T bean, PropertyDescriptor[] descriptors, List ignoredFields) + { + List result = new ArrayList<>(descriptors.length); + for (PropertyDescriptor propertyDescriptor : descriptors) + { + if (isIgnored(ignoredFields, propertyDescriptor)) + { + result.add(new PropertyMatcher(propertyDescriptor, bean)); + } } - - private boolean hasMatchingValues(Object actual, Description mismatchDescription) { - for (PropertyMatcher propertyMatcher : propertyMatchers) { - if (!propertyMatcher.matches(actual)) { - propertyMatcher.describeMismatch(actual, mismatchDescription); - return false; - } - } - return true; + return result; + } + + private static Set propertyNamesFrom(PropertyDescriptor[] descriptors, List ignoredFields) + { + HashSet result = new HashSet<>(); + for (PropertyDescriptor propertyDescriptor : descriptors) + { + if (isIgnored(ignoredFields, propertyDescriptor)) + { + result.add(propertyDescriptor.getDisplayName()); + } } - - private static List propertyMatchersFor(T bean, PropertyDescriptor[] descriptors, List ignoredFields) { - List result = new ArrayList<>(descriptors.length); - for (PropertyDescriptor propertyDescriptor : descriptors) { - if (isIgnored(ignoredFields, propertyDescriptor)) { - result.add(new PropertyMatcher(propertyDescriptor, bean)); - } - } - return result; - } - - private static Set propertyNamesFrom(PropertyDescriptor[] descriptors, List ignoredFields) { - HashSet result = new HashSet<>(); - for (PropertyDescriptor propertyDescriptor : descriptors) { - if (isIgnored(ignoredFields, propertyDescriptor)) { - result.add(propertyDescriptor.getDisplayName()); - } - } - return result; + return result; + } + + private static boolean isIgnored(List ignoredFields, PropertyDescriptor propertyDescriptor) + { + return !ignoredFields.contains(propertyDescriptor.getDisplayName()); + } + + @SuppressWarnings("WeakerAccess") + private static class PropertyMatcher extends DiagnosingMatcher + { + private final Method readMethod; + private final Matcher matcher; + private final String propertyName; + + public PropertyMatcher(PropertyDescriptor descriptor, Object expectedObject) + { + this.propertyName = descriptor.getDisplayName(); + this.readMethod = descriptor.getReadMethod(); + this.matcher = equalTo(readProperty(readMethod, expectedObject)); } - private static boolean isIgnored(List ignoredFields, PropertyDescriptor propertyDescriptor) { - return ! ignoredFields.contains(propertyDescriptor.getDisplayName()); + @Override + public boolean matches(Object actual, Description mismatch) + { + final Object actualValue = readProperty(readMethod, actual); + if (!matcher.matches(actualValue)) + { + mismatch.appendText(propertyName + " "); + matcher.describeMismatch(actualValue, mismatch); + return false; + } + return true; } - @SuppressWarnings("WeakerAccess") - private static class PropertyMatcher extends DiagnosingMatcher { - private final Method readMethod; - private final Matcher matcher; - private final String propertyName; - - public PropertyMatcher(PropertyDescriptor descriptor, Object expectedObject) { - this.propertyName = descriptor.getDisplayName(); - this.readMethod = descriptor.getReadMethod(); - this.matcher = equalTo(readProperty(readMethod, expectedObject)); - } - - @Override - public boolean matches(Object actual, Description mismatch) { - final Object actualValue = readProperty(readMethod, actual); - if (!matcher.matches(actualValue)) { - mismatch.appendText(propertyName + " "); - matcher.describeMismatch(actualValue, mismatch); - return false; - } - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(propertyName + ": ").appendDescriptionOf(matcher); - } + @Override + public void describeTo(Description description) + { + description.appendText(propertyName + ": ").appendDescriptionOf(matcher); } + } - private static Object readProperty(Method method, Object target) { - try { - return method.invoke(target, NO_ARGUMENTS); - } catch (Exception e) { - throw new IllegalArgumentException("Could not invoke " + method + " on " + target, e); - } + private static Object readProperty(Method method, Object target) + { + try + { + return method.invoke(target, NO_ARGUMENTS); } - - /** - * Creates a matcher that matches when the examined object has values for all of - * its JavaBean properties that are equal to the corresponding values of the - * specified bean. If any properties are marked as ignored, they will be dropped from - * both the expected and actual bean. Note that the ignored properties use JavaBean - * display names, for example
age
rather than method names such as
getAge
. - * For example: - *
assertThat(myBean, samePropertyValuesAs(myExpectedBean))
- *
assertThat(myBean, samePropertyValuesAs(myExpectedBean), "age", "height")
- * - * @param expectedBean - * the bean against which examined beans are compared - * @param ignoredProperties - * do not check any of these named properties. - */ - public static Matcher samePropertyValuesAs(B expectedBean, String... ignoredProperties) { - return new SamePropertyValuesAs<>(expectedBean, asList(ignoredProperties)); + catch (Exception e) + { + throw new IllegalArgumentException("Could not invoke " + method + " on " + target, e); } + } + + /** + * Creates a matcher that matches when the examined object has values for all of + * its JavaBean properties that are equal to the corresponding values of the + * specified bean. If any properties are marked as ignored, they will be dropped from + * both the expected and actual bean. Note that the ignored properties use JavaBean + * display names, for example
age
rather than method names such as
getAge
. + * For example: + *
assertThat(myBean, samePropertyValuesAs(myExpectedBean))
+ *
assertThat(myBean, samePropertyValuesAs(myExpectedBean), "age", "height")
+ * + * @param expectedBean + * the bean against which examined beans are compared + * @param ignoredProperties + * do not check any of these named properties. + */ + public static Matcher samePropertyValuesAs(B expectedBean, String... ignoredProperties) + { + return new SamePropertyValuesAs<>(expectedBean, asList(ignoredProperties)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java b/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java index a841a2c9..b7d02989 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java @@ -12,15 +12,16 @@ /** * @author Steve Freeman 2016 http://www.hamcrest.com */ -public class ArrayAsIterableMatcher extends TypeSafeMatcher { +public class ArrayAsIterableMatcher extends TypeSafeMatcher +{ protected final TypeSafeDiagnosingMatcher> iterableMatcher; private final String message; protected final Collection> matchers; public ArrayAsIterableMatcher( - TypeSafeDiagnosingMatcher> iterableMatcher, - Collection> matchers, - String message) + TypeSafeDiagnosingMatcher> iterableMatcher, + Collection> matchers, + String message) { this.matchers = matchers; this.iterableMatcher = iterableMatcher; @@ -28,18 +29,21 @@ public ArrayAsIterableMatcher( } @Override - public boolean matchesSafely(E[] item) { - return iterableMatcher.matches(asList(item)); + public boolean matchesSafely(E[] item) + { + return iterableMatcher.matches(asList(item)); } @Override - public void describeMismatchSafely(E[] item, Description mismatchDescription) { + public void describeMismatchSafely(E[] item, Description mismatchDescription) + { iterableMatcher.describeMismatch(asList(item), mismatchDescription); } @Override - public void describeTo(Description description) { - description.appendList("[", ", ", "]", matchers) - .appendText(" ").appendText(message); + public void describeTo(Description description) + { + description.appendList("[", ", ", "]", matchers) + .appendText(" ").appendText(message); } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java b/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java index fc968e0b..f7b2cee8 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java @@ -14,7 +14,8 @@ * @author Steve Freeman 2016 http://www.hamcrest.com * Collected helper code for converting matchers between lists and iterables. */ -public class ArrayMatching { +public class ArrayMatching +{ /** @@ -27,8 +28,9 @@ public class ArrayMatching { * @param elementMatcher * the matcher to apply to elements in examined arrays */ - public static Matcher hasItemInArray(Matcher elementMatcher) { - return new HasItemInArray<>(elementMatcher); + public static Matcher hasItemInArray(Matcher elementMatcher) + { + return new HasItemInArray<>(elementMatcher); } /** @@ -41,7 +43,8 @@ public static Matcher hasItemInArray(Matcher elementMatcher) * @param element * the element that should be present in examined arrays */ - public static Matcher hasItemInArray(T element) { + public static Matcher hasItemInArray(T element) + { return hasItemInArray(equalTo(element)); } @@ -66,8 +69,9 @@ public static Matcher hasItemInArray(T element) { * a list of matchers, each of which must be satisfied by an entry in an examined array */ @SafeVarargs - public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) { - return arrayContainingInAnyOrder(asList(itemMatchers)); + public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) + { + return arrayContainingInAnyOrder(asList(itemMatchers)); } /** @@ -90,7 +94,8 @@ public static Matcher arrayContainingInAnyOrder(Matcher... i * @param itemMatchers * a list of matchers, each of which must be satisfied by an item provided by an examined array */ - public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) { + public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) + { return new ArrayAsIterableMatcher<>(new IsIterableContainingInAnyOrder<>(itemMatchers), itemMatchers, "in any order"); } @@ -113,7 +118,8 @@ public static Matcher arrayContainingInAnyOrder(Collection Matcher arrayContainingInAnyOrder(E... items) { + public static Matcher arrayContainingInAnyOrder(E... items) + { return arrayContainingInAnyOrder(asEqualMatchers(items)); } @@ -128,9 +134,11 @@ public static Matcher arrayContainingInAnyOrder(E... items) { * the items that must equal the items within an examined array */ @SafeVarargs - public static Matcher arrayContaining(E... items) { + public static Matcher arrayContaining(E... items) + { return arrayContaining(asEqualMatchers(items)); } + /** * Creates a matcher for arrays that matches when each item in the examined array satisfies the * corresponding matcher in the specified matchers. For a positive match, the examined array @@ -142,12 +150,13 @@ public static Matcher arrayContaining(E... items) { * the matchers that must be satisfied by the items in the examined array */ @SafeVarargs - public static Matcher arrayContaining(Matcher... itemMatchers) { - //required for JDK 1.6 - //noinspection RedundantTypeArguments - final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); + public static Matcher arrayContaining(Matcher... itemMatchers) + { + //required for JDK 1.6 + //noinspection RedundantTypeArguments + final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); - return arrayContaining(nullSafeWithExplicitTypeMatchers); + return arrayContaining(nullSafeWithExplicitTypeMatchers); } /** @@ -160,13 +169,16 @@ public static Matcher arrayContaining(Matcher... itemMatcher * @param itemMatchers * a list of matchers, each of which must be satisfied by the corresponding item in an examined array */ - public static Matcher arrayContaining(List> itemMatchers) { - return new ArrayAsIterableMatcher<>(new IsIterableContainingInOrder<>(itemMatchers), itemMatchers, ""); + public static Matcher arrayContaining(List> itemMatchers) + { + return new ArrayAsIterableMatcher<>(new IsIterableContainingInOrder<>(itemMatchers), itemMatchers, ""); } - public static List> asEqualMatchers(E[] items) { + public static List> asEqualMatchers(E[] items) + { final List> matchers = new ArrayList<>(); - for (E item : items) { + for (E item : items) + { matchers.add(equalTo(item)); } return matchers; diff --git a/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java b/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java index 5c0513c1..651c3366 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java @@ -11,30 +11,35 @@ /** * Matches if an array contains an item satisfying a nested matcher. */ -public class HasItemInArray extends TypeSafeMatcher { - private final Matcher elementMatcher; - private final TypeSafeDiagnosingMatcher> collectionMatcher; - - public HasItemInArray(Matcher elementMatcher) { - this.elementMatcher = elementMatcher; - this.collectionMatcher = new IsIterableContaining<>(elementMatcher); - } - - @Override - public boolean matchesSafely(T[] actual) { - return collectionMatcher.matches(asList(actual)); - } - - @Override - public void describeMismatchSafely(T[] actual, Description mismatchDescription) { - collectionMatcher.describeMismatch(asList(actual), mismatchDescription); - } - - @Override - public void describeTo(Description description) { - description +public class HasItemInArray extends TypeSafeMatcher +{ + private final Matcher elementMatcher; + private final TypeSafeDiagnosingMatcher> collectionMatcher; + + public HasItemInArray(Matcher elementMatcher) + { + this.elementMatcher = elementMatcher; + this.collectionMatcher = new IsIterableContaining<>(elementMatcher); + } + + @Override + public boolean matchesSafely(T[] actual) + { + return collectionMatcher.matches(asList(actual)); + } + + @Override + public void describeMismatchSafely(T[] actual, Description mismatchDescription) + { + collectionMatcher.describeMismatch(asList(actual), mismatchDescription); + } + + @Override + public void describeTo(Description description) + { + description .appendText("an array containing ") .appendDescriptionOf(elementMatcher); - } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java b/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java index 38f5d915..cfe6bc7c 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java @@ -10,88 +10,107 @@ * Matcher for array whose elements satisfy a sequence of matchers. * The array size must equal the number of element matchers. */ -public class IsArray extends TypeSafeMatcher { - private final Matcher[] elementMatchers; - - public IsArray(Matcher[] elementMatchers) { - this.elementMatchers = elementMatchers.clone(); - } - - @Override - public boolean matchesSafely(T[] array) { - if (array.length != elementMatchers.length) return false; - - for (int i = 0; i < array.length; i++) { - if (!elementMatchers[i].matches(array[i])) return false; - } - - return true; - } +public class IsArray extends TypeSafeMatcher +{ + private final Matcher[] elementMatchers; - @Override - public void describeMismatchSafely(T[] actual, Description mismatchDescription) { - if (actual.length != elementMatchers.length) { - mismatchDescription.appendText("array length was ").appendValue(actual.length); - return; - } - for (int i = 0; i < actual.length; i++) { - if (!elementMatchers[i].matches(actual[i])) { - mismatchDescription.appendText("element ").appendValue(i).appendText(" "); - elementMatchers[i].describeMismatch(actual[i], mismatchDescription); - return; - } - } - } + public IsArray(Matcher[] elementMatchers) + { + this.elementMatchers = elementMatchers.clone(); + } - @Override - @SuppressWarnings("unchecked") - public void describeTo(Description description) { - description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(), - Arrays.asList(elementMatchers)); - } - - /** - * Returns the string that starts the description. - * - * Can be overridden in subclasses to customise how the matcher is - * described. - */ - protected String descriptionStart() { - return "["; + @Override + public boolean matchesSafely(T[] array) + { + if (array.length != elementMatchers.length) + { + return false; } - /** - * Returns the string that separates the elements in the description. - * - * Can be overridden in subclasses to customise how the matcher is - * described. - */ - protected String descriptionSeparator() { - return ", "; + for (int i = 0; i < array.length; i++) + { + if (!elementMatchers[i].matches(array[i])) + { + return false; + } } - /** - * Returns the string that ends the description. - * - * Can be overridden in subclasses to customise how the matcher is - * described. - */ - protected String descriptionEnd() { - return "]"; + return true; + } + + @Override + public void describeMismatchSafely(T[] actual, Description mismatchDescription) + { + if (actual.length != elementMatchers.length) + { + mismatchDescription.appendText("array length was ").appendValue(actual.length); + return; } - - /** - * Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches - * positively only if the number of matchers specified is equal to the length of the examined array and - * each matcher[i] is satisfied by array[i]. - * For example: - *
assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))
- * - * @param elementMatchers - * the matchers that the elements of examined arrays should satisfy - */ - public static IsArray array(Matcher... elementMatchers) { - return new IsArray(elementMatchers); + for (int i = 0; i < actual.length; i++) + { + if (!elementMatchers[i].matches(actual[i])) + { + mismatchDescription.appendText("element ").appendValue(i).appendText(" "); + elementMatchers[i].describeMismatch(actual[i], mismatchDescription); + return; + } } + } + + @Override + @SuppressWarnings("unchecked") + public void describeTo(Description description) + { + description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(), + Arrays.asList(elementMatchers)); + } + + /** + * Returns the string that starts the description. + *

+ * Can be overridden in subclasses to customise how the matcher is + * described. + */ + protected String descriptionStart() + { + return "["; + } + + /** + * Returns the string that separates the elements in the description. + *

+ * Can be overridden in subclasses to customise how the matcher is + * described. + */ + protected String descriptionSeparator() + { + return ", "; + } + + /** + * Returns the string that ends the description. + *

+ * Can be overridden in subclasses to customise how the matcher is + * described. + */ + protected String descriptionEnd() + { + return "]"; + } + + /** + * Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches + * positively only if the number of matchers specified is equal to the length of the examined array and + * each matcher[i] is satisfied by array[i]. + * For example: + *

assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))
+ * + * @param elementMatchers + * the matchers that the elements of examined arrays should satisfy + */ + public static IsArray array(Matcher... elementMatchers) + { + return new IsArray(elementMatchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java index 7e72a622..f1a4f62d 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java @@ -15,98 +15,106 @@ * @deprecated As of release 2.1, replaced by {@link ArrayMatching}. */ @Deprecated -public class IsArrayContainingInAnyOrder extends TypeSafeMatcher { - private final IsIterableContainingInAnyOrder iterableMatcher; - private final Collection> matchers; +public class IsArrayContainingInAnyOrder extends TypeSafeMatcher +{ + private final IsIterableContainingInAnyOrder iterableMatcher; + private final Collection> matchers; - public IsArrayContainingInAnyOrder(Collection> matchers) { - this.iterableMatcher = new IsIterableContainingInAnyOrder(matchers); - this.matchers = matchers; - } + public IsArrayContainingInAnyOrder(Collection> matchers) + { + this.iterableMatcher = new IsIterableContainingInAnyOrder(matchers); + this.matchers = matchers; + } - @Override - public boolean matchesSafely(E[] item) { - return iterableMatcher.matches(Arrays.asList(item)); - } - - @Override - public void describeMismatchSafely(E[] item, Description mismatchDescription) { - iterableMatcher.describeMismatch(Arrays.asList(item), mismatchDescription); - }; + @Override + public boolean matchesSafely(E[] item) + { + return iterableMatcher.matches(Arrays.asList(item)); + } - @Override - public void describeTo(Description description) { - description.appendList("[", ", ", "]", matchers) - .appendText(" in any order"); - } + @Override + public void describeMismatchSafely(E[] item, Description mismatchDescription) + { + iterableMatcher.describeMismatch(Arrays.asList(item), mismatchDescription); + } - /** - * Creates an order agnostic matcher for arrays that matches when each item in the - * examined array satisfies one matcher anywhere in the specified matchers. - * For a positive match, the examined array must be of the same length as the number of - * specified matchers. - *

- * N.B. each of the specified matchers will only be used once during a given examination, so be - * careful when specifying matchers that may be satisfied by more than one entry in an examined - * array. - *

- * For example: - *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Matcher[])}. - * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by an entry in an examined array - */ - public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) { - return arrayContainingInAnyOrder(Arrays.asList(itemMatchers)); - } + ; - /** - * Creates an order agnostic matcher for arrays that matches when each item in the - * examined array satisfies one matcher anywhere in the specified collection of matchers. - * For a positive match, the examined array must be of the same length as the specified collection - * of matchers. - *

- * N.B. each matcher in the specified collection will only be used once during a given - * examination, so be careful when specifying matchers that may be satisfied by more than - * one entry in an examined array. - *

- * For example: - *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Collection)}. - * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by an item provided by an examined array - */ - public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) { - return new IsArrayContainingInAnyOrder(itemMatchers); - } + @Override + public void describeTo(Description description) + { + description.appendList("[", ", ", "]", matchers) + .appendText(" in any order"); + } + + /** + * Creates an order agnostic matcher for arrays that matches when each item in the + * examined array satisfies one matcher anywhere in the specified matchers. + * For a positive match, the examined array must be of the same length as the number of + * specified matchers. + *

+ * N.B. each of the specified matchers will only be used once during a given examination, so be + * careful when specifying matchers that may be satisfied by more than one entry in an examined + * array. + *

+ * For example: + *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(equalTo("bar"), equalTo("foo")))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by an entry in an examined array + * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Matcher[])}. + */ + public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) + { + return arrayContainingInAnyOrder(Arrays.asList(itemMatchers)); + } + + /** + * Creates an order agnostic matcher for arrays that matches when each item in the + * examined array satisfies one matcher anywhere in the specified collection of matchers. + * For a positive match, the examined array must be of the same length as the specified collection + * of matchers. + *

+ * N.B. each matcher in the specified collection will only be used once during a given + * examination, so be careful when specifying matchers that may be satisfied by more than + * one entry in an examined array. + *

+ * For example: + *

assertThat(new String[]{"foo", "bar"}, arrayContainingInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by an item provided by an examined array + * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Collection)}. + */ + public static Matcher arrayContainingInAnyOrder(Collection> itemMatchers) + { + return new IsArrayContainingInAnyOrder(itemMatchers); + } - /** - * Creates an order agnostic matcher for arrays that matches when each item in the - * examined array is logically equal to one item anywhere in the specified items. - * For a positive match, the examined array must be of the same length as the number of - * specified items. - *

- * N.B. each of the specified items will only be used once during a given examination, so be - * careful when specifying items that may be equal to more than one entry in an examined - * array. - *

- * For example: - *

assertThat(new String[]{"foo", "bar"}, containsInAnyOrder("bar", "foo"))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Object[])}. - * - * @param items - * the items that must equal the entries of an examined array, in any order - */ - public static Matcher arrayContainingInAnyOrder(E... items) { - List> matchers = new ArrayList>(); - for (E item : items) { - matchers.add(equalTo(item)); - } - return new IsArrayContainingInAnyOrder(matchers); + /** + * Creates an order agnostic matcher for arrays that matches when each item in the + * examined array is logically equal to one item anywhere in the specified items. + * For a positive match, the examined array must be of the same length as the number of + * specified items. + *

+ * N.B. each of the specified items will only be used once during a given examination, so be + * careful when specifying items that may be equal to more than one entry in an examined + * array. + *

+ * For example: + *

assertThat(new String[]{"foo", "bar"}, containsInAnyOrder("bar", "foo"))
+ * + * @param items + * the items that must equal the entries of an examined array, in any order + * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContainingInAnyOrder(Object[])}. + */ + public static Matcher arrayContainingInAnyOrder(E... items) + { + List> matchers = new ArrayList>(); + for (E item : items) + { + matchers.add(equalTo(item)); } + return new IsArrayContainingInAnyOrder(matchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java index c046914f..9b6513db 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java @@ -14,82 +14,88 @@ /** * @deprecated As of release 2.1, replaced by {@link ArrayMatching}. */ -public class IsArrayContainingInOrder extends TypeSafeMatcher { - private final Collection> matchers; - private final IsIterableContainingInOrder iterableMatcher; +public class IsArrayContainingInOrder extends TypeSafeMatcher +{ + private final Collection> matchers; + private final IsIterableContainingInOrder iterableMatcher; - public IsArrayContainingInOrder(List> matchers) { - this.iterableMatcher = new IsIterableContainingInOrder(matchers); - this.matchers = matchers; - } + public IsArrayContainingInOrder(List> matchers) + { + this.iterableMatcher = new IsIterableContainingInOrder(matchers); + this.matchers = matchers; + } - @Override - public boolean matchesSafely(E[] item) { - return iterableMatcher.matches(asList(item)); - } - - @Override - public void describeMismatchSafely(E[] item, Description mismatchDescription) { - iterableMatcher.describeMismatch(asList(item), mismatchDescription); - } + @Override + public boolean matchesSafely(E[] item) + { + return iterableMatcher.matches(asList(item)); + } - @Override - public void describeTo(Description description) { - description.appendList("[", ", ", "]", matchers); - } + @Override + public void describeMismatchSafely(E[] item, Description mismatchDescription) + { + iterableMatcher.describeMismatch(asList(item), mismatchDescription); + } - /** - * Creates a matcher for arrays that matcheswhen each item in the examined array is - * logically equal to the corresponding item in the specified items. For a positive match, - * the examined array must be of the same length as the number of specified items. - *

- * For example: - *

assertThat(new String[]{"foo", "bar"}, contains("foo", "bar"))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(Object[])}. - * - * @param items - * the items that must equal the items within an examined array - */ - public static Matcher arrayContaining(E... items) { - List> matchers = new ArrayList>(); - for (E item : items) { - matchers.add(equalTo(item)); - } - return arrayContaining(matchers); - } + @Override + public void describeTo(Description description) + { + description.appendList("[", ", ", "]", matchers); + } - /** - * Creates a matcher for arrays that matches when each item in the examined array satisfies the - * corresponding matcher in the specified matchers. For a positive match, the examined array - * must be of the same length as the number of specified matchers. - *

- * For example: - *

assertThat(new String[]{"foo", "bar"}, contains(equalTo("foo"), equalTo("bar")))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(Matcher[])}. - * - * @param itemMatchers - * the matchers that must be satisfied by the items in the examined array - */ - public static Matcher arrayContaining(Matcher... itemMatchers) { - return arrayContaining(asList(itemMatchers)); + /** + * Creates a matcher for arrays that matcheswhen each item in the examined array is + * logically equal to the corresponding item in the specified items. For a positive match, + * the examined array must be of the same length as the number of specified items. + *

+ * For example: + *

assertThat(new String[]{"foo", "bar"}, contains("foo", "bar"))
+ * + * @param items + * the items that must equal the items within an examined array + * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(Object[])}. + */ + public static Matcher arrayContaining(E... items) + { + List> matchers = new ArrayList>(); + for (E item : items) + { + matchers.add(equalTo(item)); } + return arrayContaining(matchers); + } - /** - * Creates a matcher for arrays that matches when each item in the examined array satisfies the - * corresponding matcher in the specified list of matchers. For a positive match, the examined array - * must be of the same length as the specified list of matchers. - *

- * For example: - *

assertThat(new String[]{"foo", "bar"}, contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(List)}. - * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by the corresponding item in an examined array - */ - public static Matcher arrayContaining(List> itemMatchers) { - return new IsArrayContainingInOrder(itemMatchers); - } + /** + * Creates a matcher for arrays that matches when each item in the examined array satisfies the + * corresponding matcher in the specified matchers. For a positive match, the examined array + * must be of the same length as the number of specified matchers. + *

+ * For example: + *

assertThat(new String[]{"foo", "bar"}, contains(equalTo("foo"), equalTo("bar")))
+ * + * @param itemMatchers + * the matchers that must be satisfied by the items in the examined array + * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(Matcher[])}. + */ + public static Matcher arrayContaining(Matcher... itemMatchers) + { + return arrayContaining(asList(itemMatchers)); + } + + /** + * Creates a matcher for arrays that matches when each item in the examined array satisfies the + * corresponding matcher in the specified list of matchers. For a positive match, the examined array + * must be of the same length as the specified list of matchers. + *

+ * For example: + *

assertThat(new String[]{"foo", "bar"}, contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by the corresponding item in an examined array + * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(List)}. + */ + public static Matcher arrayContaining(List> itemMatchers) + { + return new IsArrayContainingInOrder(itemMatchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java index 4ae7235e..cd508493 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java @@ -9,50 +9,55 @@ /** * Matches if array size satisfies a nested matcher. */ -public class IsArrayWithSize extends FeatureMatcher { - public IsArrayWithSize(Matcher sizeMatcher) { - super(sizeMatcher, "an array with size","array size"); - } +public class IsArrayWithSize extends FeatureMatcher +{ + public IsArrayWithSize(Matcher sizeMatcher) + { + super(sizeMatcher, "an array with size", "array size"); + } - @Override - protected Integer featureValueOf(E[] actual) { - return actual.length; - } + @Override + protected Integer featureValueOf(E[] actual) + { + return actual.length; + } - /** - * Creates a matcher for arrays that matches when the length of the array - * satisfies the specified matcher. - * For example: - *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))
- * - * @param sizeMatcher - * a matcher for the length of an examined array - */ - public static Matcher arrayWithSize(Matcher sizeMatcher) { - return new IsArrayWithSize<>(sizeMatcher); - } + /** + * Creates a matcher for arrays that matches when the length of the array + * satisfies the specified matcher. + * For example: + *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))
+ * + * @param sizeMatcher + * a matcher for the length of an examined array + */ + public static Matcher arrayWithSize(Matcher sizeMatcher) + { + return new IsArrayWithSize<>(sizeMatcher); + } - /** - * Creates a matcher for arrays that matches when the length of the array - * equals the specified size. - * For example: - *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))
- * - * @param size - * the length that an examined array must have for a positive match - */ - public static Matcher arrayWithSize(int size) { - return arrayWithSize(equalTo(size)); - } + /** + * Creates a matcher for arrays that matches when the length of the array + * equals the specified size. + * For example: + *
assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))
+ * + * @param size + * the length that an examined array must have for a positive match + */ + public static Matcher arrayWithSize(int size) + { + return arrayWithSize(equalTo(size)); + } - /** - * Creates a matcher for arrays that matches when the length of the array - * is zero. - * For example: - *
assertThat(new String[0], emptyArray())
- * - */ - public static Matcher emptyArray() { - return describedAs("an empty array", IsArrayWithSize.arrayWithSize(0)); - } + /** + * Creates a matcher for arrays that matches when the length of the array + * is zero. + * For example: + *
assertThat(new String[0], emptyArray())
+ */ + public static Matcher emptyArray() + { + return describedAs("an empty array", IsArrayWithSize.arrayWithSize(0)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java b/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java index f79afdc6..e2ed9794 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java @@ -10,41 +10,46 @@ /** * Matches if collection size satisfies a nested matcher. */ -public class IsCollectionWithSize extends FeatureMatcher, Integer> { - public IsCollectionWithSize(Matcher sizeMatcher) { - super(sizeMatcher, "a collection with size", "collection size"); - } - - @Override - protected Integer featureValueOf(Collection actual) { - return actual.size(); - } - - /** - * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns - * a value that satisfies the specified matcher. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))
- * - * @param sizeMatcher - * a matcher for the size of an examined {@link java.util.Collection} - */ - public static Matcher> hasSize(Matcher sizeMatcher) { - return new IsCollectionWithSize(sizeMatcher); - } - - /** - * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns - * a value equal to the specified size. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), hasSize(2))
- * - * @param size - * the expected size of an examined {@link java.util.Collection} - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Matcher> hasSize(int size) { - return (Matcher)IsCollectionWithSize.hasSize(equalTo(size)); - } +public class IsCollectionWithSize extends FeatureMatcher, Integer> +{ + public IsCollectionWithSize(Matcher sizeMatcher) + { + super(sizeMatcher, "a collection with size", "collection size"); + } + + @Override + protected Integer featureValueOf(Collection actual) + { + return actual.size(); + } + + /** + * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns + * a value that satisfies the specified matcher. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))
+ * + * @param sizeMatcher + * a matcher for the size of an examined {@link java.util.Collection} + */ + public static Matcher> hasSize(Matcher sizeMatcher) + { + return new IsCollectionWithSize(sizeMatcher); + } + + /** + * Creates a matcher for {@link java.util.Collection}s that matches when the size() method returns + * a value equal to the specified size. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), hasSize(2))
+ * + * @param size + * the expected size of an examined {@link java.util.Collection} + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static Matcher> hasSize(int size) + { + return (Matcher) IsCollectionWithSize.hasSize(equalTo(size)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java b/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java index 481b08c3..4143378a 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java @@ -9,45 +9,50 @@ /** * Tests if collection is empty. */ -public class IsEmptyCollection extends TypeSafeMatcher> { - - @Override - public boolean matchesSafely(Collection item) { - return item.isEmpty(); - } - - @Override - public void describeMismatchSafely(Collection item, Description mismatchDescription) { - mismatchDescription.appendValue(item); - } - - @Override - public void describeTo(Description description) { - description.appendText("an empty collection"); - } - - /** - * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty - * method returns true. - * For example: - *
assertThat(new ArrayList<String>(), is(empty()))
- * - */ - public static Matcher> empty() { - return new IsEmptyCollection(); - } - - /** - * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty - * method returns true. - * For example: - *
assertThat(new ArrayList<String>(), is(emptyCollectionOf(String.class)))
- * - * @param unusedToForceReturnType - * the type of the collection's content - */ - @SuppressWarnings({"unchecked", "UnusedParameters"}) - public static Matcher> emptyCollectionOf(Class unusedToForceReturnType) { - return (Matcher)empty(); - } +public class IsEmptyCollection extends TypeSafeMatcher> +{ + + @Override + public boolean matchesSafely(Collection item) + { + return item.isEmpty(); + } + + @Override + public void describeMismatchSafely(Collection item, Description mismatchDescription) + { + mismatchDescription.appendValue(item); + } + + @Override + public void describeTo(Description description) + { + description.appendText("an empty collection"); + } + + /** + * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty + * method returns true. + * For example: + *
assertThat(new ArrayList<String>(), is(empty()))
+ */ + public static Matcher> empty() + { + return new IsEmptyCollection(); + } + + /** + * Creates a matcher for {@link java.util.Collection}s matching examined collections whose isEmpty + * method returns true. + * For example: + *
assertThat(new ArrayList<String>(), is(emptyCollectionOf(String.class)))
+ * + * @param unusedToForceReturnType + * the type of the collection's content + */ + @SuppressWarnings({ "unchecked", "UnusedParameters" }) + public static Matcher> emptyCollectionOf(Class unusedToForceReturnType) + { + return (Matcher) empty(); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java b/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java index 047e670c..e47d7712 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java @@ -7,42 +7,48 @@ /** * Tests if collection is empty. */ -public class IsEmptyIterable extends TypeSafeMatcher> { +public class IsEmptyIterable extends TypeSafeMatcher> +{ - @Override - public boolean matchesSafely(Iterable iterable) { - return !iterable.iterator().hasNext(); - } - @Override - public void describeMismatchSafely(Iterable iter, Description mismatchDescription) { - mismatchDescription.appendValueList("[", ",", "]", iter); - } + @Override + public boolean matchesSafely(Iterable iterable) + { + return !iterable.iterator().hasNext(); + } - @Override - public void describeTo(Description description) { - description.appendText("an empty iterable"); - } + @Override + public void describeMismatchSafely(Iterable iter, Description mismatchDescription) + { + mismatchDescription.appendValueList("[", ",", "]", iter); + } - /** - * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. - * For example: - *
assertThat(new ArrayList<String>(), is(emptyIterable()))
- * - */ - public static Matcher> emptyIterable() { - return new IsEmptyIterable(); - } + @Override + public void describeTo(Description description) + { + description.appendText("an empty iterable"); + } - /** - * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. - * For example: - *
assertThat(new ArrayList<String>(), is(emptyIterableOf(String.class)))
- * - * @param unusedToForceReturnType - * the type of the iterable's content - */ - @SuppressWarnings({"unchecked", "UnusedParameters"}) - public static Matcher> emptyIterableOf(Class unusedToForceReturnType) { - return (Matcher)emptyIterable(); - } + /** + * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. + * For example: + *
assertThat(new ArrayList<String>(), is(emptyIterable()))
+ */ + public static Matcher> emptyIterable() + { + return new IsEmptyIterable(); + } + + /** + * Creates a matcher for {@link Iterable}s matching examined iterables that yield no items. + * For example: + *
assertThat(new ArrayList<String>(), is(emptyIterableOf(String.class)))
+ * + * @param unusedToForceReturnType + * the type of the iterable's content + */ + @SuppressWarnings({ "unchecked", "UnusedParameters" }) + public static Matcher> emptyIterableOf(Class unusedToForceReturnType) + { + return (Matcher) emptyIterable(); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java b/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java index 84098110..98e2bdfb 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java @@ -7,121 +7,123 @@ import java.util.Arrays; import java.util.Collection; -public class IsIn extends BaseMatcher { - private final Collection collection; +public class IsIn extends BaseMatcher +{ + private final Collection collection; - public IsIn(Collection collection) { - this.collection = collection; - } - - public IsIn(T[] elements) { - collection = Arrays.asList(elements); - } - - @SuppressWarnings("SuspiciousMethodCalls") - @Override - public boolean matches(Object o) { - return collection.contains(o); - } + public IsIn(Collection collection) + { + this.collection = collection; + } - @Override - public void describeTo(Description buffer) { - buffer.appendText("one of "); - buffer.appendValueList("{", ", ", "}", collection); - } - - /** - * Creates a matcher that matches when the examined object is found within the - * specified collection. - * For example: - *
assertThat("foo", isIn(Arrays.asList("bar", "foo")))
- * - * @deprecated use is(in(...)) instead - * - * @param collection - * the collection in which matching items must be found - * - */ - @Deprecated - public static Matcher isIn(Collection collection) { - return in(collection); - } - - /** - * Creates a matcher that matches when the examined object is found within the - * specified collection. - * For example: - *
assertThat("foo", is(in(Arrays.asList("bar", "foo"))))
- * - * @param collection - * the collection in which matching items must be found - * - */ - public static Matcher in(Collection collection) { - return new IsIn<>(collection); - } + public IsIn(T[] elements) + { + collection = Arrays.asList(elements); + } - /** - * Creates a matcher that matches when the examined object is found within the - * specified array. - * For example: - *
assertThat("foo", isIn(new String[]{"bar", "foo"}))
- * - * @deprecated use is(in(...)) instead - * - * @param elements - * the array in which matching items must be found - * - */ - @Deprecated - public static Matcher isIn(T[] elements) { - return in(elements); - } - - /** - * Creates a matcher that matches when the examined object is found within the - * specified array. - * For example: - *
assertThat("foo", is(in(new String[]{"bar", "foo"})))
- * - * @param elements - * the array in which matching items must be found - * - */ - public static Matcher in(T[] elements) { - return new IsIn<>(elements); - } - - /** - * Creates a matcher that matches when the examined object is equal to one of the - * specified elements. - * For example: - *
assertThat("foo", isOneOf("bar", "foo"))
- * - * @deprecated use is(oneOf(...)) instead - * - * @param elements - * the elements amongst which matching items will be found - * - */ - @SafeVarargs - @Deprecated - public static Matcher isOneOf(T... elements) { - return oneOf(elements); - } - - /** - * Creates a matcher that matches when the examined object is equal to one of the - * specified elements. - * For example: - *
assertThat("foo", is(oneOf("bar", "foo")))
- * - * @param elements - * the elements amongst which matching items will be found - * - */ - @SafeVarargs - public static Matcher oneOf(T... elements) { - return in(elements); - } + @SuppressWarnings("SuspiciousMethodCalls") + @Override + public boolean matches(Object o) + { + return collection.contains(o); + } + + @Override + public void describeTo(Description buffer) + { + buffer.appendText("one of "); + buffer.appendValueList("{", ", ", "}", collection); + } + + /** + * Creates a matcher that matches when the examined object is found within the + * specified collection. + * For example: + *
assertThat("foo", isIn(Arrays.asList("bar", "foo")))
+ * + * @param collection + * the collection in which matching items must be found + * @deprecated use is(in(...)) instead + */ + @Deprecated + public static Matcher isIn(Collection collection) + { + return in(collection); + } + + /** + * Creates a matcher that matches when the examined object is found within the + * specified collection. + * For example: + *
assertThat("foo", is(in(Arrays.asList("bar", "foo"))))
+ * + * @param collection + * the collection in which matching items must be found + */ + public static Matcher in(Collection collection) + { + return new IsIn<>(collection); + } + + /** + * Creates a matcher that matches when the examined object is found within the + * specified array. + * For example: + *
assertThat("foo", isIn(new String[]{"bar", "foo"}))
+ * + * @param elements + * the array in which matching items must be found + * @deprecated use is(in(...)) instead + */ + @Deprecated + public static Matcher isIn(T[] elements) + { + return in(elements); + } + + /** + * Creates a matcher that matches when the examined object is found within the + * specified array. + * For example: + *
assertThat("foo", is(in(new String[]{"bar", "foo"})))
+ * + * @param elements + * the array in which matching items must be found + */ + public static Matcher in(T[] elements) + { + return new IsIn<>(elements); + } + + /** + * Creates a matcher that matches when the examined object is equal to one of the + * specified elements. + * For example: + *
assertThat("foo", isOneOf("bar", "foo"))
+ * + * @param elements + * the elements amongst which matching items will be found + * @deprecated use is(oneOf(...)) instead + */ + @SafeVarargs + @Deprecated + public static Matcher isOneOf(T... elements) + { + return oneOf(elements); + } + + /** + * Creates a matcher that matches when the examined object is equal to one of the + * specified elements. + * For example: + *
assertThat("foo", is(oneOf("bar", "foo")))
+ * + * @param elements + * the elements amongst which matching items will be found + */ + @SafeVarargs + public static Matcher oneOf(T... elements) + { + return in(elements); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java index d6a9a33d..8c906628 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java @@ -11,146 +11,165 @@ import static org.hamcrest.core.IsEqual.equalTo; -public class IsIterableContainingInAnyOrder extends TypeSafeDiagnosingMatcher> { - private final Collection> matchers; +public class IsIterableContainingInAnyOrder extends TypeSafeDiagnosingMatcher> +{ + private final Collection> matchers; - public IsIterableContainingInAnyOrder(Collection> matchers) { - this.matchers = matchers; - } - - @Override - protected boolean matchesSafely(Iterable items, Description mismatchDescription) { - final Matching matching = new Matching<>(matchers, mismatchDescription); - for (T item : items) { - if (! matching.matches(item)) { - return false; - } + public IsIterableContainingInAnyOrder(Collection> matchers) + { + this.matchers = matchers; + } + + @Override + protected boolean matchesSafely(Iterable items, Description mismatchDescription) + { + final Matching matching = new Matching<>(matchers, mismatchDescription); + for (T item : items) + { + if (!matching.matches(item)) + { + return false; } - - return matching.isFinished(items); - } - - @Override - public void describeTo(Description description) { - description.appendText("iterable with items ") - .appendList("[", ", ", "]", matchers) - .appendText(" in any order"); } - private static class Matching { - private final Collection> matchers; - private final Description mismatchDescription; + return matching.isFinished(items); + } - public Matching(Collection> matchers, Description mismatchDescription) { - this.matchers = new ArrayList<>(matchers); - this.mismatchDescription = mismatchDescription; - } - - public boolean matches(S item) { - if (matchers.isEmpty()) { - mismatchDescription.appendText("no match for: ").appendValue(item); - return false; - } - return isMatched(item); - } + @Override + public void describeTo(Description description) + { + description.appendText("iterable with items ") + .appendList("[", ", ", "]", matchers) + .appendText(" in any order"); + } - public boolean isFinished(Iterable items) { - if (matchers.isEmpty()) { - return true; - } - mismatchDescription - .appendText("no item matches: ").appendList("", ", ", "", matchers) - .appendText(" in ").appendValueList("[", ", ", "]", items); - return false; - } + private static class Matching + { + private final Collection> matchers; + private final Description mismatchDescription; - private boolean isMatched(S item) { - for (Matcher matcher : matchers) { - if (matcher.matches(item)) { - matchers.remove(matcher); - return true; - } - } - mismatchDescription.appendText("not matched: ").appendValue(item); + public Matching(Collection> matchers, Description mismatchDescription) + { + this.matchers = new ArrayList<>(matchers); + this.mismatchDescription = mismatchDescription; + } + + public boolean matches(S item) + { + if (matchers.isEmpty()) + { + mismatchDescription.appendText("no match for: ").appendValue(item); return false; } + return isMatched(item); } - /** - *

- * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over - * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere - * in the specified matchers. For a positive match, the examined iterable must be of the same - * length as the number of specified matchers. - *

- *

- * N.B. each of the specified matchers will only be used once during a given examination, so be - * careful when specifying matchers that may be satisfied by more than one entry in an examined - * iterable. - *

- *

- * For example: - *

- *
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(equalTo("bar"), equalTo("foo")))
- * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> containsInAnyOrder(Matcher... itemMatchers) { - return containsInAnyOrder(Arrays.asList(itemMatchers)); + public boolean isFinished(Iterable items) + { + if (matchers.isEmpty()) + { + return true; + } + mismatchDescription + .appendText("no item matches: ").appendList("", ", ", "", matchers) + .appendText(" in ").appendValueList("[", ", ", "]", items); + return false; } - /** - *

- * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over - * the examined {@link Iterable} yields a series of items, each logically equal to one item - * anywhere in the specified items. For a positive match, the examined iterable - * must be of the same length as the number of specified items. - *

- *

- * N.B. each of the specified items will only be used once during a given examination, so be - * careful when specifying items that may be equal to more than one entry in an examined - * iterable. - *

- *

- * For example: - *

- *
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder("bar", "foo"))
- * - * @param items - * the items that must equal the items provided by an examined {@link Iterable} in any order - */ - @SafeVarargs - public static Matcher> containsInAnyOrder(T... items) { - List> matchers = new ArrayList<>(); - for (T item : items) { - matchers.add(equalTo(item)); + private boolean isMatched(S item) + { + for (Matcher matcher : matchers) + { + if (matcher.matches(item)) + { + matchers.remove(matcher); + return true; } - - return new IsIterableContainingInAnyOrder<>(matchers); + } + mismatchDescription.appendText("not matched: ").appendValue(item); + return false; } + } - /** - *

- * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over - * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere - * in the specified collection of matchers. For a positive match, the examined iterable - * must be of the same length as the specified collection of matchers. - *

- *

- * N.B. each matcher in the specified collection will only be used once during a given - * examination, so be careful when specifying matchers that may be satisfied by more than - * one entry in an examined iterable. - *

- *

For example:

- *
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
- * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} - */ - public static Matcher> containsInAnyOrder(Collection> itemMatchers) { - return new IsIterableContainingInAnyOrder<>(itemMatchers); + /** + *

+ * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over + * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere + * in the specified matchers. For a positive match, the examined iterable must be of the same + * length as the number of specified matchers. + *

+ *

+ * N.B. each of the specified matchers will only be used once during a given examination, so be + * careful when specifying matchers that may be satisfied by more than one entry in an examined + * iterable. + *

+ *

+ * For example: + *

+ *
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(equalTo("bar"), equalTo("foo")))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} + */ + @SafeVarargs + public static Matcher> containsInAnyOrder(Matcher... itemMatchers) + { + return containsInAnyOrder(Arrays.asList(itemMatchers)); + } + + /** + *

+ * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over + * the examined {@link Iterable} yields a series of items, each logically equal to one item + * anywhere in the specified items. For a positive match, the examined iterable + * must be of the same length as the number of specified items. + *

+ *

+ * N.B. each of the specified items will only be used once during a given examination, so be + * careful when specifying items that may be equal to more than one entry in an examined + * iterable. + *

+ *

+ * For example: + *

+ *
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder("bar", "foo"))
+ * + * @param items + * the items that must equal the items provided by an examined {@link Iterable} in any order + */ + @SafeVarargs + public static Matcher> containsInAnyOrder(T... items) + { + List> matchers = new ArrayList<>(); + for (T item : items) + { + matchers.add(equalTo(item)); } + + return new IsIterableContainingInAnyOrder<>(matchers); + } + + /** + *

+ * Creates an order agnostic matcher for {@link Iterable}s that matches when a single pass over + * the examined {@link Iterable} yields a series of items, each satisfying one matcher anywhere + * in the specified collection of matchers. For a positive match, the examined iterable + * must be of the same length as the specified collection of matchers. + *

+ *

+ * N.B. each matcher in the specified collection will only be used once during a given + * examination, so be careful when specifying matchers that may be satisfied by more than + * one entry in an examined iterable. + *

+ *

For example:

+ *
assertThat(Arrays.asList("foo", "bar"), containsInAnyOrder(Arrays.asList(equalTo("bar"), equalTo("foo"))))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by an item provided by an examined {@link Iterable} + */ + public static Matcher> containsInAnyOrder(Collection> itemMatchers) + { + return new IsIterableContainingInAnyOrder<>(itemMatchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java index ed62aa29..2d998437 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java @@ -11,140 +11,160 @@ import static java.util.Collections.singletonList; import static org.hamcrest.collection.ArrayMatching.asEqualMatchers; -public class IsIterableContainingInOrder extends TypeSafeDiagnosingMatcher> { - private final List> matchers; - - public IsIterableContainingInOrder(List> matchers) { - this.matchers = matchers; +public class IsIterableContainingInOrder extends TypeSafeDiagnosingMatcher> +{ + private final List> matchers; + + public IsIterableContainingInOrder(List> matchers) + { + this.matchers = matchers; + } + + @Override + protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) + { + final MatchSeries matchSeries = new MatchSeries<>(matchers, mismatchDescription); + for (E item : iterable) + { + if (!matchSeries.matches(item)) + { + return false; + } } - @Override - protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) { - final MatchSeries matchSeries = new MatchSeries<>(matchers, mismatchDescription); - for (E item : iterable) { - if (!matchSeries.matches(item)) { - return false; - } - } - - return matchSeries.isFinished(); + return matchSeries.isFinished(); + } + + @Override + public void describeTo(Description description) + { + description.appendText("iterable containing ").appendList("[", ", ", "]", matchers); + } + + private static class MatchSeries + { + private final List> matchers; + private final Description mismatchDescription; + private int nextMatchIx = 0; + + public MatchSeries(List> matchers, Description mismatchDescription) + { + this.mismatchDescription = mismatchDescription; + if (matchers.isEmpty()) + { + throw new IllegalArgumentException("Should specify at least one expected element"); + } + this.matchers = matchers; } - @Override - public void describeTo(Description description) { - description.appendText("iterable containing ").appendList("[", ", ", "]", matchers); - } - - private static class MatchSeries { - private final List> matchers; - private final Description mismatchDescription; - private int nextMatchIx = 0; - - public MatchSeries(List> matchers, Description mismatchDescription) { - this.mismatchDescription = mismatchDescription; - if (matchers.isEmpty()) { - throw new IllegalArgumentException("Should specify at least one expected element"); - } - this.matchers = matchers; - } - - public boolean matches(F item) { - if (matchers.size() <= nextMatchIx) { - mismatchDescription.appendText("not matched: ").appendValue(item); - return false; - } - - return isMatched(item); - } - - public boolean isFinished() { - if (nextMatchIx < matchers.size()) { - mismatchDescription.appendText("no item was ").appendDescriptionOf(matchers.get(nextMatchIx)); - return false; - } - return true; - } - - private boolean isMatched(F item) { - final Matcher matcher = matchers.get(nextMatchIx); - if (!matcher.matches(item)) { - describeMismatch(matcher, item); - return false; - } - nextMatchIx++; - return true; - } - - private void describeMismatch(Matcher matcher, F item) { - mismatchDescription.appendText("item " + nextMatchIx + ": "); - matcher.describeMismatch(item, mismatchDescription); - } - } + public boolean matches(F item) + { + if (matchers.size() <= nextMatchIx) + { + mismatchDescription.appendText("not matched: ").appendValue(item); + return false; + } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a series of items, each logically equal to the - * corresponding item in the specified items. For a positive match, the examined iterable - * must be of the same length as the number of specified items. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), contains("foo", "bar"))
- * - * @param items - * the items that must equal the items provided by an examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> contains(E... items) { - return contains(asEqualMatchers(items)); + return isMatched(item); } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a single item that satisfies the specified matcher. - * For a positive match, the examined iterable must only yield one item. - * For example: - *
assertThat(Arrays.asList("foo"), contains(equalTo("foo")))
- * - * @param itemMatcher - * the matcher that must be satisfied by the single item provided by an - * examined {@link Iterable} - */ - @SuppressWarnings("unchecked") - public static Matcher> contains(final Matcher itemMatcher) { - return contains(new ArrayList>(singletonList(itemMatcher))); + public boolean isFinished() + { + if (nextMatchIx < matchers.size()) + { + mismatchDescription.appendText("no item was ").appendDescriptionOf(matchers.get(nextMatchIx)); + return false; + } + return true; } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a series of items, each satisfying the corresponding - * matcher in the specified matchers. For a positive match, the examined iterable - * must be of the same length as the number of specified matchers. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), contains(equalTo("foo"), equalTo("bar")))
- * - * @param itemMatchers - * the matchers that must be satisfied by the items provided by an examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> contains(Matcher... itemMatchers) { - // required for JDK 1.6 - //noinspection RedundantTypeArguments - final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); - return contains(nullSafeWithExplicitTypeMatchers); + private boolean isMatched(F item) + { + final Matcher matcher = matchers.get(nextMatchIx); + if (!matcher.matches(item)) + { + describeMismatch(matcher, item); + return false; + } + nextMatchIx++; + return true; } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a series of items, each satisfying the corresponding - * matcher in the specified list of matchers. For a positive match, the examined iterable - * must be of the same length as the specified list of matchers. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
- * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by the corresponding item provided by - * an examined {@link Iterable} - */ - public static Matcher> contains(List> itemMatchers) { - return new IsIterableContainingInOrder<>(itemMatchers); + private void describeMismatch(Matcher matcher, F item) + { + mismatchDescription.appendText("item " + nextMatchIx + ": "); + matcher.describeMismatch(item, mismatchDescription); } + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a series of items, each logically equal to the + * corresponding item in the specified items. For a positive match, the examined iterable + * must be of the same length as the number of specified items. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), contains("foo", "bar"))
+ * + * @param items + * the items that must equal the items provided by an examined {@link Iterable} + */ + @SafeVarargs + public static Matcher> contains(E... items) + { + return contains(asEqualMatchers(items)); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a single item that satisfies the specified matcher. + * For a positive match, the examined iterable must only yield one item. + * For example: + *
assertThat(Arrays.asList("foo"), contains(equalTo("foo")))
+ * + * @param itemMatcher + * the matcher that must be satisfied by the single item provided by an + * examined {@link Iterable} + */ + @SuppressWarnings("unchecked") + public static Matcher> contains(final Matcher itemMatcher) + { + return contains(new ArrayList>(singletonList(itemMatcher))); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a series of items, each satisfying the corresponding + * matcher in the specified matchers. For a positive match, the examined iterable + * must be of the same length as the number of specified matchers. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), contains(equalTo("foo"), equalTo("bar")))
+ * + * @param itemMatchers + * the matchers that must be satisfied by the items provided by an examined {@link Iterable} + */ + @SafeVarargs + public static Matcher> contains(Matcher... itemMatchers) + { + // required for JDK 1.6 + //noinspection RedundantTypeArguments + final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); + return contains(nullSafeWithExplicitTypeMatchers); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a series of items, each satisfying the corresponding + * matcher in the specified list of matchers. For a positive match, the examined iterable + * must be of the same length as the specified list of matchers. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), contains(Arrays.asList(equalTo("foo"), equalTo("bar"))))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by the corresponding item provided by + * an examined {@link Iterable} + */ + public static Matcher> contains(List> itemMatchers) + { + return new IsIterableContainingInOrder<>(itemMatchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java index 06577685..516135c1 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java @@ -10,110 +10,128 @@ import static java.util.Arrays.asList; import static org.hamcrest.core.IsEqual.equalTo; -public class IsIterableContainingInRelativeOrder extends TypeSafeDiagnosingMatcher> { - private final List> matchers; - - public IsIterableContainingInRelativeOrder(List> matchers) { - this.matchers = matchers; - } - - @Override - protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) { - MatchSeriesInRelativeOrder matchSeriesInRelativeOrder = new MatchSeriesInRelativeOrder<>(matchers, mismatchDescription); - matchSeriesInRelativeOrder.processItems(iterable); - return matchSeriesInRelativeOrder.isFinished(); +public class IsIterableContainingInRelativeOrder extends TypeSafeDiagnosingMatcher> +{ + private final List> matchers; + + public IsIterableContainingInRelativeOrder(List> matchers) + { + this.matchers = matchers; + } + + @Override + protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) + { + MatchSeriesInRelativeOrder matchSeriesInRelativeOrder = new MatchSeriesInRelativeOrder<>(matchers, mismatchDescription); + matchSeriesInRelativeOrder.processItems(iterable); + return matchSeriesInRelativeOrder.isFinished(); + } + + public void describeTo(Description description) + { + description.appendText("iterable containing ").appendList("[", ", ", "]", matchers).appendText(" in relative order"); + } + + private static class MatchSeriesInRelativeOrder + { + public final List> matchers; + private final Description mismatchDescription; + private int nextMatchIx = 0; + private F lastMatchedItem = null; + + public MatchSeriesInRelativeOrder(List> matchers, Description mismatchDescription) + { + this.mismatchDescription = mismatchDescription; + if (matchers.isEmpty()) + { + throw new IllegalArgumentException("Should specify at least one expected element"); + } + this.matchers = matchers; } - public void describeTo(Description description) { - description.appendText("iterable containing ").appendList("[", ", ", "]", matchers).appendText(" in relative order"); - } - - private static class MatchSeriesInRelativeOrder { - public final List> matchers; - private final Description mismatchDescription; - private int nextMatchIx = 0; - private F lastMatchedItem = null; - - public MatchSeriesInRelativeOrder(List> matchers, Description mismatchDescription) { - this.mismatchDescription = mismatchDescription; - if (matchers.isEmpty()) { - throw new IllegalArgumentException("Should specify at least one expected element"); - } - this.matchers = matchers; - } - - public void processItems(Iterable iterable) { - for (F item : iterable) { - if (nextMatchIx < matchers.size()) { - Matcher matcher = matchers.get(nextMatchIx); - if (matcher.matches(item)) { - lastMatchedItem = item; - nextMatchIx++; - } - } - } - } - - public boolean isFinished() { - if (nextMatchIx < matchers.size()) { - mismatchDescription.appendDescriptionOf(matchers.get(nextMatchIx)).appendText(" was not found"); - if (lastMatchedItem != null) { - mismatchDescription.appendText(" after ").appendValue(lastMatchedItem); - } - return false; - } - return true; + public void processItems(Iterable iterable) + { + for (F item : iterable) + { + if (nextMatchIx < matchers.size()) + { + Matcher matcher = matchers.get(nextMatchIx); + if (matcher.matches(item)) + { + lastMatchedItem = item; + nextMatchIx++; + } } - + } } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a series of items, that contains items logically equal to the - * corresponding item in the specified items, in the same relative order - * For example: - *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder("b", "d"))
- * - * @param items - * the items that must be contained within items provided by an examined {@link Iterable} in the same relative order - */ - @SafeVarargs - public static Matcher> containsInRelativeOrder(E... items) { - List> matchers = new ArrayList<>(); - for (E item : items) { - matchers.add(equalTo(item)); + public boolean isFinished() + { + if (nextMatchIx < matchers.size()) + { + mismatchDescription.appendDescriptionOf(matchers.get(nextMatchIx)).appendText(" was not found"); + if (lastMatchedItem != null) + { + mismatchDescription.appendText(" after ").appendValue(lastMatchedItem); } - - return containsInRelativeOrder(matchers); + return false; + } + return true; } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a series of items, that each satisfying the corresponding - * matcher in the specified matchers, in the same relative order. - * For example: - *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
- * - * @param itemMatchers - * the matchers that must be satisfied by the items provided by an examined {@link Iterable} in the same relative order - */ - @SafeVarargs - public static Matcher> containsInRelativeOrder(Matcher... itemMatchers) { - return containsInRelativeOrder(asList(itemMatchers)); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a series of items, that contains items logically equal to the + * corresponding item in the specified items, in the same relative order + * For example: + *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder("b", "d"))
+ * + * @param items + * the items that must be contained within items provided by an examined {@link Iterable} in the same relative order + */ + @SafeVarargs + public static Matcher> containsInRelativeOrder(E... items) + { + List> matchers = new ArrayList<>(); + for (E item : items) + { + matchers.add(equalTo(item)); } - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields a series of items, that contains items satisfying the corresponding - * matcher in the specified list of matchers, in the same relative order. - * For example: - *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), contains(Arrays.asList(equalTo("b"), equalTo("d"))))
- * - * @param itemMatchers - * a list of matchers, each of which must be satisfied by the items provided by - * an examined {@link Iterable} in the same relative order - */ - public static Matcher> containsInRelativeOrder(List> itemMatchers) { - return new IsIterableContainingInRelativeOrder<>(itemMatchers); - } + return containsInRelativeOrder(matchers); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a series of items, that each satisfying the corresponding + * matcher in the specified matchers, in the same relative order. + * For example: + *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
+ * + * @param itemMatchers + * the matchers that must be satisfied by the items provided by an examined {@link Iterable} in the same relative order + */ + @SafeVarargs + public static Matcher> containsInRelativeOrder(Matcher... itemMatchers) + { + return containsInRelativeOrder(asList(itemMatchers)); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields a series of items, that contains items satisfying the corresponding + * matcher in the specified list of matchers, in the same relative order. + * For example: + *
assertThat(Arrays.asList("a", "b", "c", "d", "e"), contains(Arrays.asList(equalTo("b"), equalTo("d"))))
+ * + * @param itemMatchers + * a list of matchers, each of which must be satisfied by the items provided by + * an examined {@link Iterable} in the same relative order + */ + public static Matcher> containsInRelativeOrder(List> itemMatchers) + { + return new IsIterableContainingInRelativeOrder<>(itemMatchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java index 0a1535fe..524c0d2e 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java @@ -7,47 +7,53 @@ import static org.hamcrest.core.IsEqual.equalTo; -public class IsIterableWithSize extends FeatureMatcher, Integer> { - - public IsIterableWithSize(Matcher sizeMatcher) { - super(sizeMatcher, "an iterable with size", "iterable size"); - } - - - @Override - protected Integer featureValueOf(Iterable actual) { - int size = 0; - for (Iterator iterator = actual.iterator(); iterator.hasNext(); iterator.next()) { - size++; - } - return size; - } - - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields an item count that satisfies the specified - * matcher. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(equalTo(2)))
- * - * @param sizeMatcher - * a matcher for the number of items that should be yielded by an examined {@link Iterable} - */ - public static Matcher> iterableWithSize(Matcher sizeMatcher) { - return new IsIterableWithSize(sizeMatcher); - } - - /** - * Creates a matcher for {@link Iterable}s that matches when a single pass over the - * examined {@link Iterable} yields an item count that is equal to the specified - * size argument. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(2))
- * - * @param size - * the number of items that should be yielded by an examined {@link Iterable} - */ - public static Matcher> iterableWithSize(int size) { - return iterableWithSize(equalTo(size)); +public class IsIterableWithSize extends FeatureMatcher, Integer> +{ + + public IsIterableWithSize(Matcher sizeMatcher) + { + super(sizeMatcher, "an iterable with size", "iterable size"); + } + + + @Override + protected Integer featureValueOf(Iterable actual) + { + int size = 0; + for (Iterator iterator = actual.iterator(); iterator.hasNext(); iterator.next()) + { + size++; } + return size; + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields an item count that satisfies the specified + * matcher. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(equalTo(2)))
+ * + * @param sizeMatcher + * a matcher for the number of items that should be yielded by an examined {@link Iterable} + */ + public static Matcher> iterableWithSize(Matcher sizeMatcher) + { + return new IsIterableWithSize(sizeMatcher); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when a single pass over the + * examined {@link Iterable} yields an item count that is equal to the specified + * size argument. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), iterableWithSize(2))
+ * + * @param size + * the number of items that should be yielded by an examined {@link Iterable} + */ + public static Matcher> iterableWithSize(int size) + { + return iterableWithSize(equalTo(size)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java b/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java index 4ed45392..f1a571ae 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java @@ -10,120 +10,133 @@ import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; -public class IsMapContaining extends TypeSafeMatcher> { - private final Matcher keyMatcher; - private final Matcher valueMatcher; +public class IsMapContaining extends TypeSafeMatcher> +{ + private final Matcher keyMatcher; + private final Matcher valueMatcher; - public IsMapContaining(Matcher keyMatcher, Matcher valueMatcher) { - this.keyMatcher = keyMatcher; - this.valueMatcher = valueMatcher; - } + public IsMapContaining(Matcher keyMatcher, Matcher valueMatcher) + { + this.keyMatcher = keyMatcher; + this.valueMatcher = valueMatcher; + } - @Override - public boolean matchesSafely(Map map) { - for (Entry entry : map.entrySet()) { - if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) { - return true; - } - } - return false; + @Override + public boolean matchesSafely(Map map) + { + for (Entry entry : map.entrySet()) + { + if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) + { + return true; + } } + return false; + } - @Override - public void describeMismatchSafely(Map map, Description mismatchDescription) { - mismatchDescription.appendText("map was ").appendValueList("[", ", ", "]", map.entrySet()); - } + @Override + public void describeMismatchSafely(Map map, Description mismatchDescription) + { + mismatchDescription.appendText("map was ").appendValueList("[", ", ", "]", map.entrySet()); + } - @Override - public void describeTo(Description description) { - description.appendText("map containing [") - .appendDescriptionOf(keyMatcher) - .appendText("->") - .appendDescriptionOf(valueMatcher) - .appendText("]"); - } + @Override + public void describeTo(Description description) + { + description.appendText("map containing [") + .appendDescriptionOf(keyMatcher) + .appendText("->") + .appendDescriptionOf(valueMatcher) + .appendText("]"); + } - /** - * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains - * at least one entry whose key satisfies the specified keyMatcher and whose - * value satisfies the specified valueMatcher. - * For example: - *
assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))
- * - * @param keyMatcher - * the key matcher that, in combination with the valueMatcher, must be satisfied by at least one entry - * @param valueMatcher - * the value matcher that, in combination with the keyMatcher, must be satisfied by at least one entry - */ - public static Matcher> hasEntry(Matcher keyMatcher, Matcher valueMatcher) { - return new IsMapContaining<>(keyMatcher, valueMatcher); - } + /** + * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains + * at least one entry whose key satisfies the specified keyMatcher and whose + * value satisfies the specified valueMatcher. + * For example: + *
assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))
+ * + * @param keyMatcher + * the key matcher that, in combination with the valueMatcher, must be satisfied by at least one entry + * @param valueMatcher + * the value matcher that, in combination with the keyMatcher, must be satisfied by at least one entry + */ + public static Matcher> hasEntry(Matcher keyMatcher, Matcher valueMatcher) + { + return new IsMapContaining<>(keyMatcher, valueMatcher); + } - /** - * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains - * at least one entry whose key equals the specified key and whose value equals the - * specified value. - * For example: - *
assertThat(myMap, hasEntry("bar", "foo"))
- * - * @param key - * the key that, in combination with the value, must be describe at least one entry - * @param value - * the value that, in combination with the key, must be describe at least one entry - */ - public static Matcher> hasEntry(K key, V value) { - return new IsMapContaining<>(equalTo(key), equalTo(value)); - } - - /** - * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains - * at least one key that satisfies the specified matcher. - * For example: - *
assertThat(myMap, hasKey(equalTo("bar")))
- * - * @param keyMatcher - * the matcher that must be satisfied by at least one key - */ - public static Matcher> hasKey(Matcher keyMatcher) { - return new IsMapContaining<>(keyMatcher, anything()); - } + /** + * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains + * at least one entry whose key equals the specified key and whose value equals the + * specified value. + * For example: + *
assertThat(myMap, hasEntry("bar", "foo"))
+ * + * @param key + * the key that, in combination with the value, must be describe at least one entry + * @param value + * the value that, in combination with the key, must be describe at least one entry + */ + public static Matcher> hasEntry(K key, V value) + { + return new IsMapContaining<>(equalTo(key), equalTo(value)); + } - /** - * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains - * at least one key that is equal to the specified key. - * For example: - *
assertThat(myMap, hasKey("bar"))
- * - * @param key - * the key that satisfying maps must contain - */ - public static Matcher> hasKey(K key) { - return new IsMapContaining<>(equalTo(key), anything()); - } + /** + * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains + * at least one key that satisfies the specified matcher. + * For example: + *
assertThat(myMap, hasKey(equalTo("bar")))
+ * + * @param keyMatcher + * the matcher that must be satisfied by at least one key + */ + public static Matcher> hasKey(Matcher keyMatcher) + { + return new IsMapContaining<>(keyMatcher, anything()); + } - /** - * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains - * at least one value that satisfies the specified valueMatcher. - * For example: - *
assertThat(myMap, hasValue(equalTo("foo")))
- * - * @param valueMatcher - * the matcher that must be satisfied by at least one value - */ - public static Matcher> hasValue(Matcher valueMatcher) { - return new IsMapContaining<>(anything(), valueMatcher); - } + /** + * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains + * at least one key that is equal to the specified key. + * For example: + *
assertThat(myMap, hasKey("bar"))
+ * + * @param key + * the key that satisfying maps must contain + */ + public static Matcher> hasKey(K key) + { + return new IsMapContaining<>(equalTo(key), anything()); + } - /** - * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains - * at least one value that is equal to the specified value. - * For example: - *
assertThat(myMap, hasValue("foo"))
- * - * @param value - * the value that satisfying maps must contain - */ - public static Matcher> hasValue(V value) { - return new IsMapContaining<>(anything(), equalTo(value)); - } + /** + * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains + * at least one value that satisfies the specified valueMatcher. + * For example: + *
assertThat(myMap, hasValue(equalTo("foo")))
+ * + * @param valueMatcher + * the matcher that must be satisfied by at least one value + */ + public static Matcher> hasValue(Matcher valueMatcher) + { + return new IsMapContaining<>(anything(), valueMatcher); + } + + /** + * Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains + * at least one value that is equal to the specified value. + * For example: + *
assertThat(myMap, hasValue("foo"))
+ * + * @param value + * the value that satisfying maps must contain + */ + public static Matcher> hasValue(V value) + { + return new IsMapContaining<>(anything(), equalTo(value)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java b/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java index 966d9ca2..6b52b71d 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java @@ -10,51 +10,56 @@ /** * Matches if map size satisfies a nested matcher. */ -public final class IsMapWithSize extends FeatureMatcher, Integer> { - @SuppressWarnings("WeakerAccess") - public IsMapWithSize(Matcher sizeMatcher) { - super(sizeMatcher, "a map with size", "map size"); - } - - @Override - protected Integer featureValueOf(Map actual) { - return actual.size(); - } - - /** - * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns - * a value that satisfies the specified matcher. - * For example: - *
assertThat(myMap, is(aMapWithSize(equalTo(2))))
- * - * @param sizeMatcher - * a matcher for the size of an examined {@link java.util.Map} - */ - public static Matcher> aMapWithSize(Matcher sizeMatcher) { - return new IsMapWithSize<>(sizeMatcher); - } - - /** - * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns - * a value equal to the specified size. - * For example: - *
assertThat(myMap, is(aMapWithSize(2)))
- * - * @param size - * the expected size of an examined {@link java.util.Map} - */ - public static Matcher> aMapWithSize(int size) { - return IsMapWithSize.aMapWithSize(equalTo(size)); - } - - /** - * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns - * zero. - * For example: - *
assertThat(myMap, is(anEmptyMap()))
- * - */ - public static Matcher> anEmptyMap() { - return IsMapWithSize.aMapWithSize(equalTo(0)); - } +public final class IsMapWithSize extends FeatureMatcher, Integer> +{ + @SuppressWarnings("WeakerAccess") + public IsMapWithSize(Matcher sizeMatcher) + { + super(sizeMatcher, "a map with size", "map size"); + } + + @Override + protected Integer featureValueOf(Map actual) + { + return actual.size(); + } + + /** + * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns + * a value that satisfies the specified matcher. + * For example: + *
assertThat(myMap, is(aMapWithSize(equalTo(2))))
+ * + * @param sizeMatcher + * a matcher for the size of an examined {@link java.util.Map} + */ + public static Matcher> aMapWithSize(Matcher sizeMatcher) + { + return new IsMapWithSize<>(sizeMatcher); + } + + /** + * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns + * a value equal to the specified size. + * For example: + *
assertThat(myMap, is(aMapWithSize(2)))
+ * + * @param size + * the expected size of an examined {@link java.util.Map} + */ + public static Matcher> aMapWithSize(int size) + { + return IsMapWithSize.aMapWithSize(equalTo(size)); + } + + /** + * Creates a matcher for {@link java.util.Map}s that matches when the size() method returns + * zero. + * For example: + *
assertThat(myMap, is(anEmptyMap()))
+ */ + public static Matcher> anEmptyMap() + { + return IsMapWithSize.aMapWithSize(equalTo(0)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java b/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java index cf522113..c6bfee50 100644 --- a/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java +++ b/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java @@ -8,171 +8,199 @@ import static java.lang.Integer.signum; -public final class ComparatorMatcherBuilder { +public final class ComparatorMatcherBuilder +{ + + private final Comparator comparator; + private final boolean includeComparatorInDescription; + + /** + * Creates a matcher factory for matchers of {@code Comparable}s. + * For example: + *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThanOrEqualTo(1))
+ */ + public static > ComparatorMatcherBuilder usingNaturalOrdering() + { + return new ComparatorMatcherBuilder(new Comparator() + { + @Override + public int compare(T o1, T o2) + { + return o1.compareTo(o2); + } + }, false); + } + + /** + * Creates a matcher factory for matchers of {@code Comparators}s of {@code T}. + * For example: + *
assertThat(5, comparedBy(new Comparator<Integer>() {
+   * public int compare(Integer o1, Integer o2) {
+   * return -o1.compareTo(o2);
+   * }
+   * }).lessThan(4))
+ */ + public static ComparatorMatcherBuilder comparedBy(Comparator comparator) + { + return new ComparatorMatcherBuilder(comparator, true); + } + + private ComparatorMatcherBuilder(Comparator comparator, boolean includeComparatorInDescription) + { + this.comparator = comparator; + this.includeComparatorInDescription = includeComparatorInDescription; + } + + private static final class ComparatorMatcher extends TypeSafeMatcher + { + private static final int LESS_THAN = -1; + private static final int GREATER_THAN = 1; + private static final int EQUAL = 0; private final Comparator comparator; + private final T expected; + private final int minCompare; + private final int maxCompare; private final boolean includeComparatorInDescription; - /** - * Creates a matcher factory for matchers of {@code Comparable}s. - * For example: - *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThanOrEqualTo(1))
- */ - public static > ComparatorMatcherBuilder usingNaturalOrdering() { - return new ComparatorMatcherBuilder(new Comparator() { - @Override - public int compare(T o1, T o2) { - return o1.compareTo(o2); - } - }, false); + private static final String[] comparisonDescriptions = { + "less than", + "equal to", + "greater than" + }; + + private ComparatorMatcher(Comparator comparator, T expected, int minCompare, int maxCompare, boolean includeComparatorInDescription) + { + this.comparator = comparator; + this.expected = expected; + this.minCompare = minCompare; + this.maxCompare = maxCompare; + this.includeComparatorInDescription = includeComparatorInDescription; } - /** - * Creates a matcher factory for matchers of {@code Comparators}s of {@code T}. - * For example: - *
assertThat(5, comparedBy(new Comparator<Integer>() {
-     * public int compare(Integer o1, Integer o2) {
-     * return -o1.compareTo(o2);
-     * }
-     * }).lessThan(4))
- */ - public static ComparatorMatcherBuilder comparedBy(Comparator comparator) { - return new ComparatorMatcherBuilder(comparator, true); + @Override + public boolean matchesSafely(T actual) + { + try + { + int compare = signum(comparator.compare(actual, expected)); + return minCompare <= compare && compare <= maxCompare; + } + catch (ClassCastException e) + { + return false; // type erasure means someone can shonk in a non-T :( + } } - private ComparatorMatcherBuilder(Comparator comparator, boolean includeComparatorInDescription) { - this.comparator = comparator; - this.includeComparatorInDescription = includeComparatorInDescription; + @Override + public void describeMismatchSafely(T actual, Description mismatchDescription) + { + mismatchDescription.appendValue(actual).appendText(" was ") + .appendText(asText(comparator.compare(actual, expected))) + .appendText(" ").appendValue(expected); + if (includeComparatorInDescription) + { + mismatchDescription.appendText(" when compared by ").appendValue(comparator); + } } - private static final class ComparatorMatcher extends TypeSafeMatcher { - private static final int LESS_THAN = -1; - private static final int GREATER_THAN = 1; - private static final int EQUAL = 0; - - private final Comparator comparator; - private final T expected; - private final int minCompare; - private final int maxCompare; - private final boolean includeComparatorInDescription; - - private static final String[] comparisonDescriptions = { - "less than", - "equal to", - "greater than" - }; - - private ComparatorMatcher(Comparator comparator, T expected, int minCompare, int maxCompare, boolean includeComparatorInDescription) { - this.comparator = comparator; - this.expected = expected; - this.minCompare = minCompare; - this.maxCompare = maxCompare; - this.includeComparatorInDescription = includeComparatorInDescription; - } - - @Override - public boolean matchesSafely(T actual) { - try { - int compare = signum(comparator.compare(actual, expected)); - return minCompare <= compare && compare <= maxCompare; - } catch (ClassCastException e) { - return false; // type erasure means someone can shonk in a non-T :( - } - } - - @Override - public void describeMismatchSafely(T actual, Description mismatchDescription) { - mismatchDescription.appendValue(actual).appendText(" was ") - .appendText(asText(comparator.compare(actual, expected))) - .appendText(" ").appendValue(expected); - if (includeComparatorInDescription) { - mismatchDescription.appendText(" when compared by ").appendValue(comparator); - } - } - - @Override - public void describeTo(Description description) { - description.appendText("a value ").appendText(asText(minCompare)); - if (minCompare != maxCompare) { - description.appendText(" or ").appendText(asText(maxCompare)); - } - description.appendText(" ").appendValue(expected); - if (includeComparatorInDescription) { - description.appendText(" when compared by ").appendValue(comparator); - } - } - - private static String asText(int comparison) { - return comparisonDescriptions[signum(comparison) + 1]; - } + @Override + public void describeTo(Description description) + { + description.appendText("a value ").appendText(asText(minCompare)); + if (minCompare != maxCompare) + { + description.appendText(" or ").appendText(asText(maxCompare)); + } + description.appendText(" ").appendValue(expected); + if (includeComparatorInDescription) + { + description.appendText(" when compared by ").appendValue(comparator); + } } - /** - * Creates a matcher of {@code T} object that matches when the examined object is - * equal to the specified value, as reported by the {@code Comparator} used to - * create this builder. - * For example: - *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().comparesEqualTo(1))
- * - * @param value the value which, when passed to the Comparator supplied to this builder, should return zero - */ - public Matcher comparesEqualTo(T value) { - return new ComparatorMatcher(comparator, value, ComparatorMatcher.EQUAL, ComparatorMatcher.EQUAL, includeComparatorInDescription); - } - - /** - * Creates a matcher of {@code T} object that matches when the examined object is - * greater than the specified value, as reported by the {@code Comparator} used to - * create this builder. - * For example: - *
assertThat(2, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().greaterThan(1))
- * - * @param value the value which, when passed to the Comparator supplied to this builder, should return greater - * than zero - */ - public Matcher greaterThan(T value) { - return new ComparatorMatcher(comparator, value, ComparatorMatcher.GREATER_THAN, ComparatorMatcher.GREATER_THAN, includeComparatorInDescription); - } - - /** - * Creates a matcher of {@code T} object that matches when the examined object is - * greater than or equal to the specified value, as reported by the {@code Comparator} used to - * create this builder. - * For example: - *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().greaterThanOrEqualTo(1))
- * - * @param value the value which, when passed to the Comparator supplied to this builder, should return greater - * than or equal to zero - */ - public Matcher greaterThanOrEqualTo(T value) { - return new ComparatorMatcher(comparator, value, ComparatorMatcher.EQUAL, ComparatorMatcher.GREATER_THAN, includeComparatorInDescription); - } - - /** - * Creates a matcher of {@code T} object that matches when the examined object is - * less than the specified value, as reported by the {@code Comparator} used to - * create this builder. - * For example: - *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThan(2))
- * - * @param value the value which, when passed to the Comparator supplied to this builder, should return less - * than zero - */ - public Matcher lessThan(T value) { - return new ComparatorMatcher(comparator, value, ComparatorMatcher.LESS_THAN, ComparatorMatcher.LESS_THAN, includeComparatorInDescription); - } - - /** - * Creates a matcher of {@code T} object that matches when the examined object is - * less than or equal to the specified value, as reported by the {@code Comparator} used to - * create this builder. - * For example: - *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThanOrEqualTo(1))
- * - * @param value the value which, when passed to the Comparator supplied to this builder, should return less - * than or equal to zero - */ - public Matcher lessThanOrEqualTo(T value) { - return new ComparatorMatcher(comparator, value, ComparatorMatcher.LESS_THAN, ComparatorMatcher.EQUAL, includeComparatorInDescription); + private static String asText(int comparison) + { + return comparisonDescriptions[signum(comparison) + 1]; } + } + + /** + * Creates a matcher of {@code T} object that matches when the examined object is + * equal to the specified value, as reported by the {@code Comparator} used to + * create this builder. + * For example: + *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().comparesEqualTo(1))
+ * + * @param value + * the value which, when passed to the Comparator supplied to this builder, should return zero + */ + public Matcher comparesEqualTo(T value) + { + return new ComparatorMatcher(comparator, value, ComparatorMatcher.EQUAL, ComparatorMatcher.EQUAL, includeComparatorInDescription); + } + + /** + * Creates a matcher of {@code T} object that matches when the examined object is + * greater than the specified value, as reported by the {@code Comparator} used to + * create this builder. + * For example: + *
assertThat(2, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().greaterThan(1))
+ * + * @param value + * the value which, when passed to the Comparator supplied to this builder, should return greater + * than zero + */ + public Matcher greaterThan(T value) + { + return new ComparatorMatcher(comparator, value, ComparatorMatcher.GREATER_THAN, ComparatorMatcher.GREATER_THAN, includeComparatorInDescription); + } + + /** + * Creates a matcher of {@code T} object that matches when the examined object is + * greater than or equal to the specified value, as reported by the {@code Comparator} used to + * create this builder. + * For example: + *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().greaterThanOrEqualTo(1))
+ * + * @param value + * the value which, when passed to the Comparator supplied to this builder, should return greater + * than or equal to zero + */ + public Matcher greaterThanOrEqualTo(T value) + { + return new ComparatorMatcher(comparator, value, ComparatorMatcher.EQUAL, ComparatorMatcher.GREATER_THAN, includeComparatorInDescription); + } + + /** + * Creates a matcher of {@code T} object that matches when the examined object is + * less than the specified value, as reported by the {@code Comparator} used to + * create this builder. + * For example: + *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThan(2))
+ * + * @param value + * the value which, when passed to the Comparator supplied to this builder, should return less + * than zero + */ + public Matcher lessThan(T value) + { + return new ComparatorMatcher(comparator, value, ComparatorMatcher.LESS_THAN, ComparatorMatcher.LESS_THAN, includeComparatorInDescription); + } + + /** + * Creates a matcher of {@code T} object that matches when the examined object is + * less than or equal to the specified value, as reported by the {@code Comparator} used to + * create this builder. + * For example: + *
assertThat(1, ComparatorMatcherBuilder.<Integer>usingNaturalOrdering().lessThanOrEqualTo(1))
+ * + * @param value + * the value which, when passed to the Comparator supplied to this builder, should return less + * than or equal to zero + */ + public Matcher lessThanOrEqualTo(T value) + { + return new ComparatorMatcher(comparator, value, ComparatorMatcher.LESS_THAN, ComparatorMatcher.EQUAL, includeComparatorInDescription); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/AllOf.java b/hamcrest/src/main/java/org/hamcrest/core/AllOf.java index b8c3faad..3b80b1c5 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/AllOf.java +++ b/hamcrest/src/main/java/org/hamcrest/core/AllOf.java @@ -10,52 +10,61 @@ * Calculates the logical conjunction of multiple matchers. Evaluation is shortcut, so * subsequent matchers are not called if an earlier matcher returns false. */ -public class AllOf extends DiagnosingMatcher { +public class AllOf extends DiagnosingMatcher +{ - private final Iterable> matchers; + private final Iterable> matchers; - @SafeVarargs - public AllOf(Matcher ... matchers) { - this(Arrays.asList(matchers)); - } + @SafeVarargs + public AllOf(Matcher... matchers) + { + this(Arrays.asList(matchers)); + } - public AllOf(Iterable> matchers) { - this.matchers = matchers; - } + public AllOf(Iterable> matchers) + { + this.matchers = matchers; + } - @Override - public boolean matches(Object o, Description mismatch) { - for (Matcher matcher : matchers) { - if (!matcher.matches(o)) { - mismatch.appendDescriptionOf(matcher).appendText(" "); - matcher.describeMismatch(o, mismatch); - return false; - } - } - return true; + @Override + public boolean matches(Object o, Description mismatch) + { + for (Matcher matcher : matchers) + { + if (!matcher.matches(o)) + { + mismatch.appendDescriptionOf(matcher).appendText(" "); + matcher.describeMismatch(o, mismatch); + return false; + } } + return true; + } - @Override - public void describeTo(Description description) { - description.appendList("(", " " + "and" + " ", ")", matchers); - } + @Override + public void describeTo(Description description) + { + description.appendList("(", " " + "and" + " ", ")", matchers); + } - /** - * Creates a matcher that matches if the examined object matches ALL of the specified matchers. - * For example: - *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
- */ - public static Matcher allOf(Iterable> matchers) { - return new AllOf<>(matchers); - } + /** + * Creates a matcher that matches if the examined object matches ALL of the specified matchers. + * For example: + *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
+ */ + public static Matcher allOf(Iterable> matchers) + { + return new AllOf<>(matchers); + } - /** - * Creates a matcher that matches if the examined object matches ALL of the specified matchers. - * For example: - *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
- */ - @SafeVarargs - public static Matcher allOf(Matcher... matchers) { - return allOf(Arrays.asList(matchers)); - } + /** + * Creates a matcher that matches if the examined object matches ALL of the specified matchers. + * For example: + *
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
+ */ + @SafeVarargs + public static Matcher allOf(Matcher... matchers) + { + return allOf(Arrays.asList(matchers)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java b/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java index 7a22c22e..3290568d 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java +++ b/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java @@ -9,43 +9,50 @@ * Calculates the logical disjunction of multiple matchers. Evaluation is shortcut, so * subsequent matchers are not called if an earlier matcher returns true. */ -public class AnyOf extends ShortcutCombination { - - @SafeVarargs - public AnyOf(Matcher ... matchers) { - this(Arrays.asList(matchers)); - } - - public AnyOf(Iterable> matchers) { - super(matchers); - } - - @Override - public boolean matches(Object o) { - return matches(o, true); - } - - @Override - public void describeTo(Description description) { - describeTo(description, "or"); - } - - /** - * Creates a matcher that matches if the examined object matches ANY of the specified matchers. - * For example: - *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
- */ - public static AnyOf anyOf(Iterable> matchers) { - return new AnyOf<>(matchers); - } - - /** - * Creates a matcher that matches if the examined object matches ANY of the specified matchers. - * For example: - *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
- */ - @SafeVarargs - public static AnyOf anyOf(Matcher... matchers) { - return anyOf(Arrays.asList(matchers)); - } +public class AnyOf extends ShortcutCombination +{ + + @SafeVarargs + public AnyOf(Matcher... matchers) + { + this(Arrays.asList(matchers)); + } + + public AnyOf(Iterable> matchers) + { + super(matchers); + } + + @Override + public boolean matches(Object o) + { + return matches(o, true); + } + + @Override + public void describeTo(Description description) + { + describeTo(description, "or"); + } + + /** + * Creates a matcher that matches if the examined object matches ANY of the specified matchers. + * For example: + *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
+ */ + public static AnyOf anyOf(Iterable> matchers) + { + return new AnyOf<>(matchers); + } + + /** + * Creates a matcher that matches if the examined object matches ANY of the specified matchers. + * For example: + *
assertThat("myValue", anyOf(startsWith("foo"), containsString("Val")))
+ */ + @SafeVarargs + public static AnyOf anyOf(Matcher... matchers) + { + return anyOf(Arrays.asList(matchers)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java b/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java index e37efce6..304c1644 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java @@ -6,16 +6,20 @@ import java.util.ArrayList; -public class CombinableMatcher extends TypeSafeDiagnosingMatcher { +public class CombinableMatcher extends TypeSafeDiagnosingMatcher +{ private final Matcher matcher; - public CombinableMatcher(Matcher matcher) { + public CombinableMatcher(Matcher matcher) + { this.matcher = matcher; } @Override - protected boolean matchesSafely(T item, Description mismatch) { - if (!matcher.matches(item)) { + protected boolean matchesSafely(T item, Description mismatch) + { + if (!matcher.matches(item)) + { matcher.describeMismatch(item, mismatch); return false; } @@ -23,19 +27,23 @@ protected boolean matchesSafely(T item, Description mismatch) { } @Override - public void describeTo(Description description) { + public void describeTo(Description description) + { description.appendDescriptionOf(matcher); } - public CombinableMatcher and(Matcher other) { + public CombinableMatcher and(Matcher other) + { return new CombinableMatcher<>(new AllOf<>(templatedListWith(other))); } - public CombinableMatcher or(Matcher other) { + public CombinableMatcher or(Matcher other) + { return new CombinableMatcher<>(new AnyOf<>(templatedListWith(other))); } - private ArrayList> templatedListWith(Matcher other) { + private ArrayList> templatedListWith(Matcher other) + { ArrayList> matchers = new ArrayList<>(); matchers.add(matcher); matchers.add(other); @@ -47,16 +55,22 @@ private ArrayList> templatedListWith(Matcher other * For example: *
assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ - public static CombinableBothMatcher both(Matcher matcher) { + public static CombinableBothMatcher both(Matcher matcher) + { return new CombinableBothMatcher<>(matcher); } - - public static final class CombinableBothMatcher { + + public static final class CombinableBothMatcher + { private final Matcher first; - public CombinableBothMatcher(Matcher matcher) { - this.first = matcher; + + public CombinableBothMatcher(Matcher matcher) + { + this.first = matcher; } - public CombinableMatcher and(Matcher other) { + + public CombinableMatcher and(Matcher other) + { return new CombinableMatcher<>(first).and(other); } } @@ -66,16 +80,22 @@ public CombinableMatcher and(Matcher other) { * For example: *
assertThat("fan", either(containsString("a")).or(containsString("b")))
*/ - public static CombinableEitherMatcher either(Matcher matcher) { + public static CombinableEitherMatcher either(Matcher matcher) + { return new CombinableEitherMatcher<>(matcher); } - - public static final class CombinableEitherMatcher { + + public static final class CombinableEitherMatcher + { private final Matcher first; - public CombinableEitherMatcher(Matcher matcher) { - this.first = matcher; + + public CombinableEitherMatcher(Matcher matcher) + { + this.first = matcher; } - public CombinableMatcher or(Matcher other) { + + public CombinableMatcher or(Matcher other) + { return new CombinableMatcher<>(first).or(other); } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java b/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java index 23876095..dbfbd5ff 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java +++ b/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java @@ -11,59 +11,67 @@ /** * Provides a custom description to another matcher. */ -public class DescribedAs extends BaseMatcher { - private final String descriptionTemplate; - private final Matcher matcher; - private final Object[] values; - - private final static Pattern ARG_PATTERN = Pattern.compile("%([0-9]+)"); - - public DescribedAs(String descriptionTemplate, Matcher matcher, Object[] values) { - this.descriptionTemplate = descriptionTemplate; - this.matcher = matcher; - this.values = values.clone(); - } - - @Override - public boolean matches(Object o) { - return matcher.matches(o); - } +public class DescribedAs extends BaseMatcher +{ + private final String descriptionTemplate; + private final Matcher matcher; + private final Object[] values; - @Override - public void describeTo(Description description) { - java.util.regex.Matcher arg = ARG_PATTERN.matcher(descriptionTemplate); - - int textStart = 0; - while (arg.find()) { - description.appendText(descriptionTemplate.substring(textStart, arg.start())); - description.appendValue(values[parseInt(arg.group(1))]); - textStart = arg.end(); - } - - if (textStart < descriptionTemplate.length()) { - description.appendText(descriptionTemplate.substring(textStart)); - } - } - - @Override - public void describeMismatch(Object item, Description description) { - matcher.describeMismatch(item, description); + private final static Pattern ARG_PATTERN = Pattern.compile("%([0-9]+)"); + + public DescribedAs(String descriptionTemplate, Matcher matcher, Object[] values) + { + this.descriptionTemplate = descriptionTemplate; + this.matcher = matcher; + this.values = values.clone(); + } + + @Override + public boolean matches(Object o) + { + return matcher.matches(o); + } + + @Override + public void describeTo(Description description) + { + java.util.regex.Matcher arg = ARG_PATTERN.matcher(descriptionTemplate); + + int textStart = 0; + while (arg.find()) + { + description.appendText(descriptionTemplate.substring(textStart, arg.start())); + description.appendValue(values[parseInt(arg.group(1))]); + textStart = arg.end(); } - /** - * Wraps an existing matcher, overriding its description with that specified. All other functions are - * delegated to the decorated matcher, including its mismatch description. - * For example: - *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
- * - * @param description - * the new description for the wrapped matcher - * @param matcher - * the matcher to wrap - * @param values - * optional values to insert into the tokenised description - */ - public static Matcher describedAs(String description, Matcher matcher, Object... values) { - return new DescribedAs(description, matcher, values); + if (textStart < descriptionTemplate.length()) + { + description.appendText(descriptionTemplate.substring(textStart)); } + } + + @Override + public void describeMismatch(Object item, Description description) + { + matcher.describeMismatch(item, description); + } + + /** + * Wraps an existing matcher, overriding its description with that specified. All other functions are + * delegated to the decorated matcher, including its mismatch description. + * For example: + *
describedAs("a big decimal equal to %0", equalTo(myBigDecimal), myBigDecimal.toPlainString())
+ * + * @param description + * the new description for the wrapped matcher + * @param matcher + * the matcher to wrap + * @param values + * optional values to insert into the tokenised description + */ + public static Matcher describedAs(String description, Matcher matcher, Object... values) + { + return new DescribedAs(description, matcher, values); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/Every.java b/hamcrest/src/main/java/org/hamcrest/core/Every.java index 988758b1..bab0da10 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/Every.java +++ b/hamcrest/src/main/java/org/hamcrest/core/Every.java @@ -4,41 +4,48 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; -public class Every extends TypeSafeDiagnosingMatcher> { - private final Matcher matcher; +public class Every extends TypeSafeDiagnosingMatcher> +{ + private final Matcher matcher; - public Every(Matcher matcher) { - this.matcher= matcher; - } + public Every(Matcher matcher) + { + this.matcher = matcher; + } - @Override - public boolean matchesSafely(Iterable collection, Description mismatchDescription) { - for (T t : collection) { - if (!matcher.matches(t)) { - mismatchDescription.appendText("an item "); - matcher.describeMismatch(t, mismatchDescription); - return false; - } - } - return true; + @Override + public boolean matchesSafely(Iterable collection, Description mismatchDescription) + { + for (T t : collection) + { + if (!matcher.matches(t)) + { + mismatchDescription.appendText("an item "); + matcher.describeMismatch(t, mismatchDescription); + return false; + } } + return true; + } - @Override - public void describeTo(Description description) { - description.appendText("every item is ").appendDescriptionOf(matcher); - } + @Override + public void describeTo(Description description) + { + description.appendText("every item is ").appendDescriptionOf(matcher); + } - /** - * Creates a matcher for {@link Iterable}s that only matches when a single pass over the - * examined {@link Iterable} yields items that are all matched by the specified - * itemMatcher. - * For example: - *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
- * - * @param itemMatcher - * the matcher to apply to every item provided by the examined {@link Iterable} - */ - public static Matcher> everyItem(final Matcher itemMatcher) { - return new Every<>(itemMatcher); - } + /** + * Creates a matcher for {@link Iterable}s that only matches when a single pass over the + * examined {@link Iterable} yields items that are all matched by the specified + * itemMatcher. + * For example: + *
assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))
+ * + * @param itemMatcher + * the matcher to apply to every item provided by the examined {@link Iterable} + */ + public static Matcher> everyItem(final Matcher itemMatcher) + { + return new Every<>(itemMatcher); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/Is.java b/hamcrest/src/main/java/org/hamcrest/core/Is.java index 5264e89d..cf9e915b 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/Is.java +++ b/hamcrest/src/main/java/org/hamcrest/core/Is.java @@ -9,66 +9,71 @@ /** * Decorates another Matcher, retaining the behaviour but allowing tests * to be slightly more expressive. - * + *

* For example: assertThat(cheese, equalTo(smelly)) - * vs. assertThat(cheese, is(equalTo(smelly))) + * vs. assertThat(cheese, is(equalTo(smelly))) */ -public class Is extends BaseMatcher { - private final Matcher matcher; +public class Is extends BaseMatcher +{ + private final Matcher matcher; - public Is(Matcher matcher) { - this.matcher = matcher; - } + public Is(Matcher matcher) + { + this.matcher = matcher; + } - @Override - public boolean matches(Object arg) { - return matcher.matches(arg); - } + @Override + public boolean matches(Object arg) + { + return matcher.matches(arg); + } - @Override - public void describeTo(Description description) { - description.appendText("is ").appendDescriptionOf(matcher); - } + @Override + public void describeTo(Description description) + { + description.appendText("is ").appendDescriptionOf(matcher); + } - @Override - public void describeMismatch(Object item, Description mismatchDescription) { - matcher.describeMismatch(item, mismatchDescription); - } + @Override + public void describeMismatch(Object item, Description mismatchDescription) + { + matcher.describeMismatch(item, mismatchDescription); + } - /** - * Decorates another Matcher, retaining its behaviour, but allowing tests - * to be slightly more expressive. - * For example: - *

assertThat(cheese, is(equalTo(smelly)))
- * instead of: - *
assertThat(cheese, equalTo(smelly))
- * - */ - public static Matcher is(Matcher matcher) { - return new Is<>(matcher); - } + /** + * Decorates another Matcher, retaining its behaviour, but allowing tests + * to be slightly more expressive. + * For example: + *
assertThat(cheese, is(equalTo(smelly)))
+ * instead of: + *
assertThat(cheese, equalTo(smelly))
+ */ + public static Matcher is(Matcher matcher) + { + return new Is<>(matcher); + } - /** - * A shortcut to the frequently used is(equalTo(x)). - * For example: - *
assertThat(cheese, is(smelly))
- * instead of: - *
assertThat(cheese, is(equalTo(smelly)))
- * - */ - public static Matcher is(T value) { - return is(equalTo(value)); - } + /** + * A shortcut to the frequently used is(equalTo(x)). + * For example: + *
assertThat(cheese, is(smelly))
+ * instead of: + *
assertThat(cheese, is(equalTo(smelly)))
+ */ + public static Matcher is(T value) + { + return is(equalTo(value)); + } - /** - * A shortcut to the frequently used is(instanceOf(SomeClass.class)). - * For example: - *
assertThat(cheese, isA(Cheddar.class))
- * instead of: - *
assertThat(cheese, is(instanceOf(Cheddar.class)))
- * - */ - public static Matcher isA(Class type) { - return is(IsInstanceOf.instanceOf(type)); - } + /** + * A shortcut to the frequently used is(instanceOf(SomeClass.class)). + * For example: + *
assertThat(cheese, isA(Cheddar.class))
+ * instead of: + *
assertThat(cheese, is(instanceOf(Cheddar.class)))
+ */ + public static Matcher isA(Class type) + { + return is(IsInstanceOf.instanceOf(type)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java b/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java index 94943dc0..a4f85323 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java @@ -8,41 +8,50 @@ /** * A matcher that always returns true. */ -public class IsAnything extends BaseMatcher { - - private final String message; - - public IsAnything() { - this("ANYTHING"); - } - - public IsAnything(String message) { - this.message = message; - } - - @Override - public boolean matches(Object o) { - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(message); - } - - /** - * Creates a matcher that always matches, regardless of the examined object. - */ - public static Matcher anything() { return new IsAnything<>(); } - - /** - * Creates a matcher that always matches, regardless of the examined object, but describes - * itself with the specified {@link String}. - * - * @param description - * a meaningful {@link String} used when describing itself - */ - public static Matcher anything(String description) { - return new IsAnything<>(description); - } +public class IsAnything extends BaseMatcher +{ + + private final String message; + + public IsAnything() + { + this("ANYTHING"); + } + + public IsAnything(String message) + { + this.message = message; + } + + @Override + public boolean matches(Object o) + { + return true; + } + + @Override + public void describeTo(Description description) + { + description.appendText(message); + } + + /** + * Creates a matcher that always matches, regardless of the examined object. + */ + public static Matcher anything() + { + return new IsAnything<>(); + } + + /** + * Creates a matcher that always matches, regardless of the examined object, but describes + * itself with the specified {@link String}. + * + * @param description + * a meaningful {@link String} used when describing itself + */ + public static Matcher anything(String description) + { + return new IsAnything<>(description); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java b/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java index b54b6aa9..7ff90b8e 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java @@ -8,93 +8,97 @@ * @deprecated As of release 2.1, replaced by {@link IsIterableContaining}. */ @Deprecated -public class IsCollectionContaining extends TypeSafeDiagnosingMatcher> { - private final IsIterableContaining delegate; +public class IsCollectionContaining extends TypeSafeDiagnosingMatcher> +{ + private final IsIterableContaining delegate; - public IsCollectionContaining(Matcher elementMatcher) { - this.delegate = new IsIterableContaining<>(elementMatcher); - } + public IsCollectionContaining(Matcher elementMatcher) + { + this.delegate = new IsIterableContaining<>(elementMatcher); + } - @Override - protected boolean matchesSafely(Iterable collection, Description mismatchDescription) { - return delegate.matchesSafely(collection, mismatchDescription); - } + @Override + protected boolean matchesSafely(Iterable collection, Description mismatchDescription) + { + return delegate.matchesSafely(collection, mismatchDescription); + } - @Override - public void describeTo(Description description) { - delegate.describeTo(description); - } + @Override + public void describeTo(Description description) + { + delegate.describeTo(description); + } - - /** - * Creates a matcher for {@link Iterable}s that only matches when a single pass over the - * examined {@link Iterable} yields at least one item that is matched by the specified - * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} - * will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
- * - * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItem(Matcher)}. - * - * @param itemMatcher - * the matcher to apply to items provided by the examined {@link Iterable} - */ - public static Matcher> hasItem(Matcher itemMatcher) { - return IsIterableContaining.hasItem(itemMatcher); - } - /** - * Creates a matcher for {@link Iterable}s that only matches when a single pass over the - * examined {@link Iterable} yields at least one item that is equal to the specified - * item. Whilst matching, the traversal of the examined {@link Iterable} - * will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
- * - * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItem(Object)}. - * - * @param item - * the item to compare against the items provided by the examined {@link Iterable} - */ - public static Matcher> hasItem(T item) { - // Doesn't forward to hasItem() method so compiler can sort out generics. - return IsIterableContaining.hasItem(item); - } + /** + * Creates a matcher for {@link Iterable}s that only matches when a single pass over the + * examined {@link Iterable} yields at least one item that is matched by the specified + * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} + * will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
+ * + * @param itemMatcher + * the matcher to apply to items provided by the examined {@link Iterable} + * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItem(Matcher)}. + */ + public static Matcher> hasItem(Matcher itemMatcher) + { + return IsIterableContaining.hasItem(itemMatcher); + } - /** - * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the - * examined {@link Iterable} yield at least one item that is matched by the corresponding - * matcher from the specified itemMatchers. Whilst matching, each traversal of - * the examined {@link Iterable} will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
- * - * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Matcher[])}}. - * - * @param itemMatchers - * the matchers to apply to items provided by the examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> hasItems(Matcher... itemMatchers) { - return IsIterableContaining.hasItems(itemMatchers); - } - - /** - * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the - * examined {@link Iterable} yield at least one item that is equal to the corresponding - * item from the specified items. Whilst matching, each traversal of the - * examined {@link Iterable} will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
- * - * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Object[])}}. - * - * @param items - * the items to compare against the items provided by the examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> hasItems(T... items) { - return IsIterableContaining.hasItems(items); - } + /** + * Creates a matcher for {@link Iterable}s that only matches when a single pass over the + * examined {@link Iterable} yields at least one item that is equal to the specified + * item. Whilst matching, the traversal of the examined {@link Iterable} + * will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
+ * + * @param item + * the item to compare against the items provided by the examined {@link Iterable} + * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItem(Object)}. + */ + public static Matcher> hasItem(T item) + { + // Doesn't forward to hasItem() method so compiler can sort out generics. + return IsIterableContaining.hasItem(item); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the + * examined {@link Iterable} yield at least one item that is matched by the corresponding + * matcher from the specified itemMatchers. Whilst matching, each traversal of + * the examined {@link Iterable} will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
+ * + * @param itemMatchers + * the matchers to apply to items provided by the examined {@link Iterable} + * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Matcher[])}}. + */ + @SafeVarargs + public static Matcher> hasItems(Matcher... itemMatchers) + { + return IsIterableContaining.hasItems(itemMatchers); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the + * examined {@link Iterable} yield at least one item that is equal to the corresponding + * item from the specified items. Whilst matching, each traversal of the + * examined {@link Iterable} will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
+ * + * @param items + * the items to compare against the items provided by the examined {@link Iterable} + * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Object[])}}. + */ + @SafeVarargs + public static Matcher> hasItems(T... items) + { + return IsIterableContaining.hasItems(items); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java b/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java index 582c630f..b43ae587 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java @@ -11,87 +11,101 @@ * Is the value equal to another value, as tested by the * {@link java.lang.Object#equals} invokedMethod? */ -public class IsEqual extends BaseMatcher { - private final Object expectedValue; +public class IsEqual extends BaseMatcher +{ + private final Object expectedValue; - public IsEqual(T equalArg) { - expectedValue = equalArg; - } + public IsEqual(T equalArg) + { + expectedValue = equalArg; + } - @Override - public boolean matches(Object actualValue) { - return areEqual(actualValue, expectedValue); - } + @Override + public boolean matches(Object actualValue) + { + return areEqual(actualValue, expectedValue); + } - @Override - public void describeTo(Description description) { - description.appendValue(expectedValue); - } + @Override + public void describeTo(Description description) + { + description.appendValue(expectedValue); + } - private static boolean areEqual(Object actual, Object expected) { - if (actual == null) { - return expected == null; - } - - if (expected != null && isArray(actual)) { - return isArray(expected) && areArraysEqual(actual, expected); - } - - return actual.equals(expected); + private static boolean areEqual(Object actual, Object expected) + { + if (actual == null) + { + return expected == null; } - private static boolean areArraysEqual(Object actualArray, Object expectedArray) { - return areArrayLengthsEqual(actualArray, expectedArray) && areArrayElementsEqual(actualArray, expectedArray); + if (expected != null && isArray(actual)) + { + return isArray(expected) && areArraysEqual(actual, expected); } - private static boolean areArrayLengthsEqual(Object actualArray, Object expectedArray) { - return Array.getLength(actualArray) == Array.getLength(expectedArray); - } + return actual.equals(expected); + } - private static boolean areArrayElementsEqual(Object actualArray, Object expectedArray) { - for (int i = 0; i < Array.getLength(actualArray); i++) { - if (!areEqual(Array.get(actualArray, i), Array.get(expectedArray, i))) { - return false; - } - } - return true; - } + private static boolean areArraysEqual(Object actualArray, Object expectedArray) + { + return areArrayLengthsEqual(actualArray, expectedArray) && areArrayElementsEqual(actualArray, expectedArray); + } - private static boolean isArray(Object o) { - return o.getClass().isArray(); - } + private static boolean areArrayLengthsEqual(Object actualArray, Object expectedArray) + { + return Array.getLength(actualArray) == Array.getLength(expectedArray); + } - /** - * Creates a matcher that matches when the examined object is logically equal to the specified - * operand, as determined by calling the {@link java.lang.Object#equals} method on - * the examined object. - * - *

If the specified operand is null then the created matcher will only match if - * the examined object's equals method returns true when passed a - * null (which would be a violation of the equals contract), unless the - * examined object itself is null, in which case the matcher will return a positive - * match.

- * - *

The created matcher provides a special behaviour when examining Arrays, whereby - * it will match if both the operand and the examined object are arrays of the same length and - * contain items that are equal to each other (according to the above rules) in the same - * indexes.

- * For example: - *
-     * assertThat("foo", equalTo("foo"));
-     * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
-     * 
- * - */ - public static Matcher equalTo(T operand) { - return new IsEqual<>(operand); + private static boolean areArrayElementsEqual(Object actualArray, Object expectedArray) + { + for (int i = 0; i < Array.getLength(actualArray); i++) + { + if (!areEqual(Array.get(actualArray, i), Array.get(expectedArray, i))) + { + return false; + } } + return true; + } - /** - * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being - * compared to be of the same static type. - */ - public static Matcher equalToObject(Object operand) { - return new IsEqual<>(operand); - } + private static boolean isArray(Object o) + { + return o.getClass().isArray(); + } + + /** + * Creates a matcher that matches when the examined object is logically equal to the specified + * operand, as determined by calling the {@link java.lang.Object#equals} method on + * the examined object. + * + *

If the specified operand is null then the created matcher will only match if + * the examined object's equals method returns true when passed a + * null (which would be a violation of the equals contract), unless the + * examined object itself is null, in which case the matcher will return a positive + * match.

+ * + *

The created matcher provides a special behaviour when examining Arrays, whereby + * it will match if both the operand and the examined object are arrays of the same length and + * contain items that are equal to each other (according to the above rules) in the same + * indexes.

+ * For example: + *
+   * assertThat("foo", equalTo("foo"));
+   * assertThat(new String[] {"foo", "bar"}, equalTo(new String[] {"foo", "bar"}));
+   * 
+ */ + public static Matcher equalTo(T operand) + { + return new IsEqual<>(operand); + } + + /** + * Creates an {@link org.hamcrest.core.IsEqual} matcher that does not enforce the values being + * compared to be of the same static type. + */ + public static Matcher equalToObject(Object operand) + { + return new IsEqual<>(operand); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java b/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java index 5a508c9b..4f660560 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java @@ -9,83 +9,115 @@ * Tests whether the value is an instance of a class. * Classes of basic types will be converted to the relevant "Object" classes */ -public class IsInstanceOf extends DiagnosingMatcher { - private final Class expectedClass; - private final Class matchableClass; +public class IsInstanceOf extends DiagnosingMatcher +{ + private final Class expectedClass; + private final Class matchableClass; - /** - * Creates a new instance of IsInstanceOf - * - * @param expectedClass The predicate evaluates to true for instances of this class - * or one of its subclasses. - */ - public IsInstanceOf(Class expectedClass) { - this.expectedClass = expectedClass; - this.matchableClass = matchableClass(expectedClass); - } + /** + * Creates a new instance of IsInstanceOf + * + * @param expectedClass + * The predicate evaluates to true for instances of this class + * or one of its subclasses. + */ + public IsInstanceOf(Class expectedClass) + { + this.expectedClass = expectedClass; + this.matchableClass = matchableClass(expectedClass); + } - private static Class matchableClass(Class expectedClass) { - if (boolean.class.equals(expectedClass)) return Boolean.class; - if (byte.class.equals(expectedClass)) return Byte.class; - if (char.class.equals(expectedClass)) return Character.class; - if (double.class.equals(expectedClass)) return Double.class; - if (float.class.equals(expectedClass)) return Float.class; - if (int.class.equals(expectedClass)) return Integer.class; - if (long.class.equals(expectedClass)) return Long.class; - if (short.class.equals(expectedClass)) return Short.class; - return expectedClass; + private static Class matchableClass(Class expectedClass) + { + if (boolean.class.equals(expectedClass)) + { + return Boolean.class; } - - @Override - protected boolean matches(Object item, Description mismatch) { - if (null == item) { - mismatch.appendText("null"); - return false; - } - - if (!matchableClass.isInstance(item)) { - mismatch.appendValue(item).appendText(" is a " + item.getClass().getName()); - return false; - } - - return true; + if (byte.class.equals(expectedClass)) + { + return Byte.class; } - - @Override - public void describeTo(Description description) { - description.appendText("an instance of ").appendText(expectedClass.getName()); + if (char.class.equals(expectedClass)) + { + return Character.class; + } + if (double.class.equals(expectedClass)) + { + return Double.class; + } + if (float.class.equals(expectedClass)) + { + return Float.class; + } + if (int.class.equals(expectedClass)) + { + return Integer.class; + } + if (long.class.equals(expectedClass)) + { + return Long.class; } + if (short.class.equals(expectedClass)) + { + return Short.class; + } + return expectedClass; + } - /** - * Creates a matcher that matches when the examined object is an instance of the specified type, - * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the - * the examined object. - * - *

The created matcher assumes no relationship between specified type and the examined object.

- * For example: - *
assertThat(new Canoe(), instanceOf(Paddlable.class));
- * - */ - @SuppressWarnings("unchecked") - public static Matcher instanceOf(Class type) { - return (Matcher) new IsInstanceOf(type); + @Override + protected boolean matches(Object item, Description mismatch) + { + if (null == item) + { + mismatch.appendText("null"); + return false; } - - /** - * Creates a matcher that matches when the examined object is an instance of the specified type, - * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the - * the examined object. - * - *

The created matcher forces a relationship between specified type and the examined object, and should be - * used when it is necessary to make generics conform, for example in the JMock clause - * with(any(Thing.class))

- * For example: - *
assertThat(new Canoe(), instanceOf(Canoe.class));
- * - */ - @SuppressWarnings("unchecked") - public static Matcher any(Class type) { - return (Matcher) new IsInstanceOf(type); + + if (!matchableClass.isInstance(item)) + { + mismatch.appendValue(item).appendText(" is a " + item.getClass().getName()); + return false; } + return true; + } + + @Override + public void describeTo(Description description) + { + description.appendText("an instance of ").appendText(expectedClass.getName()); + } + + /** + * Creates a matcher that matches when the examined object is an instance of the specified type, + * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the + * the examined object. + * + *

The created matcher assumes no relationship between specified type and the examined object.

+ * For example: + *
assertThat(new Canoe(), instanceOf(Paddlable.class));
+ */ + @SuppressWarnings("unchecked") + public static Matcher instanceOf(Class type) + { + return (Matcher) new IsInstanceOf(type); + } + + /** + * Creates a matcher that matches when the examined object is an instance of the specified type, + * as determined by calling the {@link java.lang.Class#isInstance(Object)} method on that type, passing the + * the examined object. + * + *

The created matcher forces a relationship between specified type and the examined object, and should be + * used when it is necessary to make generics conform, for example in the JMock clause + * with(any(Thing.class))

+ * For example: + *
assertThat(new Canoe(), instanceOf(Canoe.class));
+ */ + @SuppressWarnings("unchecked") + public static Matcher any(Class type) + { + return (Matcher) new IsInstanceOf(type); + } + } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java b/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java index 67e776b0..ac3f43d1 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java @@ -10,124 +10,140 @@ import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; -public class IsIterableContaining extends TypeSafeDiagnosingMatcher> { - private final Matcher elementMatcher; +public class IsIterableContaining extends TypeSafeDiagnosingMatcher> +{ + private final Matcher elementMatcher; - public IsIterableContaining(Matcher elementMatcher) { - this.elementMatcher = elementMatcher; - } + public IsIterableContaining(Matcher elementMatcher) + { + this.elementMatcher = elementMatcher; + } - @Override - protected boolean matchesSafely(Iterable collection, Description mismatchDescription) { - if (isEmpty(collection)) { - mismatchDescription.appendText("was empty"); - return false; - } - - for (Object item : collection) { - if (elementMatcher.matches(item)) { - return true; - } - } - - mismatchDescription.appendText("mismatches were: ["); - boolean isPastFirst = false; - for (Object item : collection) { - if (isPastFirst) { - mismatchDescription.appendText(", "); - } - elementMatcher.describeMismatch(item, mismatchDescription); - isPastFirst = true; - } - mismatchDescription.appendText("]"); - return false; + @Override + protected boolean matchesSafely(Iterable collection, Description mismatchDescription) + { + if (isEmpty(collection)) + { + mismatchDescription.appendText("was empty"); + return false; } - private boolean isEmpty(Iterable iterable) { - return ! iterable.iterator().hasNext(); + for (Object item : collection) + { + if (elementMatcher.matches(item)) + { + return true; + } } - @Override - public void describeTo(Description description) { - description - .appendText("a collection containing ") - .appendDescriptionOf(elementMatcher); + mismatchDescription.appendText("mismatches were: ["); + boolean isPastFirst = false; + for (Object item : collection) + { + if (isPastFirst) + { + mismatchDescription.appendText(", "); + } + elementMatcher.describeMismatch(item, mismatchDescription); + isPastFirst = true; } + mismatchDescription.appendText("]"); + return false; + } - - /** - * Creates a matcher for {@link Iterable}s that only matches when a single pass over the - * examined {@link Iterable} yields at least one item that is matched by the specified - * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} - * will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
- * - * @param itemMatcher - * the matcher to apply to items provided by the examined {@link Iterable} - */ - public static Matcher> hasItem(Matcher itemMatcher) { - return new IsIterableContaining<>(itemMatcher); - } + private boolean isEmpty(Iterable iterable) + { + return !iterable.iterator().hasNext(); + } - /** - * Creates a matcher for {@link Iterable}s that only matches when a single pass over the - * examined {@link Iterable} yields at least one item that is equal to the specified - * item. Whilst matching, the traversal of the examined {@link Iterable} - * will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
- * - * @param item - * the item to compare against the items provided by the examined {@link Iterable} - */ - public static Matcher> hasItem(T item) { - // Doesn't forward to hasItem() method so compiler can sort out generics. - return new IsIterableContaining<>(equalTo(item)); - } + @Override + public void describeTo(Description description) + { + description + .appendText("a collection containing ") + .appendDescriptionOf(elementMatcher); + } + + + /** + * Creates a matcher for {@link Iterable}s that only matches when a single pass over the + * examined {@link Iterable} yields at least one item that is matched by the specified + * itemMatcher. Whilst matching, the traversal of the examined {@link Iterable} + * will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))
+ * + * @param itemMatcher + * the matcher to apply to items provided by the examined {@link Iterable} + */ + public static Matcher> hasItem(Matcher itemMatcher) + { + return new IsIterableContaining<>(itemMatcher); + } - /** - * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the - * examined {@link Iterable} yield at least one item that is matched by the corresponding - * matcher from the specified itemMatchers. Whilst matching, each traversal of - * the examined {@link Iterable} will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
- * - * @param itemMatchers - * the matchers to apply to items provided by the examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> hasItems(Matcher... itemMatchers) { - List>> all = new ArrayList<>(itemMatchers.length); - - for (Matcher elementMatcher : itemMatchers) { - // Doesn't forward to hasItem() method so compiler can sort out generics. - all.add(new IsIterableContaining<>(elementMatcher)); - } - - return allOf(all); + /** + * Creates a matcher for {@link Iterable}s that only matches when a single pass over the + * examined {@link Iterable} yields at least one item that is equal to the specified + * item. Whilst matching, the traversal of the examined {@link Iterable} + * will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))
+ * + * @param item + * the item to compare against the items provided by the examined {@link Iterable} + */ + public static Matcher> hasItem(T item) + { + // Doesn't forward to hasItem() method so compiler can sort out generics. + return new IsIterableContaining<>(equalTo(item)); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the + * examined {@link Iterable} yield at least one item that is matched by the corresponding + * matcher from the specified itemMatchers. Whilst matching, each traversal of + * the examined {@link Iterable} will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems(endsWith("z"), endsWith("o")))
+ * + * @param itemMatchers + * the matchers to apply to items provided by the examined {@link Iterable} + */ + @SafeVarargs + public static Matcher> hasItems(Matcher... itemMatchers) + { + List>> all = new ArrayList<>(itemMatchers.length); + + for (Matcher elementMatcher : itemMatchers) + { + // Doesn't forward to hasItem() method so compiler can sort out generics. + all.add(new IsIterableContaining<>(elementMatcher)); } - - /** - * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the - * examined {@link Iterable} yield at least one item that is equal to the corresponding - * item from the specified items. Whilst matching, each traversal of the - * examined {@link Iterable} will stop as soon as a matching item is found. - * For example: - *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
- * - * @param items - * the items to compare against the items provided by the examined {@link Iterable} - */ - @SafeVarargs - public static Matcher> hasItems(T... items) { - List>> all = new ArrayList<>(items.length); - for (T item : items) { - all.add(hasItem(item)); - } - - return allOf(all); + + return allOf(all); + } + + /** + * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the + * examined {@link Iterable} yield at least one item that is equal to the corresponding + * item from the specified items. Whilst matching, each traversal of the + * examined {@link Iterable} will stop as soon as a matching item is found. + * For example: + *
assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))
+ * + * @param items + * the items to compare against the items provided by the examined {@link Iterable} + */ + @SafeVarargs + public static Matcher> hasItems(T... items) + { + List>> all = new ArrayList<>(items.length); + for (T item : items) + { + all.add(hasItem(item)); } + return allOf(all); + } + } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsNot.java b/hamcrest/src/main/java/org/hamcrest/core/IsNot.java index d5cf9c06..d024eec2 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsNot.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsNot.java @@ -10,48 +10,54 @@ /** * Calculates the logical negation of a matcher. */ -public class IsNot extends BaseMatcher { - private final Matcher matcher; - - public IsNot(Matcher matcher) { - this.matcher = matcher; - } - - @Override - public boolean matches(Object arg) { - return !matcher.matches(arg); - } - - @Override - public void describeTo(Description description) { - description.appendText("not ").appendDescriptionOf(matcher); - } - - - /** - * Creates a matcher that wraps an existing matcher, but inverts the logic by which - * it will match. - * For example: - *
assertThat(cheese, is(not(equalTo(smelly))))
- * - * @param matcher - * the matcher whose sense should be inverted - */ - public static Matcher not(Matcher matcher) { - return new IsNot(matcher); - } - - /** - * A shortcut to the frequently used not(equalTo(x)). - * For example: - *
assertThat(cheese, is(not(smelly)))
- * instead of: - *
assertThat(cheese, is(not(equalTo(smelly))))
- * - * @param value - * the value that any examined object should not equal - */ - public static Matcher not(T value) { - return not(equalTo(value)); - } +public class IsNot extends BaseMatcher +{ + private final Matcher matcher; + + public IsNot(Matcher matcher) + { + this.matcher = matcher; + } + + @Override + public boolean matches(Object arg) + { + return !matcher.matches(arg); + } + + @Override + public void describeTo(Description description) + { + description.appendText("not ").appendDescriptionOf(matcher); + } + + + /** + * Creates a matcher that wraps an existing matcher, but inverts the logic by which + * it will match. + * For example: + *
assertThat(cheese, is(not(equalTo(smelly))))
+ * + * @param matcher + * the matcher whose sense should be inverted + */ + public static Matcher not(Matcher matcher) + { + return new IsNot(matcher); + } + + /** + * A shortcut to the frequently used not(equalTo(x)). + * For example: + *
assertThat(cheese, is(not(smelly)))
+ * instead of: + *
assertThat(cheese, is(not(equalTo(smelly))))
+ * + * @param value + * the value that any examined object should not equal + */ + public static Matcher not(T value) + { + return not(equalTo(value)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsNull.java b/hamcrest/src/main/java/org/hamcrest/core/IsNull.java index 9ebf080f..9bef8391 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsNull.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsNull.java @@ -9,66 +9,70 @@ /** * Is the value null? */ -public class IsNull extends BaseMatcher { - @Override - public boolean matches(Object o) { - return o == null; - } +public class IsNull extends BaseMatcher +{ + @Override + public boolean matches(Object o) + { + return o == null; + } - @Override - public void describeTo(Description description) { - description.appendText("null"); - } + @Override + public void describeTo(Description description) + { + description.appendText("null"); + } - /** - * Creates a matcher that matches if examined object is null. - * For example: - *
assertThat(cheese, is(nullValue())
- * - */ - public static Matcher nullValue() { - return new IsNull(); - } + /** + * Creates a matcher that matches if examined object is null. + * For example: + *
assertThat(cheese, is(nullValue())
+ */ + public static Matcher nullValue() + { + return new IsNull(); + } - /** - * A shortcut to the frequently used not(nullValue()). - * For example: - *
assertThat(cheese, is(notNullValue()))
- * instead of: - *
assertThat(cheese, is(not(nullValue())))
- * - */ - public static Matcher notNullValue() { - return not(nullValue()); - } + /** + * A shortcut to the frequently used not(nullValue()). + * For example: + *
assertThat(cheese, is(notNullValue()))
+ * instead of: + *
assertThat(cheese, is(not(nullValue())))
+ */ + public static Matcher notNullValue() + { + return not(nullValue()); + } - /** - * Creates a matcher that matches if examined object is null. Accepts a - * single dummy argument to facilitate type inference. - * For example: - *
assertThat(cheese, is(nullValue(Cheese.class))
- * - * @param type - * dummy parameter used to infer the generic type of the returned matcher - */ - public static Matcher nullValue(Class type) { - return new IsNull(); - } + /** + * Creates a matcher that matches if examined object is null. Accepts a + * single dummy argument to facilitate type inference. + * For example: + *
assertThat(cheese, is(nullValue(Cheese.class))
+ * + * @param type + * dummy parameter used to infer the generic type of the returned matcher + */ + public static Matcher nullValue(Class type) + { + return new IsNull(); + } - /** - * A shortcut to the frequently used not(nullValue(X.class)). Accepts a - * single dummy argument to facilitate type inference.. - * For example: - *
assertThat(cheese, is(notNullValue(X.class)))
- * instead of: - *
assertThat(cheese, is(not(nullValue(X.class))))
- * - * @param type - * dummy parameter used to infer the generic type of the returned matcher - * - */ - public static Matcher notNullValue(Class type) { - return not(nullValue(type)); - } + /** + * A shortcut to the frequently used not(nullValue(X.class)). Accepts a + * single dummy argument to facilitate type inference.. + * For example: + *
assertThat(cheese, is(notNullValue(X.class)))
+ * instead of: + *
assertThat(cheese, is(not(nullValue(X.class))))
+ * + * @param type + * dummy parameter used to infer the generic type of the returned matcher + */ + public static Matcher notNullValue(Class type) + { + return not(nullValue(type)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/IsSame.java b/hamcrest/src/main/java/org/hamcrest/core/IsSame.java index cbc3971b..6d618f17 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsSame.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsSame.java @@ -8,44 +8,50 @@ /** * Is the value the same object as another value? */ -public class IsSame extends BaseMatcher { - private final T object; - - public IsSame(T object) { - this.object = object; - } - - @Override - public boolean matches(Object arg) { - return arg == object; - } - - @Override - public void describeTo(Description description) { - description.appendText("sameInstance(") - .appendValue(object) - .appendText(")"); - } - - /** - * Creates a matcher that matches only when the examined object is the same instance as - * the specified target object. - * - * @param target - * the target instance against which others should be assessed - */ - public static Matcher sameInstance(T target) { - return new IsSame(target); - } - - /** - * Creates a matcher that matches only when the examined object is the same instance as - * the specified target object. - * - * @param target - * the target instance against which others should be assessed - */ - public static Matcher theInstance(T target) { - return new IsSame(target); - } +public class IsSame extends BaseMatcher +{ + private final T object; + + public IsSame(T object) + { + this.object = object; + } + + @Override + public boolean matches(Object arg) + { + return arg == object; + } + + @Override + public void describeTo(Description description) + { + description.appendText("sameInstance(") + .appendValue(object) + .appendText(")"); + } + + /** + * Creates a matcher that matches only when the examined object is the same instance as + * the specified target object. + * + * @param target + * the target instance against which others should be assessed + */ + public static Matcher sameInstance(T target) + { + return new IsSame(target); + } + + /** + * Creates a matcher that matches only when the examined object is the same instance as + * the specified target object. + * + * @param target + * the target instance against which others should be assessed + */ + public static Matcher theInstance(T target) + { + return new IsSame(target); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java b/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java index 30b33af5..e1dd39a4 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java +++ b/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java @@ -4,30 +4,36 @@ import org.hamcrest.Description; import org.hamcrest.Matcher; -abstract class ShortcutCombination extends BaseMatcher { +abstract class ShortcutCombination extends BaseMatcher +{ - private final Iterable> matchers; + private final Iterable> matchers; - public ShortcutCombination(Iterable> matchers) { - this.matchers = matchers; - } - - @Override - public abstract boolean matches(Object o); - - @Override - public abstract void describeTo(Description description); - - protected boolean matches(Object o, boolean shortcut) { - for (Matcher matcher : matchers) { - if (matcher.matches(o) == shortcut) { - return shortcut; - } - } - return !shortcut; - } - - public void describeTo(Description description, String operator) { - description.appendList("(", " " + operator + " ", ")", matchers); + public ShortcutCombination(Iterable> matchers) + { + this.matchers = matchers; + } + + @Override + public abstract boolean matches(Object o); + + @Override + public abstract void describeTo(Description description); + + protected boolean matches(Object o, boolean shortcut) + { + for (Matcher matcher : matchers) + { + if (matcher.matches(o) == shortcut) + { + return shortcut; + } } + return !shortcut; + } + + public void describeTo(Description description, String operator) + { + description.appendList("(", " " + operator + " ", ")", matchers); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/StringContains.java b/hamcrest/src/main/java/org/hamcrest/core/StringContains.java index 050fd159..23b77d28 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringContains.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringContains.java @@ -5,44 +5,50 @@ /** * Tests if the argument is a string that contains a specific substring. */ -public class StringContains extends SubstringMatcher { - public StringContains(String substring) { this(false, substring); } +public class StringContains extends SubstringMatcher +{ + public StringContains(String substring) + { + this(false, substring); + } - public StringContains(boolean ignoringCase, String substring) { - super("containing", ignoringCase, substring); - } + public StringContains(boolean ignoringCase, String substring) + { + super("containing", ignoringCase, substring); + } - @Override - protected boolean evalSubstringOf(String s) { - return converted(s).contains(converted(substring)); - } + @Override + protected boolean evalSubstringOf(String s) + { + return converted(s).contains(converted(substring)); + } - /** - * Creates a matcher that matches if the examined {@link String} contains the specified - * {@link String} anywhere. - * For example: - *
assertThat("myStringOfNote", containsString("ring"))
- * - * @param substring - * the substring that the returned matcher will expect to find within any examined string - * - */ - public static Matcher containsString(String substring) { - return new StringContains(false, substring); - } + /** + * Creates a matcher that matches if the examined {@link String} contains the specified + * {@link String} anywhere. + * For example: + *
assertThat("myStringOfNote", containsString("ring"))
+ * + * @param substring + * the substring that the returned matcher will expect to find within any examined string + */ + public static Matcher containsString(String substring) + { + return new StringContains(false, substring); + } - /** - * Creates a matcher that matches if the examined {@link String} contains the specified - * {@link String} anywhere, ignoring case. - * For example: - *
assertThat("myStringOfNote", containsStringIgnoringCase("Ring"))
- * - * @param substring - * the substring that the returned matcher will expect to find within any examined string - * - */ - public static Matcher containsStringIgnoringCase(String substring) { - return new StringContains(true, substring); - } + /** + * Creates a matcher that matches if the examined {@link String} contains the specified + * {@link String} anywhere, ignoring case. + * For example: + *
assertThat("myStringOfNote", containsStringIgnoringCase("Ring"))
+ * + * @param substring + * the substring that the returned matcher will expect to find within any examined string + */ + public static Matcher containsStringIgnoringCase(String substring) + { + return new StringContains(true, substring); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java b/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java index 48ffd923..b7fd933b 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java @@ -5,40 +5,50 @@ /** * Tests if the argument is a string that ends with a specific substring. */ -public class StringEndsWith extends SubstringMatcher { - public StringEndsWith(String substring) { this(false, substring); } +public class StringEndsWith extends SubstringMatcher +{ + public StringEndsWith(String substring) + { + this(false, substring); + } - public StringEndsWith(boolean ignoringCase, String substring) { super("ending with", ignoringCase, substring); } + public StringEndsWith(boolean ignoringCase, String substring) + { + super("ending with", ignoringCase, substring); + } - @Override - protected boolean evalSubstringOf(String s) { - return converted(s).endsWith(converted(substring)); - } + @Override + protected boolean evalSubstringOf(String s) + { + return converted(s).endsWith(converted(substring)); + } - /** - * Creates a matcher that matches if the examined {@link String} ends with the specified - * {@link String}. - * For example: - *
assertThat("myStringOfNote", endsWith("Note"))
- * - * @param suffix - * the substring that the returned matcher will expect at the end of any examined string - */ - public static Matcher endsWith(String suffix) { - return new StringEndsWith(false, suffix); - } + /** + * Creates a matcher that matches if the examined {@link String} ends with the specified + * {@link String}. + * For example: + *
assertThat("myStringOfNote", endsWith("Note"))
+ * + * @param suffix + * the substring that the returned matcher will expect at the end of any examined string + */ + public static Matcher endsWith(String suffix) + { + return new StringEndsWith(false, suffix); + } - /** - * Creates a matcher that matches if the examined {@link String} ends with the specified - * {@link String}, ignoring case. - * For example: - *
assertThat("myStringOfNote", endsWithIgnoringCase("note"))
- * - * @param suffix - * the substring that the returned matcher will expect at the end of any examined string - */ - public static Matcher endsWithIgnoringCase(String suffix) { - return new StringEndsWith(true, suffix); - } + /** + * Creates a matcher that matches if the examined {@link String} ends with the specified + * {@link String}, ignoring case. + * For example: + *
assertThat("myStringOfNote", endsWithIgnoringCase("note"))
+ * + * @param suffix + * the substring that the returned matcher will expect at the end of any examined string + */ + public static Matcher endsWithIgnoringCase(String suffix) + { + return new StringEndsWith(true, suffix); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/StringRegularExpression.java b/hamcrest/src/main/java/org/hamcrest/core/StringRegularExpression.java index b893ff0e..aaa8aaf6 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringRegularExpression.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringRegularExpression.java @@ -12,24 +12,28 @@ /** * @author borettim * @author sf105 - * */ -public class StringRegularExpression extends TypeSafeDiagnosingMatcher { +public class StringRegularExpression extends TypeSafeDiagnosingMatcher +{ - protected StringRegularExpression(Pattern pattern) { + protected StringRegularExpression(Pattern pattern) + { this.pattern = pattern; } private Pattern pattern; @Override - public void describeTo(Description description) { + public void describeTo(Description description) + { description.appendText("a string matching the pattern ").appendValue(pattern); } @Override - protected boolean matchesSafely(String actual, Description mismatchDescription) { - if (!pattern.matcher(actual).matches()) { + protected boolean matchesSafely(String actual, Description mismatchDescription) + { + if (!pattern.matcher(actual).matches()) + { mismatchDescription.appendText("the string was ").appendValue(actual); return false; } @@ -47,7 +51,8 @@ protected boolean matchesSafely(String actual, Description mismatchDescription) * the pattern to be used. * @return The matcher. */ - public static Matcher matchesRegex(Pattern pattern) { + public static Matcher matchesRegex(Pattern pattern) + { return new StringRegularExpression(pattern); } @@ -62,7 +67,8 @@ public static Matcher matchesRegex(Pattern pattern) { * The regex to be used for the validation. * @return The matcher. */ - public static Matcher matchesRegex(String regex) { + public static Matcher matchesRegex(String regex) + { return matchesRegex(Pattern.compile(regex)); } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java b/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java index fa49b793..d9d25005 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java @@ -5,38 +5,54 @@ /** * Tests if the argument is a string that starts with a specific substring. */ -public class StringStartsWith extends SubstringMatcher { - public StringStartsWith(String substring) { this(false, substring); } +public class StringStartsWith extends SubstringMatcher +{ + public StringStartsWith(String substring) + { + this(false, substring); + } - public StringStartsWith(boolean ignoringCase, String substring) { super("starting with", ignoringCase, substring); } + public StringStartsWith(boolean ignoringCase, String substring) + { + super("starting with", ignoringCase, substring); + } - @Override - protected boolean evalSubstringOf(String s) { return converted(s).startsWith(converted(substring)); } + @Override + protected boolean evalSubstringOf(String s) + { + return converted(s).startsWith(converted(substring)); + } - /** - *

- * Creates a matcher that matches if the examined {@link String} starts with the specified - * {@link String}. - *

- * For example: - *
assertThat("myStringOfNote", startsWith("my"))
- * - * @param prefix - * the substring that the returned matcher will expect at the start of any examined string - */ - public static Matcher startsWith(String prefix) { return new StringStartsWith(false, prefix); } + /** + *

+ * Creates a matcher that matches if the examined {@link String} starts with the specified + * {@link String}. + *

+ * For example: + *
assertThat("myStringOfNote", startsWith("my"))
+ * + * @param prefix + * the substring that the returned matcher will expect at the start of any examined string + */ + public static Matcher startsWith(String prefix) + { + return new StringStartsWith(false, prefix); + } - /** - *

- * Creates a matcher that matches if the examined {@link String} starts with the specified - * {@link String}, ignoring case - *

- * For example: - *
assertThat("myStringOfNote", startsWithIgnoringCase("My"))
- * - * @param prefix - * the substring that the returned matcher will expect at the start of any examined string - */ - public static Matcher startsWithIgnoringCase(String prefix) { return new StringStartsWith(true, prefix); } + /** + *

+ * Creates a matcher that matches if the examined {@link String} starts with the specified + * {@link String}, ignoring case + *

+ * For example: + *
assertThat("myStringOfNote", startsWithIgnoringCase("My"))
+ * + * @param prefix + * the substring that the returned matcher will expect at the start of any examined string + */ + public static Matcher startsWithIgnoringCase(String prefix) + { + return new StringStartsWith(true, prefix); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java b/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java index f2b7cff0..ca043c19 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java @@ -3,45 +3,57 @@ import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; -public abstract class SubstringMatcher extends TypeSafeMatcher { - - // TODO: Replace String with CharSequence to allow for easy interoperability between - // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). - - private final String relationship; - private final boolean ignoringCase; - protected final String substring; - - protected SubstringMatcher(String relationship, boolean ignoringCase, String substring) { - this.relationship = relationship; - this.ignoringCase = ignoringCase; - this.substring = substring; - if (null == substring) { - throw new IllegalArgumentException("missing substring"); - } +public abstract class SubstringMatcher extends TypeSafeMatcher +{ + + // TODO: Replace String with CharSequence to allow for easy interoperability between + // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). + + private final String relationship; + private final boolean ignoringCase; + protected final String substring; + + protected SubstringMatcher(String relationship, boolean ignoringCase, String substring) + { + this.relationship = relationship; + this.ignoringCase = ignoringCase; + this.substring = substring; + if (null == substring) + { + throw new IllegalArgumentException("missing substring"); } - - @Override - public boolean matchesSafely(String item) { - return evalSubstringOf(ignoringCase ? item.toLowerCase() :item); - } - @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("was \"").appendText(item).appendText("\""); - } - - @Override - public void describeTo(Description description) { - description.appendText("a string ") - .appendText(relationship) - .appendText(" ") - .appendValue(substring); - if (ignoringCase) { - description.appendText(" ignoring case"); - } + } + + @Override + public boolean matchesSafely(String item) + { + return evalSubstringOf(ignoringCase ? item.toLowerCase() : item); + } + + @Override + public void describeMismatchSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("was \"").appendText(item).appendText("\""); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a string ") + .appendText(relationship) + .appendText(" ") + .appendValue(substring); + if (ignoringCase) + { + description.appendText(" ignoring case"); } + } + + protected String converted(String arg) + { + return ignoringCase ? arg.toLowerCase() : arg; + } - protected String converted(String arg) { return ignoringCase ? arg.toLowerCase() : arg; } - protected abstract boolean evalSubstringOf(String string); + protected abstract boolean evalSubstringOf(String string); } diff --git a/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java b/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java index 03e4c43e..3aa73b2f 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java @@ -3,29 +3,35 @@ import java.lang.reflect.Array; import java.util.Iterator; -public class ArrayIterator implements Iterator { - private final Object array; - private int currentIndex = 0; - - public ArrayIterator(Object array) { - if (!array.getClass().isArray()) { - throw new IllegalArgumentException("not an array"); - } - this.array = array; - } - - @Override - public boolean hasNext() { - return currentIndex < Array.getLength(array); - } +public class ArrayIterator implements Iterator +{ + private final Object array; + private int currentIndex = 0; - @Override - public Object next() { - return Array.get(array, currentIndex++); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("cannot remove items from an array"); + public ArrayIterator(Object array) + { + if (!array.getClass().isArray()) + { + throw new IllegalArgumentException("not an array"); } + this.array = array; + } + + @Override + public boolean hasNext() + { + return currentIndex < Array.getLength(array); + } + + @Override + public Object next() + { + return Array.get(array, currentIndex++); + } + + @Override + public void remove() + { + throw new UnsupportedOperationException("cannot remove items from an array"); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java b/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java index 9310abfc..a35d17b6 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java @@ -6,13 +6,16 @@ import java.util.ArrayList; import java.util.List; -public class NullSafety { - @SuppressWarnings("unchecked") - public static List> nullSafe(Matcher[] itemMatchers) { - final List> matchers = new ArrayList>(itemMatchers.length); - for (final Matcher itemMatcher : itemMatchers) { - matchers.add((Matcher) (itemMatcher == null ? IsNull.nullValue() : itemMatcher)); - } - return matchers; +public class NullSafety +{ + @SuppressWarnings("unchecked") + public static List> nullSafe(Matcher[] itemMatchers) + { + final List> matchers = new ArrayList>(itemMatchers.length); + for (final Matcher itemMatcher : itemMatchers) + { + matchers.add((Matcher) (itemMatcher == null ? IsNull.nullValue() : itemMatcher)); } + return matchers; + } } diff --git a/hamcrest/src/main/java/org/hamcrest/internal/ReflectiveTypeFinder.java b/hamcrest/src/main/java/org/hamcrest/internal/ReflectiveTypeFinder.java index b06df48c..2810ca62 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/ReflectiveTypeFinder.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/ReflectiveTypeFinder.java @@ -1,25 +1,25 @@ /** - * The TypeSafe classes, and their descendants, need a mechanism to find out what type has been used as a parameter - * for the concrete matcher. Unfortunately, this type is lost during type erasure so we need to use reflection - * to get it back, by picking out the type of a known parameter to a known method. - * The catch is that, with bridging methods, this type is only visible in the class that actually implements + * The TypeSafe classes, and their descendants, need a mechanism to find out what type has been used as a parameter + * for the concrete matcher. Unfortunately, this type is lost during type erasure so we need to use reflection + * to get it back, by picking out the type of a known parameter to a known method. + * The catch is that, with bridging methods, this type is only visible in the class that actually implements * the expected method, so the ReflectiveTypeFinder needs to be applied to that class or a subtype. - * + *

* For example, the abstract TypeSafeDiagnosingMatcher<T> defines an abstract method *

protected abstract boolean matchesSafely(T item, Description mismatchDescription);
* By default it uses new ReflectiveTypeFinder("matchesSafely", 2, 0); to find the * parameterised type. If we create a TypeSafeDiagnosingMatcher<String>, the type * finder will return String.class. - * - * A FeatureMatcher is an abstract subclass of TypeSafeDiagnosingMatcher. + *

+ * A FeatureMatcher is an abstract subclass of TypeSafeDiagnosingMatcher. * Although it has a templated implementation of matchesSafely(<T>, Description);, the * actual run-time signature of this is matchesSafely(Object, Description);. Instead, - * we must find the type by reflecting on the concrete implementation of + * we must find the type by reflecting on the concrete implementation of *

protected abstract U featureValueOf(T actual);
* a method which is declared in FeatureMatcher. - * - * In short, use this to extract a type from a method in the leaf class of a templated class hierarchy. - * + *

+ * In short, use this to extract a type from a method in the leaf class of a templated class hierarchy. + * * @author Steve Freeman * @author Nat Pryce */ @@ -27,44 +27,54 @@ import java.lang.reflect.Method; -public class ReflectiveTypeFinder { +public class ReflectiveTypeFinder +{ private final String methodName; private final int expectedNumberOfParameters; private final int typedParameter; - public ReflectiveTypeFinder(String methodName, int expectedNumberOfParameters, int typedParameter) { + public ReflectiveTypeFinder(String methodName, int expectedNumberOfParameters, int typedParameter) + { this.methodName = methodName; this.expectedNumberOfParameters = expectedNumberOfParameters; this.typedParameter = typedParameter; } - - public Class findExpectedType(Class fromClass) { - for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { - for (Method method : c.getDeclaredMethods()) { - if (canObtainExpectedTypeFrom(method)) { - return expectedTypeFrom(method); - } + + public Class findExpectedType(Class fromClass) + { + for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) + { + for (Method method : c.getDeclaredMethods()) + { + if (canObtainExpectedTypeFrom(method)) + { + return expectedTypeFrom(method); } + } } throw new Error("Cannot determine correct type for " + methodName + "() method."); } /** - * @param method The method to examine. + * @param method + * The method to examine. * @return true if this method references the relevant type */ - private boolean canObtainExpectedTypeFrom(Method method) { - return method.getName().equals(methodName) - && method.getParameterTypes().length == expectedNumberOfParameters - && !method.isSynthetic(); + private boolean canObtainExpectedTypeFrom(Method method) + { + return method.getName().equals(methodName) + && method.getParameterTypes().length == expectedNumberOfParameters + && !method.isSynthetic(); } /** - * @param method The method from which to extract + * @param method + * The method from which to extract * @return The type we're looking for */ - private Class expectedTypeFrom(Method method) { - return method.getParameterTypes()[typedParameter]; + private Class expectedTypeFrom(Method method) + { + return method.getParameterTypes()[typedParameter]; } } diff --git a/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java b/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java index 6537018a..f7e50754 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java @@ -3,15 +3,18 @@ import org.hamcrest.Description; import org.hamcrest.SelfDescribing; -public class SelfDescribingValue implements SelfDescribing { - private T value; - - public SelfDescribingValue(T value) { - this.value = value; - } +public class SelfDescribingValue implements SelfDescribing +{ + private T value; - @Override - public void describeTo(Description description) { - description.appendValue(value); - } + public SelfDescribingValue(T value) + { + this.value = value; + } + + @Override + public void describeTo(Description description) + { + description.appendValue(value); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java b/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java index bc8f8f43..978c5f57 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java @@ -4,25 +4,30 @@ import java.util.Iterator; -public class SelfDescribingValueIterator implements Iterator { - private Iterator values; - - public SelfDescribingValueIterator(Iterator values) { - this.values = values; - } - - @Override - public boolean hasNext() { - return values.hasNext(); - } +public class SelfDescribingValueIterator implements Iterator +{ + private Iterator values; - @Override - public SelfDescribing next() { - return new SelfDescribingValue(values.next()); - } + public SelfDescribingValueIterator(Iterator values) + { + this.values = values; + } - @Override - public void remove() { - values.remove(); - } + @Override + public boolean hasNext() + { + return values.hasNext(); + } + + @Override + public SelfDescribing next() + { + return new SelfDescribingValue(values.next()); + } + + @Override + public void remove() + { + values.remove(); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java b/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java index 88288b07..77025beb 100644 --- a/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java +++ b/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java @@ -10,98 +10,152 @@ import static org.hamcrest.core.IsEqual.equalTo; -public final class FileMatchers { - - public static Matcher anExistingDirectory() { - return fileChecker(IS_DIRECTORY, "an existing directory", "is not a directory"); - } - - public static Matcher anExistingFileOrDirectory() { - return fileChecker(EXISTS, "an existing file or directory", "does not exist"); - } - - public static Matcher anExistingFile() { - return fileChecker(IS_FILE, "an existing File", "is not a file"); - } - - public static Matcher aReadableFile() { - return fileChecker(CAN_READ, "a readable File", "cannot be read"); - } - - public static Matcher aWritableFile() { - return fileChecker(CAN_WRITE, "a writable File", "cannot be written to"); - } - - public static Matcher aFileWithSize(long size) { - return aFileWithSize(equalTo(size)); - } - - public static Matcher aFileWithSize(final Matcher expected) { - return new FeatureMatcher(expected, "A file with size", "size") { - @Override protected Long featureValueOf(File actual) { return actual.length(); } - }; +public final class FileMatchers +{ + + public static Matcher anExistingDirectory() + { + return fileChecker(IS_DIRECTORY, "an existing directory", "is not a directory"); + } + + public static Matcher anExistingFileOrDirectory() + { + return fileChecker(EXISTS, "an existing file or directory", "does not exist"); + } + + public static Matcher anExistingFile() + { + return fileChecker(IS_FILE, "an existing File", "is not a file"); + } + + public static Matcher aReadableFile() + { + return fileChecker(CAN_READ, "a readable File", "cannot be read"); + } + + public static Matcher aWritableFile() + { + return fileChecker(CAN_WRITE, "a writable File", "cannot be written to"); + } + + public static Matcher aFileWithSize(long size) + { + return aFileWithSize(equalTo(size)); + } + + public static Matcher aFileWithSize(final Matcher expected) + { + return new FeatureMatcher(expected, "A file with size", "size") + { + @Override protected Long featureValueOf(File actual) + { + return actual.length(); + } + }; + } + + public static Matcher aFileNamed(final Matcher expected) + { + return new FeatureMatcher(expected, "A file with name", "name") + { + @Override protected String featureValueOf(File actual) + { + return actual.getName(); + } + }; + } + + public static Matcher aFileWithCanonicalPath(final Matcher expected) + { + return new FeatureMatcher(expected, "A file with canonical path", "path") + { + @Override protected String featureValueOf(File actual) + { + try + { + return actual.getCanonicalPath(); + } + catch (IOException e) + { + return "Exception: " + e.getMessage(); + } + } + }; + } + + public static Matcher aFileWithAbsolutePath(final Matcher expected) + { + return new FeatureMatcher(expected, "A file with absolute path", "path") + { + @Override protected String featureValueOf(File actual) + { + return actual.getAbsolutePath(); + } + }; + } + + public static interface FileStatus + { + boolean check(File actual); + } + + public static final FileStatus CAN_WRITE = new FileStatus() + { + @Override public boolean check(File actual) + { + return actual.canWrite(); } - - public static Matcher aFileNamed(final Matcher expected) { - return new FeatureMatcher(expected, "A file with name", "name") { - @Override protected String featureValueOf(File actual) { return actual.getName(); } - }; + }; + public static final FileStatus CAN_READ = new FileStatus() + { + @Override public boolean check(File actual) + { + return actual.canRead(); } + }; - public static Matcher aFileWithCanonicalPath(final Matcher expected) { - return new FeatureMatcher(expected, "A file with canonical path", "path") { - @Override protected String featureValueOf(File actual) { - try { - return actual.getCanonicalPath(); - } catch (IOException e) { - return "Exception: " + e.getMessage(); - } - } - }; + public static final FileStatus IS_FILE = new FileStatus() + { + @Override public boolean check(File actual) + { + return actual.isFile(); } + }; - public static Matcher aFileWithAbsolutePath(final Matcher expected) { - return new FeatureMatcher(expected, "A file with absolute path", "path") { - @Override protected String featureValueOf(File actual) { return actual.getAbsolutePath(); } - }; + public static final FileStatus IS_DIRECTORY = new FileStatus() + { + @Override public boolean check(File actual) + { + return actual.isDirectory(); } + }; - public static interface FileStatus { - boolean check(File actual); + public static final FileStatus EXISTS = new FileStatus() + { + @Override public boolean check(File actual) + { + return actual.exists(); } - - public static final FileStatus CAN_WRITE = new FileStatus() { - @Override public boolean check(File actual) { return actual.canWrite(); } - }; - public static final FileStatus CAN_READ = new FileStatus() { - @Override public boolean check(File actual) { return actual.canRead(); } - }; - - public static final FileStatus IS_FILE = new FileStatus() { - @Override public boolean check(File actual) { return actual.isFile(); } - }; - - public static final FileStatus IS_DIRECTORY = new FileStatus() { - @Override public boolean check(File actual) { return actual.isDirectory(); } + }; + + private static Matcher fileChecker(final FileStatus fileStatus, final String successDescription, final String failureDescription) + { + return new TypeSafeDiagnosingMatcher() + { + public boolean matchesSafely(File actual, Description mismatchDescription) + { + final boolean result = fileStatus.check(actual); + if (!result) + { + mismatchDescription.appendText(failureDescription); + } + return result; + } + + public void describeTo(Description description) + { + description.appendText(successDescription); + } }; - - public static final FileStatus EXISTS = new FileStatus() { - @Override public boolean check(File actual) { return actual.exists(); } - }; - - private static Matcher fileChecker(final FileStatus fileStatus, final String successDescription, final String failureDescription) { - return new TypeSafeDiagnosingMatcher() { - public boolean matchesSafely(File actual, Description mismatchDescription) { - final boolean result = fileStatus.check(actual); - if (!result) { - mismatchDescription.appendText(failureDescription); - } - return result; - } - - public void describeTo(Description description) { - description.appendText(successDescription); - } - }; - } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java b/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java index d9cb0264..6939a2e1 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java +++ b/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java @@ -7,40 +7,46 @@ import java.math.BigDecimal; import java.math.MathContext; -public class BigDecimalCloseTo extends TypeSafeMatcher { +public class BigDecimalCloseTo extends TypeSafeMatcher +{ private final BigDecimal delta; private final BigDecimal value; - public BigDecimalCloseTo(BigDecimal value, BigDecimal error) { - this.delta = error; - this.value = value; + public BigDecimalCloseTo(BigDecimal value, BigDecimal error) + { + this.delta = error; + this.value = value; } @Override - public boolean matchesSafely(BigDecimal item) { - return actualDelta(item).compareTo(BigDecimal.ZERO) <= 0; + public boolean matchesSafely(BigDecimal item) + { + return actualDelta(item).compareTo(BigDecimal.ZERO) <= 0; } @Override - public void describeMismatchSafely(BigDecimal item, Description mismatchDescription) { - mismatchDescription.appendValue(item) - .appendText(" differed by ") - .appendValue(actualDelta(item)) - .appendText(" more than delta ") - .appendValue(delta); + public void describeMismatchSafely(BigDecimal item, Description mismatchDescription) + { + mismatchDescription.appendValue(item) + .appendText(" differed by ") + .appendValue(actualDelta(item)) + .appendText(" more than delta ") + .appendValue(delta); } @Override - public void describeTo(Description description) { - description.appendText("a numeric value within ") - .appendValue(delta) - .appendText(" of ") - .appendValue(value); + public void describeTo(Description description) + { + description.appendText("a numeric value within ") + .appendValue(delta) + .appendText(" of ") + .appendValue(value); } - private BigDecimal actualDelta(BigDecimal item) { - return item.subtract(value, MathContext.DECIMAL128).abs().subtract(delta, MathContext.DECIMAL128).stripTrailingZeros(); + private BigDecimal actualDelta(BigDecimal item) + { + return item.subtract(value, MathContext.DECIMAL128).abs().subtract(delta, MathContext.DECIMAL128).stripTrailingZeros(); } /** @@ -49,14 +55,15 @@ private BigDecimal actualDelta(BigDecimal item) { * is done by BigDecimals {@link java.math.BigDecimal#compareTo(java.math.BigDecimal)} method. * For example: *

assertThat(new BigDecimal("1.03"), is(closeTo(new BigDecimal("1.0"), new BigDecimal("0.03"))))
- * + * * @param operand * the expected value of matching BigDecimals * @param error * the delta (+/-) within which matches will be allowed */ - public static Matcher closeTo(BigDecimal operand, BigDecimal error) { - return new BigDecimalCloseTo(operand, error); + public static Matcher closeTo(BigDecimal operand, BigDecimal error) + { + return new BigDecimalCloseTo(operand, error); } } diff --git a/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java b/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java index 3b6967dc..d36fe605 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java +++ b/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java @@ -11,53 +11,60 @@ * Is the value a number equal to a value within some range of * acceptable error? */ -public class IsCloseTo extends TypeSafeMatcher { - private final double delta; - private final double value; - - public IsCloseTo(double value, double error) { - this.delta = error; - this.value = value; - } - - @Override - public boolean matchesSafely(Double item) { - return actualDelta(item) <= 0.0; - } - - @Override - public void describeMismatchSafely(Double item, Description mismatchDescription) { - mismatchDescription.appendValue(item) - .appendText(" differed by ") - .appendValue(actualDelta(item)) - .appendText(" more than delta ") - .appendValue(delta); - } - - @Override - public void describeTo(Description description) { - description.appendText("a numeric value within ") - .appendValue(delta) - .appendText(" of ") - .appendValue(value); - } - - private double actualDelta(Double item) { - return abs(item - value) - delta; - } - - /** - * Creates a matcher of {@link Double}s that matches when an examined double is equal - * to the specified operand, within a range of +/- error. - * For example: - *
assertThat(1.03, is(closeTo(1.0, 0.03)))
- * - * @param operand - * the expected value of matching doubles - * @param error - * the delta (+/-) within which matches will be allowed - */ - public static Matcher closeTo(double operand, double error) { - return new IsCloseTo(operand, error); - } +public class IsCloseTo extends TypeSafeMatcher +{ + private final double delta; + private final double value; + + public IsCloseTo(double value, double error) + { + this.delta = error; + this.value = value; + } + + @Override + public boolean matchesSafely(Double item) + { + return actualDelta(item) <= 0.0; + } + + @Override + public void describeMismatchSafely(Double item, Description mismatchDescription) + { + mismatchDescription.appendValue(item) + .appendText(" differed by ") + .appendValue(actualDelta(item)) + .appendText(" more than delta ") + .appendValue(delta); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a numeric value within ") + .appendValue(delta) + .appendText(" of ") + .appendValue(value); + } + + private double actualDelta(Double item) + { + return abs(item - value) - delta; + } + + /** + * Creates a matcher of {@link Double}s that matches when an examined double is equal + * to the specified operand, within a range of +/- error. + * For example: + *
assertThat(1.03, is(closeTo(1.0, 0.03)))
+ * + * @param operand + * the expected value of matching doubles + * @param error + * the delta (+/-) within which matches will be allowed + */ + public static Matcher closeTo(double operand, double error) + { + return new IsCloseTo(operand, error); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java b/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java index 415a9a2b..b7f70813 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java +++ b/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java @@ -8,31 +8,38 @@ /** * Is the value a number actually not a number (NaN)? */ -public final class IsNaN extends TypeSafeMatcher { - - private IsNaN() { } - - @Override - public boolean matchesSafely(Double item) { - return Double.isNaN(item); - } - - @Override - public void describeMismatchSafely(Double item, Description mismatchDescription) { - mismatchDescription.appendText("was ").appendValue(item); - } - - @Override - public void describeTo(Description description) { - description.appendText("a double value of NaN"); - } - - /** - * Creates a matcher of {@link Double}s that matches when an examined double is not a number. - * For example: - *
assertThat(Double.NaN, is(notANumber()))
- */ - public static Matcher notANumber() { - return new IsNaN(); - } +public final class IsNaN extends TypeSafeMatcher +{ + + private IsNaN() + { + } + + @Override + public boolean matchesSafely(Double item) + { + return Double.isNaN(item); + } + + @Override + public void describeMismatchSafely(Double item, Description mismatchDescription) + { + mismatchDescription.appendText("was ").appendValue(item); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a double value of NaN"); + } + + /** + * Creates a matcher of {@link Double}s that matches when an examined double is not a number. + * For example: + *
assertThat(Double.NaN, is(notANumber()))
+ */ + public static Matcher notANumber() + { + return new IsNaN(); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java b/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java index 8a77713d..10fb098c 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java +++ b/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java @@ -3,77 +3,89 @@ import org.hamcrest.Matcher; import org.hamcrest.comparator.ComparatorMatcherBuilder; -public class OrderingComparison { +public class OrderingComparison +{ - private OrderingComparison() { - } + private OrderingComparison() + { + } - /** - * Creates a matcher of {@link Comparable} object that matches when the examined object is - * equal to the specified value, as reported by the compareTo method of the - * examined object. - * For example: - *
assertThat(1, comparesEqualTo(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return zero - */ - public static > Matcher comparesEqualTo(T value) { - return ComparatorMatcherBuilder.usingNaturalOrdering().comparesEqualTo(value); - } + /** + * Creates a matcher of {@link Comparable} object that matches when the examined object is + * equal to the specified value, as reported by the compareTo method of the + * examined object. + * For example: + *
assertThat(1, comparesEqualTo(1))
+ * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return zero + */ + public static > Matcher comparesEqualTo(T value) + { + return ComparatorMatcherBuilder.usingNaturalOrdering().comparesEqualTo(value); + } - /** - * Creates a matcher of {@link Comparable} object that matches when the examined object is - * greater than the specified value, as reported by the compareTo method of the - * examined object. - * For example: - *
assertThat(2, greaterThan(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return greater - * than zero - */ - public static > Matcher greaterThan(T value) { - return ComparatorMatcherBuilder.usingNaturalOrdering().greaterThan(value); - } + /** + * Creates a matcher of {@link Comparable} object that matches when the examined object is + * greater than the specified value, as reported by the compareTo method of the + * examined object. + * For example: + *
assertThat(2, greaterThan(1))
+ * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return greater + * than zero + */ + public static > Matcher greaterThan(T value) + { + return ComparatorMatcherBuilder.usingNaturalOrdering().greaterThan(value); + } - /** - * Creates a matcher of {@link Comparable} object that matches when the examined object is - * greater than or equal to the specified value, as reported by the compareTo method - * of the examined object. - * For example: - *
assertThat(1, greaterThanOrEqualTo(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return greater - * than or equal to zero - */ - public static > Matcher greaterThanOrEqualTo(T value) { - return ComparatorMatcherBuilder.usingNaturalOrdering().greaterThanOrEqualTo(value); - } + /** + * Creates a matcher of {@link Comparable} object that matches when the examined object is + * greater than or equal to the specified value, as reported by the compareTo method + * of the examined object. + * For example: + *
assertThat(1, greaterThanOrEqualTo(1))
+ * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return greater + * than or equal to zero + */ + public static > Matcher greaterThanOrEqualTo(T value) + { + return ComparatorMatcherBuilder.usingNaturalOrdering().greaterThanOrEqualTo(value); + } - /** - * Creates a matcher of {@link Comparable} object that matches when the examined object is - * less than the specified value, as reported by the compareTo method of the - * examined object. - * For example: - *
assertThat(1, lessThan(2))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return less - * than zero - */ - public static > Matcher lessThan(T value) { - return ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(value); - } + /** + * Creates a matcher of {@link Comparable} object that matches when the examined object is + * less than the specified value, as reported by the compareTo method of the + * examined object. + * For example: + *
assertThat(1, lessThan(2))
+ * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return less + * than zero + */ + public static > Matcher lessThan(T value) + { + return ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(value); + } - /** - * Creates a matcher of {@link Comparable} object that matches when the examined object is - * less than or equal to the specified value, as reported by the compareTo method - * of the examined object. - * For example: - *
assertThat(1, lessThanOrEqualTo(1))
- * - * @param value the value which, when passed to the compareTo method of the examined object, should return less - * than or equal to zero - */ - public static > Matcher lessThanOrEqualTo(T value) { - return ComparatorMatcherBuilder.usingNaturalOrdering().lessThanOrEqualTo(value); - } + /** + * Creates a matcher of {@link Comparable} object that matches when the examined object is + * less than or equal to the specified value, as reported by the compareTo method + * of the examined object. + * For example: + *
assertThat(1, lessThanOrEqualTo(1))
+ * + * @param value + * the value which, when passed to the compareTo method of the examined object, should return less + * than or equal to zero + */ + public static > Matcher lessThanOrEqualTo(T value) + { + return ComparatorMatcherBuilder.usingNaturalOrdering().lessThanOrEqualTo(value); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java b/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java index cffea890..c1de6919 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java +++ b/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java @@ -12,75 +12,93 @@ import static java.lang.String.format; -public class HasEqualValues extends TypeSafeDiagnosingMatcher { - private final T expectedObject; - private final List fieldMatchers; +public class HasEqualValues extends TypeSafeDiagnosingMatcher +{ + private final T expectedObject; + private final List fieldMatchers; - public HasEqualValues(T expectedObject) { - super(expectedObject.getClass()); - this.expectedObject = expectedObject; - this.fieldMatchers = fieldMatchers(expectedObject); + public HasEqualValues(T expectedObject) + { + super(expectedObject.getClass()); + this.expectedObject = expectedObject; + this.fieldMatchers = fieldMatchers(expectedObject); + } + + @Override + protected boolean matchesSafely(T item, Description mismatch) + { + for (FieldMatcher fieldMatcher : fieldMatchers) + { + if (!fieldMatcher.matches(item, mismatch)) + { + return false; + } } + return true; + } - @Override - protected boolean matchesSafely(T item, Description mismatch) { - for (FieldMatcher fieldMatcher : fieldMatchers) { - if (!fieldMatcher.matches(item, mismatch)) { - return false; - } - } - return true; + @Override + public void describeTo(Description description) + { + description.appendText(expectedObject.getClass().getSimpleName()) + .appendText(" has values ") + .appendList("[", ", ", "]", fieldMatchers); + } + + private static class FieldMatcher extends DiagnosingMatcher + { + private final Field field; + private final Matcher matcher; + + public FieldMatcher(Field field, Object expectedObject) + { + this.field = field; + this.matcher = IsEqual.equalTo(uncheckedGet(field, expectedObject)); } @Override - public void describeTo(Description description) { - description.appendText(expectedObject.getClass().getSimpleName()) - .appendText(" has values ") - .appendList("[", ", ", "]", fieldMatchers); + protected boolean matches(Object item, Description mismatch) + { + final Object actual = uncheckedGet(field, item); + if (!matcher.matches(actual)) + { + mismatch.appendText("'").appendText(field.getName()).appendText("' "); + matcher.describeMismatch(actual, mismatch); + return false; + } + return true; } - private static class FieldMatcher extends DiagnosingMatcher { - private final Field field; - private final Matcher matcher; - - public FieldMatcher(Field field, Object expectedObject) { - this.field = field; - this.matcher = IsEqual.equalTo(uncheckedGet(field, expectedObject)); - } - @Override - protected boolean matches(Object item, Description mismatch) { - final Object actual = uncheckedGet(field, item); - if (!matcher.matches(actual)) { - mismatch.appendText("'").appendText(field.getName()).appendText("' "); - matcher.describeMismatch(actual, mismatch); - return false; - } - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(field.getName()) - .appendText(": ") - .appendDescriptionOf(matcher); - } + @Override + public void describeTo(Description description) + { + description.appendText(field.getName()) + .appendText(": ") + .appendDescriptionOf(matcher); } + } - private static List fieldMatchers(Object expectedObject) { - final List result = new ArrayList<>(); - for (Field field : expectedObject.getClass().getFields()) { - result.add(new FieldMatcher(field, expectedObject)); - } - return result; + private static List fieldMatchers(Object expectedObject) + { + final List result = new ArrayList<>(); + for (Field field : expectedObject.getClass().getFields()) + { + result.add(new FieldMatcher(field, expectedObject)); } + return result; + } - private static Object uncheckedGet(Field field, Object object) { - try { - return field.get(object); - } catch (Exception e) { - throw new AssertionError(format("IllegalAccess, reading field '%s' from %s", field.getName(), object)); - } + private static Object uncheckedGet(Field field, Object object) + { + try + { + return field.get(object); + } + catch (Exception e) + { + throw new AssertionError(format("IllegalAccess, reading field '%s' from %s", field.getName(), object)); } + } } diff --git a/hamcrest/src/main/java/org/hamcrest/object/HasToString.java b/hamcrest/src/main/java/org/hamcrest/object/HasToString.java index 2dab9de4..31e00d13 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/HasToString.java +++ b/hamcrest/src/main/java/org/hamcrest/object/HasToString.java @@ -5,39 +5,44 @@ import static org.hamcrest.core.IsEqual.equalTo; -public class HasToString extends FeatureMatcher { - public HasToString(Matcher toStringMatcher) { - super(toStringMatcher, "with toString()", "toString()"); - } - - @Override - protected String featureValueOf(T actual) { - return String.valueOf(actual); - } +public class HasToString extends FeatureMatcher +{ + public HasToString(Matcher toStringMatcher) + { + super(toStringMatcher, "with toString()", "toString()"); + } - /** - * Creates a matcher that matches any examined object whose toString method - * returns a value that satisfies the specified matcher. - * For example: - *
assertThat(true, hasToString(equalTo("TRUE")))
- * - * @param toStringMatcher - * the matcher used to verify the toString result - */ - public static Matcher hasToString(Matcher toStringMatcher) { - return new HasToString(toStringMatcher); - } + @Override + protected String featureValueOf(T actual) + { + return String.valueOf(actual); + } - /** - * Creates a matcher that matches any examined object whose toString method - * returns a value equalTo the specified string. - * For example: - *
assertThat(true, hasToString("TRUE"))
- * - * @param expectedToString - * the expected toString result - */ - public static Matcher hasToString(String expectedToString) { - return new HasToString(equalTo(expectedToString)); - } + /** + * Creates a matcher that matches any examined object whose toString method + * returns a value that satisfies the specified matcher. + * For example: + *
assertThat(true, hasToString(equalTo("TRUE")))
+ * + * @param toStringMatcher + * the matcher used to verify the toString result + */ + public static Matcher hasToString(Matcher toStringMatcher) + { + return new HasToString(toStringMatcher); + } + + /** + * Creates a matcher that matches any examined object whose toString method + * returns a value equalTo the specified string. + * For example: + *
assertThat(true, hasToString("TRUE"))
+ * + * @param expectedToString + * the expected toString result + */ + public static Matcher hasToString(String expectedToString) + { + return new HasToString(equalTo(expectedToString)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java b/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java index e1410a47..87e1ef1c 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java +++ b/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java @@ -4,38 +4,44 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; -public class IsCompatibleType extends TypeSafeMatcher> { - private final Class type; - - public IsCompatibleType(Class type) { - this.type = type; - } - - @Override - public boolean matchesSafely(Class cls) { - return type.isAssignableFrom(cls); - } - - @Override - public void describeMismatchSafely(Class cls, Description mismatchDescription) { - mismatchDescription.appendValue(cls.getName()); - } - - @Override - public void describeTo(Description description) { - description.appendText("type < ").appendText(type.getName()); - } - - /** - * Creates a matcher of {@link Class} that matches when the specified baseType is - * assignable from the examined class. - * For example: - *
assertThat(Integer.class, typeCompatibleWith(Number.class))
- * - * @param baseType - * the base class to examine classes against - */ - public static Matcher> typeCompatibleWith(Class baseType) { - return new IsCompatibleType(baseType); - } +public class IsCompatibleType extends TypeSafeMatcher> +{ + private final Class type; + + public IsCompatibleType(Class type) + { + this.type = type; + } + + @Override + public boolean matchesSafely(Class cls) + { + return type.isAssignableFrom(cls); + } + + @Override + public void describeMismatchSafely(Class cls, Description mismatchDescription) + { + mismatchDescription.appendValue(cls.getName()); + } + + @Override + public void describeTo(Description description) + { + description.appendText("type < ").appendText(type.getName()); + } + + /** + * Creates a matcher of {@link Class} that matches when the specified baseType is + * assignable from the examined class. + * For example: + *
assertThat(Integer.class, typeCompatibleWith(Number.class))
+ * + * @param baseType + * the base class to examine classes against + */ + public static Matcher> typeCompatibleWith(Class baseType) + { + return new IsCompatibleType(baseType); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java b/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java index 43b64d46..1b777b01 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java +++ b/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java @@ -10,67 +10,76 @@ /** * Tests if the value is an event announced by a specific object. */ -public class IsEventFrom extends TypeSafeDiagnosingMatcher { - private final Class eventClass; - private final Object source; +public class IsEventFrom extends TypeSafeDiagnosingMatcher +{ + private final Class eventClass; + private final Object source; - public IsEventFrom(Class eventClass, Object source) { - this.eventClass = eventClass; - this.source = source; - } + public IsEventFrom(Class eventClass, Object source) + { + this.eventClass = eventClass; + this.source = source; + } - @Override - public boolean matchesSafely(EventObject item, Description mismatchDescription) { - if (!eventClass.isInstance(item)) { - mismatchDescription.appendText("item type was " + item.getClass().getName()); - return false; - } - - if (!eventHasSameSource(item)) { - mismatchDescription.appendText("source was ").appendValue(item.getSource()); - return false; - } - return true; + @Override + public boolean matchesSafely(EventObject item, Description mismatchDescription) + { + if (!eventClass.isInstance(item)) + { + mismatchDescription.appendText("item type was " + item.getClass().getName()); + return false; } - - private boolean eventHasSameSource(EventObject ev) { - return ev.getSource() == source; + if (!eventHasSameSource(item)) + { + mismatchDescription.appendText("source was ").appendValue(item.getSource()); + return false; } + return true; + } - @Override - public void describeTo(Description description) { - description.appendText("an event of type ") - .appendText(eventClass.getName()) - .appendText(" from ") - .appendValue(source); - } - /** - * Creates a matcher of {@link java.util.EventObject} that matches any object - * derived from eventClass announced by source. - * For example: - *
assertThat(myEvent, is(eventFrom(PropertyChangeEvent.class, myBean)))
- * - * @param eventClass - * the class of the event to match on - * @param source - * the source of the event - */ - public static Matcher eventFrom(Class eventClass, Object source) { - return new IsEventFrom(eventClass, source); - } + private boolean eventHasSameSource(EventObject ev) + { + return ev.getSource() == source; + } - /** - * Creates a matcher of {@link java.util.EventObject} that matches any EventObject - * announced by source. - * For example: - *
assertThat(myEvent, is(eventFrom(myBean)))
- * - * @param source - * the source of the event - */ - public static Matcher eventFrom(Object source) { - return eventFrom(EventObject.class, source); - } + @Override + public void describeTo(Description description) + { + description.appendText("an event of type ") + .appendText(eventClass.getName()) + .appendText(" from ") + .appendValue(source); + } + + /** + * Creates a matcher of {@link java.util.EventObject} that matches any object + * derived from eventClass announced by source. + * For example: + *
assertThat(myEvent, is(eventFrom(PropertyChangeEvent.class, myBean)))
+ * + * @param eventClass + * the class of the event to match on + * @param source + * the source of the event + */ + public static Matcher eventFrom(Class eventClass, Object source) + { + return new IsEventFrom(eventClass, source); + } + + /** + * Creates a matcher of {@link java.util.EventObject} that matches any EventObject + * announced by source. + * For example: + *
assertThat(myEvent, is(eventFrom(myBean)))
+ * + * @param source + * the source of the event + */ + public static Matcher eventFrom(Object source) + { + return eventFrom(EventObject.class, source); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java b/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java index e5e3d466..1539774b 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java +++ b/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java @@ -9,49 +9,57 @@ * @author Marco Leichsenring * @author Steve Freeman */ -public class CharSequenceLength extends FeatureMatcher { - - /** - * @param lengthMatcher The matcher to apply to the feature - */ - @SuppressWarnings("WeakerAccess") - public CharSequenceLength(Matcher lengthMatcher) { - super(lengthMatcher, "a CharSequence with length", "length"); - } - - @Override - protected Integer featureValueOf(CharSequence actual) { - return actual.length(); - } - - /** - * Creates a matcher of {@link CharSequence} that matches when a char sequence has the given length - * For example: - * - *
-     * assertThat("text", hasLength(4))
-     * 
- * - * @param length the expected length of the string - */ - public static Matcher hasLength(int length) { - return new CharSequenceLength(equalTo(length)); - } - - /** - * Creates a matcher of {@link CharSequence} that matches when a char sequence has the given length - * For example: - * - *
-      * assertThat("text", hasLength(lessThan(4)))
-      * 
- * - * @param lengthMatcher the expected length of the string - */ - @SuppressWarnings("WeakerAccess") - public static Matcher hasLength(Matcher lengthMatcher) { - return new CharSequenceLength(lengthMatcher); - } +public class CharSequenceLength extends FeatureMatcher +{ + + /** + * @param lengthMatcher + * The matcher to apply to the feature + */ + @SuppressWarnings("WeakerAccess") + public CharSequenceLength(Matcher lengthMatcher) + { + super(lengthMatcher, "a CharSequence with length", "length"); + } + + @Override + protected Integer featureValueOf(CharSequence actual) + { + return actual.length(); + } + + /** + * Creates a matcher of {@link CharSequence} that matches when a char sequence has the given length + * For example: + * + *
+   * assertThat("text", hasLength(4))
+   * 
+ * + * @param length + * the expected length of the string + */ + public static Matcher hasLength(int length) + { + return new CharSequenceLength(equalTo(length)); + } + + /** + * Creates a matcher of {@link CharSequence} that matches when a char sequence has the given length + * For example: + * + *
+   * assertThat("text", hasLength(lessThan(4)))
+   * 
+ * + * @param lengthMatcher + * the expected length of the string + */ + @SuppressWarnings("WeakerAccess") + public static Matcher hasLength(Matcher lengthMatcher) + { + return new CharSequenceLength(lengthMatcher); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java b/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java index b168541b..4371a006 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java @@ -13,43 +13,49 @@ /** * Matches blank Strings (and null). */ -public final class IsBlankString extends TypeSafeMatcher { - private static final IsBlankString BLANK_INSTANCE = new IsBlankString(); - @SuppressWarnings("unchecked") - private static final Matcher NULL_OR_BLANK_INSTANCE = anyOf(nullValue(), BLANK_INSTANCE); - - private static final Pattern REGEX_WHITESPACE = Pattern.compile("\\s*"); - - private IsBlankString() { } - - @Override - public boolean matchesSafely(String item) { - return REGEX_WHITESPACE.matcher(item).matches(); - } - - @Override - public void describeTo(Description description) { - description.appendText("a blank string"); - } - - /** - * Creates a matcher of {@link String} that matches when the examined string contains - * zero or more whitespace characters and nothing else. - * For example: - *
assertThat("  ", is(blankString()))
- */ - public static Matcher blankString() { - return BLANK_INSTANCE; - } - - /** - * Creates a matcher of {@link String} that matches when the examined string is null, or - * contains zero or more whitespace characters and nothing else. - * For example: - *
assertThat(((String)null), is(blankOrNullString()))
- * - */ - public static Matcher blankOrNullString() { - return NULL_OR_BLANK_INSTANCE; - } +public final class IsBlankString extends TypeSafeMatcher +{ + private static final IsBlankString BLANK_INSTANCE = new IsBlankString(); + @SuppressWarnings("unchecked") + private static final Matcher NULL_OR_BLANK_INSTANCE = anyOf(nullValue(), BLANK_INSTANCE); + + private static final Pattern REGEX_WHITESPACE = Pattern.compile("\\s*"); + + private IsBlankString() + { + } + + @Override + public boolean matchesSafely(String item) + { + return REGEX_WHITESPACE.matcher(item).matches(); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a blank string"); + } + + /** + * Creates a matcher of {@link String} that matches when the examined string contains + * zero or more whitespace characters and nothing else. + * For example: + *
assertThat("  ", is(blankString()))
+ */ + public static Matcher blankString() + { + return BLANK_INSTANCE; + } + + /** + * Creates a matcher of {@link String} that matches when the examined string is null, or + * contains zero or more whitespace characters and nothing else. + * For example: + *
assertThat(((String)null), is(blankOrNullString()))
+ */ + public static Matcher blankOrNullString() + { + return NULL_OR_BLANK_INSTANCE; + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java b/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java index bbe56814..9eccbb79 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java @@ -11,67 +11,73 @@ /** * Matches empty Strings (and null). */ -public final class IsEmptyString extends TypeSafeMatcher { - private static final IsEmptyString INSTANCE = new IsEmptyString(); - @SuppressWarnings("unchecked") - private static final Matcher NULL_OR_EMPTY_INSTANCE = anyOf(nullValue(), INSTANCE); +public final class IsEmptyString extends TypeSafeMatcher +{ + private static final IsEmptyString INSTANCE = new IsEmptyString(); + @SuppressWarnings("unchecked") + private static final Matcher NULL_OR_EMPTY_INSTANCE = anyOf(nullValue(), INSTANCE); - private IsEmptyString() { } + private IsEmptyString() + { + } - @Override - public boolean matchesSafely(String item) { - return item.equals(""); - } + @Override + public boolean matchesSafely(String item) + { + return item.equals(""); + } - @Override - public void describeTo(Description description) { - description.appendText("an empty string"); - } + @Override + public void describeTo(Description description) + { + description.appendText("an empty string"); + } - /** - * Creates a matcher of {@link String} that matches when the examined string has zero length. - * For example: - *
assertThat("", isEmptyString())
- * - * @deprecated use is(emptyString()) instead - */ - @Deprecated - public static Matcher isEmptyString() { - return emptyString(); - } + /** + * Creates a matcher of {@link String} that matches when the examined string has zero length. + * For example: + *
assertThat("", isEmptyString())
+ * + * @deprecated use is(emptyString()) instead + */ + @Deprecated + public static Matcher isEmptyString() + { + return emptyString(); + } - /** - * Creates a matcher of {@link String} that matches when the examined string has zero length. - * For example: - *
assertThat("", is(emptyString()))
- * - */ - public static Matcher emptyString() { - return INSTANCE; - } + /** + * Creates a matcher of {@link String} that matches when the examined string has zero length. + * For example: + *
assertThat("", is(emptyString()))
+ */ + public static Matcher emptyString() + { + return INSTANCE; + } - /** - * Creates a matcher of {@link String} that matches when the examined string is null, or - * has zero length. - * For example: - *
assertThat(((String)null), isEmptyOrNullString())
- * - * @deprecated use is(emptyOrNullString()) instead - * - */ - @Deprecated - public static Matcher isEmptyOrNullString() { - return emptyOrNullString(); - } + /** + * Creates a matcher of {@link String} that matches when the examined string is null, or + * has zero length. + * For example: + *
assertThat(((String)null), isEmptyOrNullString())
+ * + * @deprecated use is(emptyOrNullString()) instead + */ + @Deprecated + public static Matcher isEmptyOrNullString() + { + return emptyOrNullString(); + } - /** - * Creates a matcher of {@link String} that matches when the examined string is null, or - * has zero length. - * For example: - *
assertThat(((String)null), is(emptyOrNullString()))
- * - */ - public static Matcher emptyOrNullString() { - return NULL_OR_EMPTY_INSTANCE; - } + /** + * Creates a matcher of {@link String} that matches when the examined string is null, or + * has zero length. + * For example: + *
assertThat(((String)null), is(emptyOrNullString()))
+ */ + public static Matcher emptyOrNullString() + { + return NULL_OR_EMPTY_INSTANCE; + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java b/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java index c3e0d7b1..f3401532 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java @@ -9,66 +9,75 @@ /** * Tests if a string is equal to another string, compressing any changes in whitespace. */ -public class IsEqualCompressingWhiteSpace extends TypeSafeMatcher { +public class IsEqualCompressingWhiteSpace extends TypeSafeMatcher +{ - // TODO: Replace String with CharSequence to allow for easy interoperability between - // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). + // TODO: Replace String with CharSequence to allow for easy interoperability between + // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). - private final String string; + private final String string; - public IsEqualCompressingWhiteSpace(String string) { - if (string == null) { - throw new IllegalArgumentException("Non-null value required"); - } - this.string = string; + public IsEqualCompressingWhiteSpace(String string) + { + if (string == null) + { + throw new IllegalArgumentException("Non-null value required"); } + this.string = string; + } - @Override - public boolean matchesSafely(String item) { - return stripSpaces(string).equals(stripSpaces(item)); - } - - @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("was ").appendValue(item); - } - - @Override - public void describeTo(Description description) { - description.appendText("a string equal to ") - .appendValue(string) - .appendText(" compressing white space"); - } + @Override + public boolean matchesSafely(String item) + { + return stripSpaces(string).equals(stripSpaces(item)); + } - public String stripSpaces(String toBeStripped) { - return toBeStripped.replaceAll("\\s+", " ").trim(); - } + @Override + public void describeMismatchSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("was ").appendValue(item); + } - /** - * @deprecated {@link #equalToCompressingWhiteSpace(String)} - * @param expectedString - * the expected value of matched strings - */ - public static Matcher equalToIgnoringWhiteSpace(String expectedString) { - return new IsEqualCompressingWhiteSpace(expectedString); - } + @Override + public void describeTo(Description description) + { + description.appendText("a string equal to ") + .appendValue(string) + .appendText(" compressing white space"); + } - /** - * Creates a matcher of {@link String} that matches when the examined string is equal to - * the specified expectedString, when whitespace differences are (mostly) ignored. To be - * exact, the following whitespace rules are applied: - *
    - *
  • all leading and trailing whitespace of both the expectedString and the examined string are ignored
  • - *
  • any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
  • - *
- * For example: - *
assertThat("   my\tfoo  bar ", equalToCompressingWhiteSpace(" my  foo bar"))
- * - * @param expectedString - * the expected value of matched strings - */ - public static Matcher equalToCompressingWhiteSpace(String expectedString) { - return new IsEqualCompressingWhiteSpace(expectedString); - } + public String stripSpaces(String toBeStripped) + { + return toBeStripped.replaceAll("\\s+", " ").trim(); + } + + /** + * @param expectedString + * the expected value of matched strings + * @deprecated {@link #equalToCompressingWhiteSpace(String)} + */ + public static Matcher equalToIgnoringWhiteSpace(String expectedString) + { + return new IsEqualCompressingWhiteSpace(expectedString); + } + + /** + * Creates a matcher of {@link String} that matches when the examined string is equal to + * the specified expectedString, when whitespace differences are (mostly) ignored. To be + * exact, the following whitespace rules are applied: + *
    + *
  • all leading and trailing whitespace of both the expectedString and the examined string are ignored
  • + *
  • any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
  • + *
+ * For example: + *
assertThat("   my\tfoo  bar ", equalToCompressingWhiteSpace(" my  foo bar"))
+ * + * @param expectedString + * the expected value of matched strings + */ + public static Matcher equalToCompressingWhiteSpace(String expectedString) + { + return new IsEqualCompressingWhiteSpace(expectedString); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java b/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java index defa6123..2d51e20e 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java @@ -7,48 +7,55 @@ /** * Tests if a string is equal to another string, regardless of the case. */ -public class IsEqualIgnoringCase extends TypeSafeMatcher { +public class IsEqualIgnoringCase extends TypeSafeMatcher +{ - // TODO: Replace String with CharSequence to allow for easy interoperability between - // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). + // TODO: Replace String with CharSequence to allow for easy interoperability between + // String, StringBuffer, StringBuilder, CharBuffer, etc (joe). - private final String string; + private final String string; - public IsEqualIgnoringCase(String string) { - if (string == null) { - throw new IllegalArgumentException("Non-null value required"); - } - this.string = string; - } - - @Override - public boolean matchesSafely(String item) { - return string.equalsIgnoreCase(item); - } - - @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("was ").appendValue(item); - } - - @Override - public void describeTo(Description description) { - description.appendText("a string equal to ") - .appendValue(string) - .appendText(" ignoring case"); - } - - /** - * Creates a matcher of {@link String} that matches when the examined string is equal to - * the specified expectedString, ignoring case. - * For example: - *
assertThat("Foo", equalToIgnoringCase("FOO"))
- * - * @param expectedString - * the expected value of matched strings - */ - public static Matcher equalToIgnoringCase(String expectedString) { - return new IsEqualIgnoringCase(expectedString); + public IsEqualIgnoringCase(String string) + { + if (string == null) + { + throw new IllegalArgumentException("Non-null value required"); } + this.string = string; + } + + @Override + public boolean matchesSafely(String item) + { + return string.equalsIgnoreCase(item); + } + + @Override + public void describeMismatchSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("was ").appendValue(item); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a string equal to ") + .appendValue(string) + .appendText(" ignoring case"); + } + + /** + * Creates a matcher of {@link String} that matches when the examined string is equal to + * the specified expectedString, ignoring case. + * For example: + *
assertThat("Foo", equalToIgnoringCase("FOO"))
+ * + * @param expectedString + * the expected value of matched strings + */ + public static Matcher equalToIgnoringCase(String expectedString) + { + return new IsEqualIgnoringCase(expectedString); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java b/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java index e0eda0a8..77a8ca91 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java +++ b/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java @@ -6,36 +6,42 @@ import java.util.regex.Pattern; -public class MatchesPattern extends TypeSafeMatcher { - private final Pattern pattern; - - public MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - protected boolean matchesSafely(String item) { - return pattern.matcher(item).matches(); - } - - @Override - public void describeTo(Description description) { - description.appendText("a string matching the pattern '" + pattern + "'"); - } - - /** - * Creates a matcher of {@link java.lang.String} that matches when the examined string - * exactly matches the given {@link java.util.regex.Pattern}. - */ - public static Matcher matchesPattern(Pattern pattern) { - return new MatchesPattern(pattern); - } - - /** - * Creates a matcher of {@link java.lang.String} that matches when the examined string - * exactly matches the given regular expression, treated as a {@link java.util.regex.Pattern}. - */ - public static Matcher matchesPattern(String regex) { - return new MatchesPattern(Pattern.compile(regex)); - } +public class MatchesPattern extends TypeSafeMatcher +{ + private final Pattern pattern; + + public MatchesPattern(Pattern pattern) + { + this.pattern = pattern; + } + + @Override + protected boolean matchesSafely(String item) + { + return pattern.matcher(item).matches(); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a string matching the pattern '" + pattern + "'"); + } + + /** + * Creates a matcher of {@link java.lang.String} that matches when the examined string + * exactly matches the given {@link java.util.regex.Pattern}. + */ + public static Matcher matchesPattern(Pattern pattern) + { + return new MatchesPattern(pattern); + } + + /** + * Creates a matcher of {@link java.lang.String} that matches when the examined string + * exactly matches the given regular expression, treated as a {@link java.util.regex.Pattern}. + */ + public static Matcher matchesPattern(String regex) + { + return new MatchesPattern(Pattern.compile(regex)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java b/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java index 6df9a531..85fd53b0 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java @@ -6,65 +6,74 @@ import java.util.Arrays; -public class StringContainsInOrder extends TypeSafeMatcher { - private final Iterable substrings; +public class StringContainsInOrder extends TypeSafeMatcher +{ + private final Iterable substrings; - public StringContainsInOrder(Iterable substrings) { - this.substrings = substrings; - } + public StringContainsInOrder(Iterable substrings) + { + this.substrings = substrings; + } - @Override - public boolean matchesSafely(String s) { - int fromIndex = 0; - - for (String substring : substrings) { - fromIndex = s.indexOf(substring, fromIndex); - if (fromIndex == -1) { - return false; - } - fromIndex++; - } - - return true; - } - - @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("was \"").appendText(item).appendText("\""); - } - - @Override - public void describeTo(Description description) { - description.appendText("a string containing ") - .appendValueList("", ", ", "", substrings) - .appendText(" in order"); - } - - /** - * Creates a matcher of {@link String} that matches when the examined string contains all of - * the specified substrings, considering the order of their appearance. - * For example: - *
assertThat("myfoobarbaz", stringContainsInOrder(Arrays.asList("bar", "foo")))
- * fails as "foo" occurs before "bar" in the string "myfoobarbaz" - * - * @param substrings - * the substrings that must be contained within matching strings - */ - public static Matcher stringContainsInOrder(Iterable substrings) { - return new StringContainsInOrder(substrings); - } + @Override + public boolean matchesSafely(String s) + { + int fromIndex = 0; - /** - * Creates a matcher of {@link String} that matches when the examined string contains all of - * the specified substrings, considering the order of their appearance. - * For example: - *
assertThat("myfoobarbaz", stringContainsInOrder("bar", "foo"))
- * fails as "foo" occurs before "bar" in the string "myfoobarbaz" - * - * @param substrings - * the substrings that must be contained within matching strings - */ - public static Matcher stringContainsInOrder(String... substrings) { - return new StringContainsInOrder(Arrays.asList(substrings)); + for (String substring : substrings) + { + fromIndex = s.indexOf(substring, fromIndex); + if (fromIndex == -1) + { + return false; + } + fromIndex++; } + + return true; + } + + @Override + public void describeMismatchSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("was \"").appendText(item).appendText("\""); + } + + @Override + public void describeTo(Description description) + { + description.appendText("a string containing ") + .appendValueList("", ", ", "", substrings) + .appendText(" in order"); + } + + /** + * Creates a matcher of {@link String} that matches when the examined string contains all of + * the specified substrings, considering the order of their appearance. + * For example: + *
assertThat("myfoobarbaz", stringContainsInOrder(Arrays.asList("bar", "foo")))
+ * fails as "foo" occurs before "bar" in the string "myfoobarbaz" + * + * @param substrings + * the substrings that must be contained within matching strings + */ + public static Matcher stringContainsInOrder(Iterable substrings) + { + return new StringContainsInOrder(substrings); + } + + /** + * Creates a matcher of {@link String} that matches when the examined string contains all of + * the specified substrings, considering the order of their appearance. + * For example: + *
assertThat("myfoobarbaz", stringContainsInOrder("bar", "foo"))
+ * fails as "foo" occurs before "bar" in the string "myfoobarbaz" + * + * @param substrings + * the substrings that must be contained within matching strings + */ + public static Matcher stringContainsInOrder(String... substrings) + { + return new StringContainsInOrder(Arrays.asList(substrings)); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java b/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java index 30ed081a..91927914 100644 --- a/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java +++ b/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java @@ -21,149 +21,178 @@ * @author Joe Walnes * @author Steve Freeman */ -public class HasXPath extends TypeSafeDiagnosingMatcher { - public static final NamespaceContext NO_NAMESPACE_CONTEXT = null; - private static final IsAnything WITH_ANY_CONTENT = new IsAnything(""); - private static final Condition.Step NODE_EXISTS = nodeExists(); - private final Matcher valueMatcher; - private final XPathExpression compiledXPath; - private final String xpathString; - private final QName evaluationMode; - - /** - * @param xPathExpression XPath expression. - * @param valueMatcher Matcher to use at given XPath. - * May be null to specify that the XPath must exist but the value is irrelevant. - */ - public HasXPath(String xPathExpression, Matcher valueMatcher) { - this(xPathExpression, NO_NAMESPACE_CONTEXT, valueMatcher); +public class HasXPath extends TypeSafeDiagnosingMatcher +{ + public static final NamespaceContext NO_NAMESPACE_CONTEXT = null; + private static final IsAnything WITH_ANY_CONTENT = new IsAnything(""); + private static final Condition.Step NODE_EXISTS = nodeExists(); + private final Matcher valueMatcher; + private final XPathExpression compiledXPath; + private final String xpathString; + private final QName evaluationMode; + + /** + * @param xPathExpression + * XPath expression. + * @param valueMatcher + * Matcher to use at given XPath. + * May be null to specify that the XPath must exist but the value is irrelevant. + */ + public HasXPath(String xPathExpression, Matcher valueMatcher) + { + this(xPathExpression, NO_NAMESPACE_CONTEXT, valueMatcher); + } + + /** + * @param xPathExpression + * XPath expression. + * @param namespaceContext + * Resolves XML namespace prefixes in the XPath expression + * @param valueMatcher + * Matcher to use at given XPath. + * May be null to specify that the XPath must exist but the value is irrelevant. + */ + public HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher) + { + this(xPathExpression, namespaceContext, valueMatcher, STRING); + } + + private HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher, QName mode) + { + this.compiledXPath = compiledXPath(xPathExpression, namespaceContext); + this.xpathString = xPathExpression; + this.valueMatcher = valueMatcher; + this.evaluationMode = mode; + } + + @Override + public boolean matchesSafely(Node item, Description mismatch) + { + return evaluated(item, mismatch) + .and(NODE_EXISTS) + .matching(valueMatcher); + } + + @Override + public void describeTo(Description description) + { + description.appendText("an XML document with XPath ").appendText(xpathString); + if (valueMatcher != null) + { + description.appendText(" ").appendDescriptionOf(valueMatcher); } + } - /** - * @param xPathExpression XPath expression. - * @param namespaceContext Resolves XML namespace prefixes in the XPath expression - * @param valueMatcher Matcher to use at given XPath. - * May be null to specify that the XPath must exist but the value is irrelevant. - */ - public HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher) { - this(xPathExpression, namespaceContext, valueMatcher, STRING); + private Condition evaluated(Node item, Description mismatch) + { + try + { + return matched(compiledXPath.evaluate(item, evaluationMode), mismatch); } - - private HasXPath(String xPathExpression, NamespaceContext namespaceContext, Matcher valueMatcher, QName mode) { - this.compiledXPath = compiledXPath(xPathExpression, namespaceContext); - this.xpathString = xPathExpression; - this.valueMatcher = valueMatcher; - this.evaluationMode = mode; - } - - @Override - public boolean matchesSafely(Node item, Description mismatch) { - return evaluated(item, mismatch) - .and(NODE_EXISTS) - .matching(valueMatcher); - } - - @Override - public void describeTo(Description description) { - description.appendText("an XML document with XPath ").appendText(xpathString); - if (valueMatcher != null) { - description.appendText(" ").appendDescriptionOf(valueMatcher); - } - } - - private Condition evaluated(Node item, Description mismatch) { - try { - return matched(compiledXPath.evaluate(item, evaluationMode), mismatch); - } catch (XPathExpressionException e) { - mismatch.appendText(e.getMessage()); - } - return notMatched(); - } - - private static Condition.Step nodeExists() { - return new Condition.Step() { - @Override - public Condition apply(Object value, Description mismatch) { - if (value == null) { - mismatch.appendText("xpath returned no results."); - return notMatched(); - } - return matched(String.valueOf(value), mismatch); - } - }; + catch (XPathExpressionException e) + { + mismatch.appendText(e.getMessage()); } - - private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) { - try { - final XPath xPath = XPathFactory.newInstance().newXPath(); - if (namespaceContext != null) { - xPath.setNamespaceContext(namespaceContext); - } - return xPath.compile(xPathExpression); - } catch (XPathExpressionException e) { - throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e); + return notMatched(); + } + + private static Condition.Step nodeExists() + { + return new Condition.Step() + { + @Override + public Condition apply(Object value, Description mismatch) + { + if (value == null) + { + mismatch.appendText("xpath returned no results."); + return notMatched(); } + return matched(String.valueOf(value), mismatch); + } + }; + } + + private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) + { + try + { + final XPath xPath = XPathFactory.newInstance().newXPath(); + if (namespaceContext != null) + { + xPath.setNamespaceContext(namespaceContext); + } + return xPath.compile(xPathExpression); } - - - /** - * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the - * specified xPath that satisfies the specified valueMatcher. - * For example: - *
assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar")))
- * - * @param xPath - * the target xpath - * @param valueMatcher - * matcher for the value at the specified xpath - */ - public static Matcher hasXPath(String xPath, Matcher valueMatcher) { - return hasXPath(xPath, NO_NAMESPACE_CONTEXT, valueMatcher); - } - - /** - * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the - * specified xPath, within the specified namespaceContext, that satisfies - * the specified valueMatcher. - * For example: - *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs, equalTo("Cheddar")))
- * - * @param xPath - * the target xpath - * @param namespaceContext - * the namespace for matching nodes - * @param valueMatcher - * matcher for the value at the specified xpath - */ - public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext, Matcher valueMatcher) { - return new HasXPath(xPath, namespaceContext, valueMatcher, STRING); - } - - /** - * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node - * at the specified xPath, with any content. - * For example: - *
assertThat(xml, hasXPath("/root/something[2]/cheese"))
- * - * @param xPath - * the target xpath - */ - public static Matcher hasXPath(String xPath) { - return hasXPath(xPath, NO_NAMESPACE_CONTEXT); - } - - /** - * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node - * at the specified xPath within the specified namespace context, with any content. - * For example: - *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs))
- * - * @param xPath - * the target xpath - * @param namespaceContext - * the namespace for matching nodes - */ - public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext) { - return new HasXPath(xPath, namespaceContext, WITH_ANY_CONTENT, XPathConstants.NODE); + catch (XPathExpressionException e) + { + throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e); } + } + + + /** + * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the + * specified xPath that satisfies the specified valueMatcher. + * For example: + *
assertThat(xml, hasXPath("/root/something[2]/cheese", equalTo("Cheddar")))
+ * + * @param xPath + * the target xpath + * @param valueMatcher + * matcher for the value at the specified xpath + */ + public static Matcher hasXPath(String xPath, Matcher valueMatcher) + { + return hasXPath(xPath, NO_NAMESPACE_CONTEXT, valueMatcher); + } + + /** + * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node has a value at the + * specified xPath, within the specified namespaceContext, that satisfies + * the specified valueMatcher. + * For example: + *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs, equalTo("Cheddar")))
+ * + * @param xPath + * the target xpath + * @param namespaceContext + * the namespace for matching nodes + * @param valueMatcher + * matcher for the value at the specified xpath + */ + public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext, Matcher valueMatcher) + { + return new HasXPath(xPath, namespaceContext, valueMatcher, STRING); + } + + /** + * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node + * at the specified xPath, with any content. + * For example: + *
assertThat(xml, hasXPath("/root/something[2]/cheese"))
+ * + * @param xPath + * the target xpath + */ + public static Matcher hasXPath(String xPath) + { + return hasXPath(xPath, NO_NAMESPACE_CONTEXT); + } + + /** + * Creates a matcher of {@link org.w3c.dom.Node}s that matches when the examined node contains a node + * at the specified xPath within the specified namespace context, with any content. + * For example: + *
assertThat(xml, hasXPath("/root/something[2]/cheese", myNs))
+ * + * @param xPath + * the target xpath + * @param namespaceContext + * the namespace for matching nodes + */ + public static Matcher hasXPath(String xPath, NamespaceContext namespaceContext) + { + return new HasXPath(xPath, namespaceContext, WITH_ANY_CONTENT, XPathConstants.NODE); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java index f11dec3b..c2d70a1a 100644 --- a/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java @@ -3,75 +3,94 @@ import junit.framework.TestCase; import org.junit.Assert; -public abstract class AbstractMatcherTest extends TestCase { +public abstract class AbstractMatcherTest extends TestCase +{ /** * Create an instance of the Matcher so some generic safety-net tests can be run on it. */ protected abstract Matcher createMatcher(); - - public static void assertMatches(Matcher matcher, T arg) { - assertMatches("Expected match, but mismatched", matcher, arg); + + public static void assertMatches(Matcher matcher, T arg) + { + assertMatches("Expected match, but mismatched", matcher, arg); } - public static void assertMatches(String message, Matcher matcher, Object arg) { - if (!matcher.matches(arg)) { + public static void assertMatches(String message, Matcher matcher, Object arg) + { + if (!matcher.matches(arg)) + { Assert.fail(message + " because: '" + mismatchDescription(matcher, arg) + "'"); } } - public static void assertDoesNotMatch(Matcher c, T arg) { - assertDoesNotMatch("Unexpected match", c, arg); + public static void assertDoesNotMatch(Matcher c, T arg) + { + assertDoesNotMatch("Unexpected match", c, arg); } - public static void assertDoesNotMatch(String message, Matcher c, T arg) { + public static void assertDoesNotMatch(String message, Matcher c, T arg) + { Assert.assertFalse(message, c.matches(arg)); } - public static void assertDescription(String expected, Matcher matcher) { + public static void assertDescription(String expected, Matcher matcher) + { Description description = new StringDescription(); description.appendDescriptionOf(matcher); Assert.assertEquals("Expected description", expected, description.toString().trim()); } - public static void assertMismatchDescription(String expected, Matcher matcher, Object arg) { + public static void assertMismatchDescription(String expected, Matcher matcher, Object arg) + { Assert.assertFalse("Precondition: Matcher should not match item.", matcher.matches(arg)); Assert.assertEquals("Expected mismatch description", expected, mismatchDescription(matcher, arg)); } - - public static void assertNullSafe(Matcher matcher) { - try { - matcher.matches(null); - } - catch (Exception e) { - Assert.fail("Matcher was not null safe"); - } + + public static void assertNullSafe(Matcher matcher) + { + try + { + matcher.matches(null); + } + catch (Exception e) + { + Assert.fail("Matcher was not null safe"); + } } - public static void assertUnknownTypeSafe(Matcher matcher) { - try { - matcher.matches(new UnknownType()); - } catch (Exception e) { - Assert.fail("Matcher was not unknown type safe, because: " + e); - } + public static void assertUnknownTypeSafe(Matcher matcher) + { + try + { + matcher.matches(new UnknownType()); + } + catch (Exception e) + { + Assert.fail("Matcher was not unknown type safe, because: " + e); + } } - public void testIsNullSafe() { + public void testIsNullSafe() + { assertNullSafe(createMatcher()); } - public void testCopesWithUnknownTypes() { + public void testCopesWithUnknownTypes() + { createMatcher().matches(new UnknownType()); } - private static String mismatchDescription(Matcher matcher, Object arg) { - Description description = new StringDescription(); - matcher.describeMismatch(arg, description); - return description.toString().trim(); - } + private static String mismatchDescription(Matcher matcher, Object arg) + { + Description description = new StringDescription(); + matcher.describeMismatch(arg, description); + return description.toString().trim(); + } @SuppressWarnings("WeakerAccess") - public static class UnknownType { + public static class UnknownType + { } } diff --git a/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java b/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java index afbdd65f..9505f2cb 100644 --- a/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java @@ -4,111 +4,131 @@ import static org.junit.Assert.assertEquals; -public final class BaseDescriptionTest { +public final class BaseDescriptionTest +{ - private final StringBuilder result = new StringBuilder(); + private final StringBuilder result = new StringBuilder(); - private final BaseDescription baseDescription = new BaseDescription() { - @Override protected void append(char c) { - result.append(c); - } - }; - - @Test public void - describesAppendedNullValue() { - baseDescription.appendValue(null); - assertEquals("null", result.toString()); - } - - @Test public void - quotesAppendedStringValue() { - baseDescription.appendValue("foo"); - assertEquals("\"foo\"", result.toString()); - } - - @Test public void - quotesAppendedCharacterValue() { - baseDescription.appendValue('f'); - assertEquals("\"f\"", result.toString()); - } - - @Test public void - quotesAppendedTab() { - baseDescription.appendValue('\t'); - assertEquals("\"\\t\"", result.toString()); - } - - @Test public void - quotesAppendedNewLine() { - baseDescription.appendValue('\n'); - assertEquals("\"\\n\"", result.toString()); - } - - @Test public void - quotesAppendedLineReturn() { - baseDescription.appendValue('\r'); - assertEquals("\"\\r\"", result.toString()); - } - - @Test public void - quotesAppendedBackslash() { - baseDescription.appendValue('\\'); - assertEquals("\"\\\\\"", result.toString()); - } - - @Test public void - quotesAppendedDoubleQuotes() { - baseDescription.appendValue('"'); - assertEquals("\"\\\"\"", result.toString()); - } - - @Test public void - bracketsAppendedByteValue() { - baseDescription.appendValue(Byte.valueOf("2")); - assertEquals("<2b>", result.toString()); - } - - @Test public void - bracketsAppendedShortValue() { - baseDescription.appendValue(Short.valueOf("2")); - assertEquals("<2s>", result.toString()); - } - - @Test public void - bracketsAppendedLongValue() { - baseDescription.appendValue(Long.valueOf("2")); - assertEquals("<2L>", result.toString()); - } - - @Test public void - bracketsAppendedFloatValue() { - baseDescription.appendValue(Float.valueOf("1.2")); - assertEquals("<1.2F>", result.toString()); - } - - @Test public void - describesAppendedArrayValue() { - baseDescription.appendValue(new String[] {"2", "3"}); - assertEquals("[\"2\", \"3\"]", result.toString()); + private final BaseDescription baseDescription = new BaseDescription() + { + @Override protected void append(char c) + { + result.append(c); } + }; + + @Test public void + describesAppendedNullValue() + { + baseDescription.appendValue(null); + assertEquals("null", result.toString()); + } + + @Test public void + quotesAppendedStringValue() + { + baseDescription.appendValue("foo"); + assertEquals("\"foo\"", result.toString()); + } + + @Test public void + quotesAppendedCharacterValue() + { + baseDescription.appendValue('f'); + assertEquals("\"f\"", result.toString()); + } + + @Test public void + quotesAppendedTab() + { + baseDescription.appendValue('\t'); + assertEquals("\"\\t\"", result.toString()); + } + + @Test public void + quotesAppendedNewLine() + { + baseDescription.appendValue('\n'); + assertEquals("\"\\n\"", result.toString()); + } + + @Test public void + quotesAppendedLineReturn() + { + baseDescription.appendValue('\r'); + assertEquals("\"\\r\"", result.toString()); + } + + @Test public void + quotesAppendedBackslash() + { + baseDescription.appendValue('\\'); + assertEquals("\"\\\\\"", result.toString()); + } + + @Test public void + quotesAppendedDoubleQuotes() + { + baseDescription.appendValue('"'); + assertEquals("\"\\\"\"", result.toString()); + } + + @Test public void + bracketsAppendedByteValue() + { + baseDescription.appendValue(Byte.valueOf("2")); + assertEquals("<2b>", result.toString()); + } + + @Test public void + bracketsAppendedShortValue() + { + baseDescription.appendValue(Short.valueOf("2")); + assertEquals("<2s>", result.toString()); + } + + @Test public void + bracketsAppendedLongValue() + { + baseDescription.appendValue(Long.valueOf("2")); + assertEquals("<2L>", result.toString()); + } + + @Test public void + bracketsAppendedFloatValue() + { + baseDescription.appendValue(Float.valueOf("1.2")); + assertEquals("<1.2F>", result.toString()); + } + + @Test public void + describesAppendedArrayValue() + { + baseDescription.appendValue(new String[] { "2", "3" }); + assertEquals("[\"2\", \"3\"]", result.toString()); + } + + @Test public void + bracketsAppendedObjectValue() + { + final Object value = new Object(); + baseDescription.appendValue(value); + assertEquals("<" + value.toString() + ">", result.toString()); + } + + @Test public void + safelyDescribesAppendedValueOfObjectWhoseToStringThrowsAnException() + { + final Object value = new Object() + { + @Override public String toString() + { + throw new UnsupportedOperationException(); + } + }; - @Test public void - bracketsAppendedObjectValue() { - final Object value = new Object(); - baseDescription.appendValue(value); - assertEquals("<" + value.toString() + ">", result.toString()); - } - - @Test public void - safelyDescribesAppendedValueOfObjectWhoseToStringThrowsAnException() { - final Object value = new Object() { - @Override public String toString() { - throw new UnsupportedOperationException(); - } - }; - - final String expected = value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); - baseDescription.appendValue(value); - assertEquals("<" + expected + ">", result.toString()); - } + final String expected = value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); + baseDescription.appendValue(value); + assertEquals("<" + expected + ">", result.toString()); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java index e663f041..a003936e 100644 --- a/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java @@ -4,23 +4,28 @@ import static org.junit.Assert.assertEquals; -public final class BaseMatcherTest { +public final class BaseMatcherTest +{ - @Test - public void - describesItselfWithToStringMethod() { - Matcher someMatcher = new BaseMatcher() { - @Override - public boolean matches(Object item) { - throw new UnsupportedOperationException(); - } + @Test + public void + describesItselfWithToStringMethod() + { + Matcher someMatcher = new BaseMatcher() + { + @Override + public boolean matches(Object item) + { + throw new UnsupportedOperationException(); + } - @Override - public void describeTo(Description description) { - description.appendText("SOME DESCRIPTION"); - } - }; + @Override + public void describeTo(Description description) + { + description.appendText("SOME DESCRIPTION"); + } + }; - assertEquals("SOME DESCRIPTION", someMatcher.toString()); - } + assertEquals("SOME DESCRIPTION", someMatcher.toString()); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java index 08649f7a..862d0db3 100644 --- a/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java @@ -4,17 +4,21 @@ import static org.hamcrest.AbstractMatcherTest.assertDescription; -public final class CustomMatcherTest { +public final class CustomMatcherTest +{ - @Test public void - usesStaticDescription() throws Exception { - Matcher matcher = new CustomMatcher("I match strings") { - @Override - public boolean matches(Object item) { - return (item instanceof String); - } - }; + @Test public void + usesStaticDescription() throws Exception + { + Matcher matcher = new CustomMatcher("I match strings") + { + @Override + public boolean matches(Object item) + { + return (item instanceof String); + } + }; - assertDescription("I match strings", matcher); - } + assertDescription("I match strings", matcher); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java index 2c867126..a0bb2dc8 100644 --- a/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java @@ -4,38 +4,46 @@ import static org.hamcrest.AbstractMatcherTest.*; -public final class CustomTypeSafeMatcherTest { - private static final String STATIC_DESCRIPTION = "I match non empty strings"; - - private final Matcher customMatcher = new CustomTypeSafeMatcher(STATIC_DESCRIPTION) { - @Override - public boolean matchesSafely(String item) { - return false; - } - - @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("an " + item); - } - }; - - @Test public void - usesStaticDescription() throws Exception { - assertDescription(STATIC_DESCRIPTION, customMatcher); +public final class CustomTypeSafeMatcherTest +{ + private static final String STATIC_DESCRIPTION = "I match non empty strings"; + + private final Matcher customMatcher = new CustomTypeSafeMatcher(STATIC_DESCRIPTION) + { + @Override + public boolean matchesSafely(String item) + { + return false; } - @Test public void - reportsMismatch() { - assertMismatchDescription("an item", customMatcher, "item"); - } - - @Test public void - isNullSafe() { - assertNullSafe(customMatcher); - } - - @Test public void - copesWithUnknownTypes() { - assertUnknownTypeSafe(customMatcher); + @Override + public void describeMismatchSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("an " + item); } + }; + + @Test public void + usesStaticDescription() throws Exception + { + assertDescription(STATIC_DESCRIPTION, customMatcher); + } + + @Test public void + reportsMismatch() + { + assertMismatchDescription("an item", customMatcher, "item"); + } + + @Test public void + isNullSafe() + { + assertNullSafe(customMatcher); + } + + @Test public void + copesWithUnknownTypes() + { + assertUnknownTypeSafe(customMatcher); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java index 8d864eb8..adf056f8 100644 --- a/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java @@ -6,63 +6,84 @@ import static org.hamcrest.AbstractMatcherTest.*; import static org.junit.Assert.assertEquals; -public final class FeatureMatcherTest { - private final FeatureMatcher resultMatcher = resultMatcher(); +public final class FeatureMatcherTest +{ + private final FeatureMatcher resultMatcher = resultMatcher(); - @Test public void - matchesPartOfAnObject() { - assertMatches("feature", resultMatcher, new Thingy("bar")); - assertDescription("Thingy with result \"bar\"", resultMatcher); - } + @Test public void + matchesPartOfAnObject() + { + assertMatches("feature", resultMatcher, new Thingy("bar")); + assertDescription("Thingy with result \"bar\"", resultMatcher); + } - @Test public void - mismatchesPartOfAnObject() { - assertMismatchDescription("result mismatch-description", resultMatcher, new Thingy("foo")); - } + @Test public void + mismatchesPartOfAnObject() + { + assertMismatchDescription("result mismatch-description", resultMatcher, new Thingy("foo")); + } - @Test public void - doesNotThrowNullPointerException() { - assertMismatchDescription("was null", resultMatcher, null); - } + @Test public void + doesNotThrowNullPointerException() + { + assertMismatchDescription("was null", resultMatcher, null); + } - @Test public void - doesNotThrowClassCastException() { - resultMatcher.matches(new ShouldNotMatch()); - StringDescription mismatchDescription = new StringDescription(); - resultMatcher.describeMismatch(new ShouldNotMatch(), mismatchDescription); - assertEquals("was ShouldNotMatch ", mismatchDescription.toString()); - } + @Test public void + doesNotThrowClassCastException() + { + resultMatcher.matches(new ShouldNotMatch()); + StringDescription mismatchDescription = new StringDescription(); + resultMatcher.describeMismatch(new ShouldNotMatch(), mismatchDescription); + assertEquals("was ShouldNotMatch ", mismatchDescription.toString()); + } - public static class Match extends IsEqual { - public Match(String equalArg) { super(equalArg); } - @Override public void describeMismatch(Object item, Description description) { - description.appendText("mismatch-description"); - } + public static class Match extends IsEqual + { + public Match(String equalArg) + { + super(equalArg); } - public static class Thingy { - private final String result; + @Override public void describeMismatch(Object item, Description description) + { + description.appendText("mismatch-description"); + } + } - public Thingy(String result) { - this.result = result; - } + public static class Thingy + { + private final String result; - public String getResult() { - return result; - } + public Thingy(String result) + { + this.result = result; } - public static class ShouldNotMatch { - @Override public String toString() { return "ShouldNotMatch"; } - } + public String getResult() + { + return result; + } + } - private static FeatureMatcher resultMatcher() { - return new FeatureMatcher(new Match("bar"), "Thingy with result", "result") { - @Override - public String featureValueOf(Thingy actual) { - return actual.getResult(); - } - }; + public static class ShouldNotMatch + { + @Override public String toString() + { + return "ShouldNotMatch"; } + } + + private static FeatureMatcher resultMatcher() + { + return new FeatureMatcher(new Match("bar"), "Thingy with result", "result") + { + @Override + public String featureValueOf(Thingy actual) + { + return actual.getResult(); + } + }; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java b/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java index 8d88daa8..c63ad3cf 100644 --- a/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java +++ b/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java @@ -6,20 +6,24 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; -public final class MatcherAssertTest { +public final class MatcherAssertTest +{ @Test public void - includesDescriptionOfTestedValueInErrorMessage() { + includesDescriptionOfTestedValueInErrorMessage() + { String expected = "expected"; String actual = "actual"; String endLine = System.lineSeparator(); String expectedMessage = "identifier" + endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; - try { + try + { assertThat("identifier", actual, equalTo(expected)); } - catch (AssertionError e) { + catch (AssertionError e) + { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } @@ -28,17 +32,20 @@ public final class MatcherAssertTest { } @Test public void - descriptionCanBeElided() { + descriptionCanBeElided() + { String expected = "expected"; String actual = "actual"; String endLine = System.lineSeparator(); String expectedMessage = endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; - try { + try + { assertThat(actual, equalTo(expected)); } - catch (AssertionError e) { + catch (AssertionError e) + { assertTrue(e.getMessage().startsWith(expectedMessage)); return; } @@ -47,13 +54,16 @@ public final class MatcherAssertTest { } @Test public void - canTestBooleanDirectly() { + canTestBooleanDirectly() + { assertThat("success reason message", true); - try { + try + { assertThat("failing reason message", false); } - catch (AssertionError e) { + catch (AssertionError e) + { assertEquals("failing reason message", e.getMessage()); return; } @@ -62,20 +72,25 @@ public final class MatcherAssertTest { } @Test public void - includesMismatchDescription() { - Matcher matcherWithCustomMismatchDescription = new BaseMatcher() { + includesMismatchDescription() + { + Matcher matcherWithCustomMismatchDescription = new BaseMatcher() + { @Override - public boolean matches(Object item) { + public boolean matches(Object item) + { return false; } @Override - public void describeTo(Description description) { + public void describeTo(Description description) + { description.appendText("Something cool"); } @Override - public void describeMismatch(Object item, Description mismatchDescription) { + public void describeMismatch(Object item, Description mismatchDescription) + { mismatchDescription.appendText("Not cool"); } }; @@ -83,17 +98,20 @@ public void describeMismatch(Object item, Description mismatchDescription) { String endLine = System.lineSeparator(); String expectedMessage = endLine + "Expected: Something cool" + endLine + " but: Not cool"; - try { + try + { assertThat("Value", matcherWithCustomMismatchDescription); fail("should have failed"); } - catch (AssertionError e) { + catch (AssertionError e) + { assertEquals(expectedMessage, e.getMessage()); } } @Test public void - canAssertSubtypes() { + canAssertSubtypes() + { assertThat(1, equalTo((Number) 1)); } } diff --git a/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java b/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java index cccece0a..f7e1d220 100644 --- a/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java @@ -5,14 +5,16 @@ import static org.junit.Assert.assertEquals; -public final class NullDescriptionTest { +public final class NullDescriptionTest +{ - private final NullDescription nullDescription = new Description.NullDescription(); + private final NullDescription nullDescription = new Description.NullDescription(); - @Test public void - isUnchangedByAppendedText() { - nullDescription.appendText("myText"); - assertEquals("", nullDescription.toString()); - } + @Test public void + isUnchangedByAppendedText() + { + nullDescription.appendText("myText"); + assertEquals("", nullDescription.toString()); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java index 0b001391..5b7ff617 100644 --- a/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java @@ -8,74 +8,106 @@ * @author Steve Freeman 2016 http://www.hamcrest.com */ @SuppressWarnings("WeakerAccess") -public class TypeSafeDiagnosingMatcherTest { +public class TypeSafeDiagnosingMatcherTest +{ + + @Test public void + describesMismatches() + { + assertMismatchDescription("was null", STRING_MATCHER, null); + assertMismatchDescription("was Character \"c\"", STRING_MATCHER, 'c'); + assertMismatchDescription("mismatching", STRING_MATCHER, "other"); + } - @Test public void - describesMismatches() { - assertMismatchDescription("was null", STRING_MATCHER, null); - assertMismatchDescription("was Character \"c\"", STRING_MATCHER, 'c'); - assertMismatchDescription("mismatching", STRING_MATCHER, "other"); - } + @Test public void + detects_non_builtin_types() + { + final Matcher matcher = new TypeSafeDiagnosingMatcher() + { + @Override + protected boolean matchesSafely(NotBuiltIn item, Description mismatchDescription) + { + return true; + } + + @Override public void describeTo(Description description) + { + description.appendText("a not builtin"); + } + }; - @Test public void - detects_non_builtin_types() { - final Matcher matcher = new TypeSafeDiagnosingMatcher() { - @Override - protected boolean matchesSafely(NotBuiltIn item, Description mismatchDescription) { - return true; - } + assertMatches("not built in", matcher, new NotBuiltIn()); + assertDoesNotMatch("other not built in", (Matcher) matcher, new OtherNotBuiltIn()); + } - @Override public void describeTo(Description description) { description.appendText("a not builtin"); } - }; + @Test public void + filters_type_for_subclassed_matcher_when_expected_type_passed_in() + { + final Matcher matcher = new SubMatcher<>(new NotBuiltIn()); - assertMatches("not built in", matcher, new NotBuiltIn()); - assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); - } + assertMatches("not built in", matcher, new NotBuiltIn()); + assertDoesNotMatch("other not built in", (Matcher) matcher, new OtherNotBuiltIn()); + } - @Test public void - filters_type_for_subclassed_matcher_when_expected_type_passed_in() { - final Matcher matcher = new SubMatcher<>(new NotBuiltIn()); + @Test public void + but_cannot_detect_generic_type_in_subclassed_matcher_using_reflection() + { + final Matcher matcher = new SubMatcher<>(); - assertMatches("not built in", matcher, new NotBuiltIn()); - assertDoesNotMatch("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); + assertMatches("not built in", matcher, new NotBuiltIn()); + assertMatches("other not built in", (Matcher) matcher, new OtherNotBuiltIn()); } - @Test public void - but_cannot_detect_generic_type_in_subclassed_matcher_using_reflection() { - final Matcher matcher = new SubMatcher<>(); + private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher() + { + @Override + protected boolean matchesSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("mismatching"); + return false; + } - assertMatches("not built in", matcher, new NotBuiltIn()); - assertMatches("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); + @Override + public void describeTo(Description description) + { } + }; - private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher() { - @Override - protected boolean matchesSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("mismatching"); - return false; - } + public static class SubMatcher extends TypeSafeDiagnosingMatcher + { + public SubMatcher() + { + super(); + } - @Override - public void describeTo(Description description) { } - }; + public SubMatcher(T expectedObject) + { + super(expectedObject.getClass()); + } - public static class SubMatcher extends TypeSafeDiagnosingMatcher { - public SubMatcher() { - super(); - } - public SubMatcher(T expectedObject) { - super(expectedObject.getClass()); - } - @Override protected boolean matchesSafely(T item, Description mismatchDescription) { return true; } - @Override public void describeTo(Description description) { description.appendText("sub type"); } + @Override protected boolean matchesSafely(T item, Description mismatchDescription) + { + return true; } - public static class NotBuiltIn { - public final String value = "not built in"; - @Override public String toString() { return "NotBuiltIn"; } + @Override public void describeTo(Description description) + { + description.appendText("sub type"); } + } + + public static class NotBuiltIn + { + public final String value = "not built in"; - public static class OtherNotBuiltIn { // empty + @Override public String toString() + { + return "NotBuiltIn"; } + } + + public static class OtherNotBuiltIn + { // empty + } } diff --git a/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java index 5563fabc..c85c3734 100644 --- a/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java @@ -6,36 +6,43 @@ import static org.junit.Assert.assertFalse; @SuppressWarnings("WeakerAccess") -public final class TypeSafeMatcherTest { +public final class TypeSafeMatcherTest +{ private final Matcher matcher = new TypeSafeMatcherSubclass(); - public static class TypeSafeMatcherSubclass extends TypeSafeMatcher { + public static class TypeSafeMatcherSubclass extends TypeSafeMatcher + { @Override - public boolean matchesSafely(String item) { + public boolean matchesSafely(String item) + { return false; } @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("The mismatch"); + public void describeMismatchSafely(String item, Description mismatchDescription) + { + mismatchDescription.appendText("The mismatch"); } @Override - public void describeTo(Description description) { + public void describeTo(Description description) + { } } @Test public void - canDetermineMatcherTypeFromProtectedMatchesSafelyMethod() { + canDetermineMatcherTypeFromProtectedMatchesSafelyMethod() + { assertFalse(matcher.matches(null)); assertFalse(matcher.matches(10)); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void - describesMismatches() { - assertMismatchDescription("was null", matcher, null); - assertMismatchDescription("was a java.lang.Integer (<3>)", (Matcher)matcher, 3); - assertMismatchDescription("The mismatch", matcher, "a string"); + describesMismatches() + { + assertMismatchDescription("was null", matcher, null); + assertMismatchDescription("was a java.lang.Integer (<3>)", (Matcher) matcher, 3); + assertMismatchDescription("The mismatch", matcher, "a string"); } } diff --git a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java index 11813106..5fdf0897 100644 --- a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java +++ b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java @@ -13,36 +13,42 @@ * @author Tom Denley * @since 1.1.0 */ -public final class HasPropertyTest { - - private final HasPropertyWithValueTest.BeanWithoutInfo bean = new HasPropertyWithValueTest.BeanWithoutInfo("a bean", false); - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = hasProperty("irrelevant"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesWhenThePropertyExists() { - assertMatches(hasProperty("writeOnlyProperty"), bean); - } - - @Test public void - doesNotMatchIfPropertyDoesNotExist() { - assertDoesNotMatch(hasProperty("aNonExistentProp"), bean); - } - - @Test public void - describesItself() { - assertDescription("hasProperty(\"property\")", hasProperty("property")); - } - - @Test public void - describesAMismatch() { - assertMismatchDescription("no \"aNonExistentProp\" in <[Person: a bean]>", - hasProperty("aNonExistentProp"), bean); - } +public final class HasPropertyTest +{ + + private final HasPropertyWithValueTest.BeanWithoutInfo bean = new HasPropertyWithValueTest.BeanWithoutInfo("a bean", false); + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = hasProperty("irrelevant"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesWhenThePropertyExists() + { + assertMatches(hasProperty("writeOnlyProperty"), bean); + } + + @Test public void + doesNotMatchIfPropertyDoesNotExist() + { + assertDoesNotMatch(hasProperty("aNonExistentProp"), bean); + } + + @Test public void + describesItself() + { + assertDescription("hasProperty(\"property\")", hasProperty("property")); + } + + @Test public void + describesAMismatch() + { + assertMismatchDescription("no \"aNonExistentProp\" in <[Person: a bean]>", + hasProperty("aNonExistentProp"), bean); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java index d5f427e6..21714668 100644 --- a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java +++ b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java @@ -21,48 +21,56 @@ * @since 1.1.0 */ @SuppressWarnings("UnusedDeclaration") -public class HasPropertyWithValueTest extends AbstractMatcherTest { +public class HasPropertyWithValueTest extends AbstractMatcherTest +{ private final BeanWithoutInfo shouldMatch = new BeanWithoutInfo("is expected", true); private final BeanWithoutInfo shouldNotMatch = new BeanWithoutInfo("not expected", false); private final BeanWithInfo beanWithInfo = new BeanWithInfo("with info"); @Override - protected Matcher createMatcher() { + protected Matcher createMatcher() + { return hasProperty("irrelevant", anything()); } - public void testMatchesBeanWithoutInfoWithMatchedNamedProperty() { + public void testMatchesBeanWithoutInfoWithMatchedNamedProperty() + { final Matcher propertyMatcher = hasProperty("property", equalTo("is expected")); assertMatches("with property", propertyMatcher, shouldMatch); assertMismatchDescription("property 'property' was \"not expected\"", propertyMatcher, shouldNotMatch); } - public void testMatchesBeanWithoutInfoWithMatchedNamedBooleanProperty() { + public void testMatchesBeanWithoutInfoWithMatchedNamedBooleanProperty() + { final Matcher booleanPropertyMatcher = hasProperty("booleanProperty", is(true)); assertMatches("with property", booleanPropertyMatcher, shouldMatch); assertMismatchDescription("property 'booleanProperty' was ", booleanPropertyMatcher, shouldNotMatch); } - public void testMatchesBeanWithInfoWithMatchedNamedProperty() { + public void testMatchesBeanWithInfoWithMatchedNamedProperty() + { assertMatches("with bean info", hasProperty("property", equalTo("with info")), beanWithInfo); - assertMismatchDescription("property 'property' was \"with info\"", + assertMismatchDescription("property 'property' was \"with info\"", hasProperty("property", equalTo("without info")), beanWithInfo); } - public void testDoesNotMatchBeanWithoutInfoOrMatchedNamedProperty() { - assertMismatchDescription("No property \"nonExistentProperty\"", - hasProperty("nonExistentProperty", anything()), shouldNotMatch); - } + public void testDoesNotMatchBeanWithoutInfoOrMatchedNamedProperty() + { + assertMismatchDescription("No property \"nonExistentProperty\"", + hasProperty("nonExistentProperty", anything()), shouldNotMatch); + } - public void testDoesNotMatchWriteOnlyProperty() { + public void testDoesNotMatchWriteOnlyProperty() + { assertMismatchDescription("property \"writeOnlyProperty\" is not readable", - hasProperty("writeOnlyProperty", anything()), shouldNotMatch); + hasProperty("writeOnlyProperty", anything()), shouldNotMatch); } - public void testMatchesPath() { + public void testMatchesPath() + { assertMatches("1-step path", hasPropertyAtPath("property", equalTo("is expected")), shouldMatch); assertMatches("2-step path", hasPropertyAtPath("inner.property", equalTo("is expected")), new BeanWithInner(shouldMatch)); assertMatches("3-step path", hasPropertyAtPath("inner.inner.property", equalTo("is expected")), new BeanWithInner(new BeanWithInner(shouldMatch))); @@ -71,36 +79,44 @@ public void testMatchesPath() { assertMismatchDescription("inner.inner.property.was \"not expected\"", hasPropertyAtPath("inner.inner.property", equalTo("something")), new BeanWithInner(new BeanWithInner(shouldNotMatch))); } - public void testDescribeTo() { + public void testDescribeTo() + { assertDescription("hasProperty(\"property\", )", hasProperty("property", equalTo(true))); } - public void testMatchesPropertyAndValue() { + public void testMatchesPropertyAndValue() + { assertMatches("property with value", hasProperty("property", anything()), beanWithInfo); } - - public void testDoesNotWriteMismatchIfPropertyMatches() { + + public void testDoesNotWriteMismatchIfPropertyMatches() + { Description description = new StringDescription(); - hasProperty( "property", anything()).describeMismatch(beanWithInfo, description); + hasProperty("property", anything()).describeMismatch(beanWithInfo, description); assertEquals("Expected mismatch description", "", description.toString()); } - public void testDescribesMissingPropertyMismatch() { + public void testDescribesMissingPropertyMismatch() + { assertMismatchDescription("No property \"honk\"", hasProperty("honk", anything()), shouldNotMatch); } - public void testExceptionsInBeanMethodsShouldBeReportedCorrectly() { + public void testExceptionsInBeanMethodsShouldBeReportedCorrectly() + { assertMismatchDescription( - "Calling 'public java.lang.String org.hamcrest.beans.HasPropertyWithValueTest$BeanWithBug.getBroken()': \"bean failed\"", - hasProperty("broken", anything()), - new BeanWithBug()); + "Calling 'public java.lang.String org.hamcrest.beans.HasPropertyWithValueTest$BeanWithBug.getBroken()': \"bean failed\"", + hasProperty("broken", anything()), + new BeanWithBug()); } - public void testCanAccessAnAnonymousInnerClass() { - class X implements IX { + public void testCanAccessAnAnonymousInnerClass() + { + class X implements IX + { @Override - public int getTest() { + public int getTest() + { return 1; } } @@ -108,77 +124,114 @@ public int getTest() { assertThat(new X(), HasPropertyWithValue.hasProperty("test", IsEqual.equalTo(1))); } - interface IX { + interface IX + { int getTest(); } @SuppressWarnings("WeakerAccess") - public static class BeanWithoutInfo { + public static class BeanWithoutInfo + { private String property; private final boolean booleanProperty; - public BeanWithoutInfo(String property, boolean booleanProperty) { + public BeanWithoutInfo(String property, boolean booleanProperty) + { this.property = property; this.booleanProperty = booleanProperty; } - public String getProperty() { + public String getProperty() + { return property; } - public void setProperty(String property) { + public void setProperty(String property) + { this.property = property; } - public boolean isBooleanProperty() { return booleanProperty; } + public boolean isBooleanProperty() + { + return booleanProperty; + } - public void setWriteOnlyProperty(@SuppressWarnings("unused") float property) { + public void setWriteOnlyProperty(@SuppressWarnings("unused") float property) + { } @Override - public String toString() { + public String toString() + { return "[Person: " + property + "]"; } } @SuppressWarnings("WeakerAccess") - public static class BeanWithInner { + public static class BeanWithInner + { private final Object inner; - public BeanWithInner(Object inner) { this.inner = inner; } - public Object getInner() { return inner; } + public BeanWithInner(Object inner) + { + this.inner = inner; + } + + public Object getInner() + { + return inner; + } } @SuppressWarnings("WeakerAccess") - public static class BeanWithInfo { + public static class BeanWithInfo + { private final String propertyValue; - public BeanWithInfo(String propertyValue) { this.propertyValue = propertyValue; } - public String property() { return propertyValue; } + public BeanWithInfo(String propertyValue) + { + this.propertyValue = propertyValue; + } + + public String property() + { + return propertyValue; + } } - public static class BeanWithInfoBeanInfo extends SimpleBeanInfo { + public static class BeanWithInfoBeanInfo extends SimpleBeanInfo + { @Override - public PropertyDescriptor[] getPropertyDescriptors() { - try { - return new PropertyDescriptor[] { - new PropertyDescriptor("property", BeanWithInfo.class, "property", null) - }; - } catch (IntrospectionException e) { + public PropertyDescriptor[] getPropertyDescriptors() + { + try + { + return new PropertyDescriptor[] { + new PropertyDescriptor("property", BeanWithInfo.class, "property", null) + }; + } + catch (IntrospectionException e) + { throw new AssertionError("Introspection exception", e); } } } @SuppressWarnings("WeakerAccess") - public static class BeanWithBug { - public String getBroken() { + public static class BeanWithBug + { + public String getBroken() + { throw new BeanFailed(); } } @SuppressWarnings("WeakerAccess") - public static class BeanFailed extends RuntimeException { - public BeanFailed() { super("bean failed"); } + public static class BeanFailed extends RuntimeException + { + public BeanFailed() + { + super("bean failed"); + } } } diff --git a/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java b/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java index caecb684..aeb19081 100644 --- a/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java @@ -6,60 +6,71 @@ import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs; @SuppressWarnings("WeakerAccess") -public class SamePropertyValuesAsTest extends AbstractMatcherTest { +public class SamePropertyValuesAsTest extends AbstractMatcherTest +{ private static final Value aValue = new Value("expected"); private static final ExampleBean expectedBean = new ExampleBean("same", 1, aValue); private static final ExampleBean actualBean = new ExampleBean("same", 1, aValue); - - + + @Override - protected Matcher createMatcher() { + protected Matcher createMatcher() + { return samePropertyValuesAs(expectedBean); } - public void test_reports_match_when_all_properties_match() { + public void test_reports_match_when_all_properties_match() + { assertMatches("matched properties", samePropertyValuesAs(expectedBean), actualBean); } - - public void test_reports_mismatch_when_actual_type_is_not_assignable_to_expected_type() { - assertMismatchDescription("is incompatible type: ExampleBean", - samePropertyValuesAs((Object)aValue), actualBean); + + public void test_reports_mismatch_when_actual_type_is_not_assignable_to_expected_type() + { + assertMismatchDescription("is incompatible type: ExampleBean", + samePropertyValuesAs((Object) aValue), actualBean); } - public void test_reports_mismatch_on_first_property_difference() { + public void test_reports_mismatch_on_first_property_difference() + { assertMismatchDescription("stringProperty was \"different\"", - samePropertyValuesAs(expectedBean), new ExampleBean("different", 1, aValue)); + samePropertyValuesAs(expectedBean), new ExampleBean("different", 1, aValue)); assertMismatchDescription("intProperty was <2>", - samePropertyValuesAs(expectedBean), new ExampleBean("same", 2, aValue)); + samePropertyValuesAs(expectedBean), new ExampleBean("same", 2, aValue)); assertMismatchDescription("valueProperty was ", - samePropertyValuesAs(expectedBean), new ExampleBean("same", 1, new Value("other"))); + samePropertyValuesAs(expectedBean), new ExampleBean("same", 1, new Value("other"))); } - public void test_matches_beans_with_inheritance_but_no_extra_properties() { - assertMatches("sub type with same properties", - samePropertyValuesAs(expectedBean), new SubBeanWithNoExtraProperties("same", 1, aValue)); + public void test_matches_beans_with_inheritance_but_no_extra_properties() + { + assertMatches("sub type with same properties", + samePropertyValuesAs(expectedBean), new SubBeanWithNoExtraProperties("same", 1, aValue)); } - public void test_rejects_subtype_that_has_extra_properties() { + public void test_rejects_subtype_that_has_extra_properties() + { assertMismatchDescription("has extra properties called [extraProperty]", - samePropertyValuesAs(expectedBean), new SubBeanWithExtraProperty("same", 1, aValue)); + samePropertyValuesAs(expectedBean), new SubBeanWithExtraProperty("same", 1, aValue)); } - public void test_ignores_extra_subtype_properties() { + public void test_ignores_extra_subtype_properties() + { final SubBeanWithExtraProperty withExtraProperty = new SubBeanWithExtraProperty("same", 1, aValue); assertMatches("extra property", samePropertyValuesAs(expectedBean, "extraProperty"), withExtraProperty); } - public void test_ignores_different_properties() { + public void test_ignores_different_properties() + { final ExampleBean differentBean = new ExampleBean("different", 1, aValue); assertMatches("different property", samePropertyValuesAs(expectedBean, "stringProperty"), differentBean); } - public void test_accepts_missing_properties_to_ignore() { + public void test_accepts_missing_properties_to_ignore() + { assertMatches("ignored property", samePropertyValuesAs(expectedBean, "notAProperty"), actualBean); } - public void test_can_ignore_all_properties() { + public void test_can_ignore_all_properties() + { final ExampleBean differentBean = new ExampleBean("different", 2, new Value("not expected")); assertMatches( "different property", @@ -68,7 +79,8 @@ public void test_can_ignore_all_properties() { } - public void testDescribesItself() { + public void testDescribesItself() + { assertDescription( "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ]", samePropertyValuesAs(expectedBean)); @@ -78,54 +90,76 @@ public void testDescribesItself() { samePropertyValuesAs(expectedBean, "ignored1", "ignored2")); } - public static class Value { - public Value(Object value) { + public static class Value + { + public Value(Object value) + { this.value = value; } public final Object value; + @Override - public String toString() { + public String toString() + { return "Value " + value; } } - + @SuppressWarnings("unused") - public static class ExampleBean { + public static class ExampleBean + { private String stringProperty; private int intProperty; private Value valueProperty; - public ExampleBean(String stringProperty, int intProperty, Value valueProperty) { + public ExampleBean(String stringProperty, int intProperty, Value valueProperty) + { this.stringProperty = stringProperty; this.intProperty = intProperty; this.valueProperty = valueProperty; } - - public String getStringProperty() { + + public String getStringProperty() + { return stringProperty; } - public int getIntProperty() { + + public int getIntProperty() + { return intProperty; } - public Value getValueProperty() { + + public Value getValueProperty() + { return valueProperty; } - @Override public String toString() { return "an ExampleBean"; } + @Override public String toString() + { + return "an ExampleBean"; + } } - - public static class SubBeanWithNoExtraProperties extends ExampleBean { - public SubBeanWithNoExtraProperties(String stringProperty, int intProperty, Value valueProperty) { + + public static class SubBeanWithNoExtraProperties extends ExampleBean + { + public SubBeanWithNoExtraProperties(String stringProperty, int intProperty, Value valueProperty) + { super(stringProperty, intProperty, valueProperty); } } - - public static class SubBeanWithExtraProperty extends ExampleBean { - public SubBeanWithExtraProperty(String stringProperty, int intProperty, Value valueProperty) { + + public static class SubBeanWithExtraProperty extends ExampleBean + { + public SubBeanWithExtraProperty(String stringProperty, int intProperty, Value valueProperty) + { super(stringProperty, intProperty, valueProperty); } + @SuppressWarnings("unused") - public String getExtraProperty() { return "extra"; } + public String getExtraProperty() + { + return "extra"; + } } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java index 572bf63d..1a4c5a9f 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java @@ -6,38 +6,44 @@ import static org.hamcrest.collection.ArrayMatching.arrayContainingInAnyOrder; import static org.hamcrest.core.IsEqual.equalTo; -public class ArrayMatchingInAnyOrderTest extends AbstractMatcherTest { - - @SuppressWarnings("unchecked") - @Override - protected Matcher createMatcher() { - return ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2)); - } - - @SuppressWarnings("unchecked") - public void testHasAReadableDescription() { - assertDescription("[<1>, <2>] in any order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2))); - assertDescription("[<1>, <2>] in any order", ArrayMatching.arrayContainingInAnyOrder(1, 2)); - } - - public void testMatchesItemsInAnyOrder() { - assertMatches("in order", ArrayMatching.arrayContainingInAnyOrder(1, 2, 3), new Integer[] {1, 2, 3}); - assertMatches("out of order", ArrayMatching.arrayContainingInAnyOrder(1, 2, 3), new Integer[] {3, 2, 1}); - assertMatches("single", ArrayMatching.arrayContainingInAnyOrder(1), new Integer[] {1}); - } - - @SuppressWarnings("unchecked") - public void testAppliesMatchersInAnyOrder() { - assertMatches("in order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); - assertMatches("out of order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {3, 2, 1}); - assertMatches("single", ArrayMatching.arrayContainingInAnyOrder(equalTo(1)), new Integer[] {1}); - } - - public void testMismatchesItemsInAnyOrder() { - Matcher matcher = ArrayMatching.arrayContainingInAnyOrder(1, 2, 3); - assertMismatchDescription("was null", matcher, null); - assertMismatchDescription("no item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); - assertMismatchDescription("no item matches: <2>, <3> in [<1>]", matcher, new Integer[] {1}); - assertMismatchDescription("not matched: <4>", matcher, new Integer[] {4,3,2,1}); - } +public class ArrayMatchingInAnyOrderTest extends AbstractMatcherTest +{ + + @SuppressWarnings("unchecked") + @Override + protected Matcher createMatcher() + { + return ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2)); + } + + @SuppressWarnings("unchecked") + public void testHasAReadableDescription() + { + assertDescription("[<1>, <2>] in any order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2))); + assertDescription("[<1>, <2>] in any order", ArrayMatching.arrayContainingInAnyOrder(1, 2)); + } + + public void testMatchesItemsInAnyOrder() + { + assertMatches("in order", ArrayMatching.arrayContainingInAnyOrder(1, 2, 3), new Integer[] { 1, 2, 3 }); + assertMatches("out of order", ArrayMatching.arrayContainingInAnyOrder(1, 2, 3), new Integer[] { 3, 2, 1 }); + assertMatches("single", ArrayMatching.arrayContainingInAnyOrder(1), new Integer[] { 1 }); + } + + @SuppressWarnings("unchecked") + public void testAppliesMatchersInAnyOrder() + { + assertMatches("in order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] { 1, 2, 3 }); + assertMatches("out of order", ArrayMatching.arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] { 3, 2, 1 }); + assertMatches("single", ArrayMatching.arrayContainingInAnyOrder(equalTo(1)), new Integer[] { 1 }); + } + + public void testMismatchesItemsInAnyOrder() + { + Matcher matcher = ArrayMatching.arrayContainingInAnyOrder(1, 2, 3); + assertMismatchDescription("was null", matcher, null); + assertMismatchDescription("no item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); + assertMismatchDescription("no item matches: <2>, <3> in [<1>]", matcher, new Integer[] { 1 }); + assertMismatchDescription("not matched: <4>", matcher, new Integer[] { 4, 3, 2, 1 }); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java index 784817a0..30f4351d 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java @@ -6,40 +6,47 @@ import static org.hamcrest.collection.ArrayMatching.arrayContaining; import static org.hamcrest.core.IsEqual.equalTo; -public class ArrayMatchingInOrderTest extends AbstractMatcherTest { - - @SuppressWarnings("unchecked") - @Override - protected Matcher createMatcher() { - return arrayContaining(equalTo(1), equalTo(2)); - } - - @SuppressWarnings("unchecked") - public void testHasAReadableDescription() { - assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); - } - - public void testMatchesItemsInOrder() { - assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] {1, 2, 3}); - assertMatches("single", arrayContaining(1), new Integer[] {1}); - } - - @SuppressWarnings("unchecked") - public void testAppliesMatchersInOrder() { - assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); - assertMatches("single", arrayContaining(equalTo(1)), new Integer[] {1}); - } - - public void testMismatchesItemsInOrder() { - Matcher matcher = arrayContaining(1, 2, 3); - assertMismatchDescription("was null", matcher, null); - assertMismatchDescription("no item was <1>", matcher, new Integer[] {}); - assertMismatchDescription("no item was <2>", matcher, new Integer[] {1}); - assertMismatchDescription("item 0: was <4>", matcher, new Integer[] {4,3,2,1}); - assertMismatchDescription("item 2: was <4>", matcher, new Integer[] {1,2, 4}); - } - - public void testCanHandleNullValuesInAnArray() { - assertMatches("with nulls", arrayContaining(null, null), new Object[]{null, null}); - } +public class ArrayMatchingInOrderTest extends AbstractMatcherTest +{ + + @SuppressWarnings("unchecked") + @Override + protected Matcher createMatcher() + { + return arrayContaining(equalTo(1), equalTo(2)); + } + + @SuppressWarnings("unchecked") + public void testHasAReadableDescription() + { + assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); + } + + public void testMatchesItemsInOrder() + { + assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] { 1, 2, 3 }); + assertMatches("single", arrayContaining(1), new Integer[] { 1 }); + } + + @SuppressWarnings("unchecked") + public void testAppliesMatchersInOrder() + { + assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] { 1, 2, 3 }); + assertMatches("single", arrayContaining(equalTo(1)), new Integer[] { 1 }); + } + + public void testMismatchesItemsInOrder() + { + Matcher matcher = arrayContaining(1, 2, 3); + assertMismatchDescription("was null", matcher, null); + assertMismatchDescription("no item was <1>", matcher, new Integer[] {}); + assertMismatchDescription("no item was <2>", matcher, new Integer[] { 1 }); + assertMismatchDescription("item 0: was <4>", matcher, new Integer[] { 4, 3, 2, 1 }); + assertMismatchDescription("item 2: was <4>", matcher, new Integer[] { 1, 2, 4 }); + } + + public void testCanHandleNullValuesInAnArray() + { + assertMatches("with nulls", arrayContaining(null, null), new Object[] { null, null }); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java b/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java index c4d7e34a..d19af798 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java @@ -6,71 +6,77 @@ import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.collection.ArrayMatching.hasItemInArray; -public class HasItemInArrayTest extends AbstractMatcherTest { +public class HasItemInArrayTest extends AbstractMatcherTest +{ - @Override - protected Matcher createMatcher() { - return hasItemInArray("irrelevant"); - } + @Override + protected Matcher createMatcher() + { + return hasItemInArray("irrelevant"); + } - public void testMatchesAnArrayThatContainsAnElementMatchingTheGivenMatcher() { - assertMatches("should matches array that contains 'a'", - hasItemInArray("a"), new String[]{"a", "b", "c"}); - } + public void testMatchesAnArrayThatContainsAnElementMatchingTheGivenMatcher() + { + assertMatches("should matches array that contains 'a'", + hasItemInArray("a"), new String[] { "a", "b", "c" }); + } - public void testDoesNotMatchAnArrayThatDoesntContainAnElementMatchingTheGivenMatcher() { - assertDoesNotMatch("should not matches array that doesn't contain 'a'", - hasItemInArray("a"), new String[]{"b", "c"}); - assertDoesNotMatch("should not matches empty array", - hasItemInArray("a"), new String[0]); - assertMismatchDescription( - "mismatches were: [<3> was greater than <2>, <4> was greater than <2>, <5> was greater than <2>]", - hasItemInArray(lessThan(2)), new Integer[] {3, 4, 5}); - } + public void testDoesNotMatchAnArrayThatDoesntContainAnElementMatchingTheGivenMatcher() + { + assertDoesNotMatch("should not matches array that doesn't contain 'a'", + hasItemInArray("a"), new String[] { "b", "c" }); + assertDoesNotMatch("should not matches empty array", + hasItemInArray("a"), new String[0]); + assertMismatchDescription( + "mismatches were: [<3> was greater than <2>, <4> was greater than <2>, <5> was greater than <2>]", + hasItemInArray(lessThan(2)), new Integer[] { 3, 4, 5 }); + } - public void testDoesNotMatchNull() { - assertDoesNotMatch("should not matches null", - hasItemInArray("a"), null); - } + public void testDoesNotMatchNull() + { + assertDoesNotMatch("should not matches null", + hasItemInArray("a"), null); + } - public void testHasAReadableDescription() { - assertDescription("an array containing a value less than <2>", hasItemInArray(lessThan(2))); - } + public void testHasAReadableDescription() + { + assertDescription("an array containing a value less than <2>", hasItemInArray(lessThan(2))); + } - // Remaining code no longer compiles, thanks to generics. I think that's a good thing, but - // I still need to investigate how this behaves with code that doesn't use generics. - // I expect ClassCastExceptions will be thrown. - // -Joe. + // Remaining code no longer compiles, thanks to generics. I think that's a good thing, but + // I still need to investigate how this behaves with code that doesn't use generics. + // I expect ClassCastExceptions will be thrown. + // -Joe. -// public void testDoesNotMatchObjectThatIsNotAnArray() { -// assertDoesNotMatch("should not matches empty list", -// arrayContaining("a"), "not a collection"); -// } + // public void testDoesNotMatchObjectThatIsNotAnArray() { + // assertDoesNotMatch("should not matches empty list", + // arrayContaining("a"), "not a collection"); + // } -// public void testMatchesPrimitiveArrayElements() { -// assertMatches("boolean", arrayContaining(true), new boolean[]{true, false}); -// assertDoesNotMatch("boolean", arrayContaining(false), new boolean[]{false}); -// -// assertMatches("byte", arrayContaining((byte) 1), new byte[]{1, 2, 3}); -// assertDoesNotMatch("byte", arrayContaining((byte) 0), new byte[]{1, 2, 3}); -// -// assertMatches("char", arrayContaining('a'), new char[]{'a', 'b', 'c'}); -// assertDoesNotMatch("char", arrayContaining('z'), new char[]{'a', 'b', 'c'}); -// -// assertMatches("short", arrayContaining((short) 1), new short[]{1, 2, 3}); -// assertDoesNotMatch("short", arrayContaining((short) 0), new short[]{1, 2, 3}); -// -// assertMatches("int", arrayContaining(1), new int[]{1, 2, 3}); -// assertDoesNotMatch("int", arrayContaining(0), new int[]{1, 2, 3}); -// -// assertMatches("long", arrayContaining(1L), new long[]{1, 2, 3}); -// assertDoesNotMatch("long", arrayContaining(0L), new long[]{1, 2, 3}); -// -// assertMatches("float", arrayContaining(1f), new float[]{1f, 2f, 3f}); -// assertDoesNotMatch("float", arrayContaining(0f), new float[]{1f, 2f, 3f}); -// -// assertMatches("double", arrayContaining(1.0), new double[]{1.0, 2.0, 3.0}); -// assertDoesNotMatch("double", arrayContaining(0.0), new double[]{1.0, 2.0, 3.0}); -// } + // public void testMatchesPrimitiveArrayElements() { + // assertMatches("boolean", arrayContaining(true), new boolean[]{true, false}); + // assertDoesNotMatch("boolean", arrayContaining(false), new boolean[]{false}); + // + // assertMatches("byte", arrayContaining((byte) 1), new byte[]{1, 2, 3}); + // assertDoesNotMatch("byte", arrayContaining((byte) 0), new byte[]{1, 2, 3}); + // + // assertMatches("char", arrayContaining('a'), new char[]{'a', 'b', 'c'}); + // assertDoesNotMatch("char", arrayContaining('z'), new char[]{'a', 'b', 'c'}); + // + // assertMatches("short", arrayContaining((short) 1), new short[]{1, 2, 3}); + // assertDoesNotMatch("short", arrayContaining((short) 0), new short[]{1, 2, 3}); + // + // assertMatches("int", arrayContaining(1), new int[]{1, 2, 3}); + // assertDoesNotMatch("int", arrayContaining(0), new int[]{1, 2, 3}); + // + // assertMatches("long", arrayContaining(1L), new long[]{1, 2, 3}); + // assertDoesNotMatch("long", arrayContaining(0L), new long[]{1, 2, 3}); + // + // assertMatches("float", arrayContaining(1f), new float[]{1f, 2f, 3f}); + // assertDoesNotMatch("float", arrayContaining(0f), new float[]{1f, 2f, 3f}); + // + // assertMatches("double", arrayContaining(1.0), new double[]{1.0, 2.0, 3.0}); + // assertDoesNotMatch("double", arrayContaining(0.0), new double[]{1.0, 2.0, 3.0}); + // } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java index 01d9e3de..64362a8b 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java @@ -6,38 +6,44 @@ import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; -public class IsArrayContainingInAnyOrderTest extends AbstractMatcherTest { - - @SuppressWarnings("unchecked") - @Override - protected Matcher createMatcher() { - return arrayContainingInAnyOrder(equalTo(1), equalTo(2)); - } - - @SuppressWarnings("unchecked") - public void testHasAReadableDescription() { - assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(equalTo(1), equalTo(2))); - assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(1, 2)); - } - - public void testMatchesItemsInAnyOrder() { - assertMatches("in order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] {1, 2, 3}); - assertMatches("out of order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] {3, 2, 1}); - assertMatches("single", arrayContainingInAnyOrder(1), new Integer[] {1}); - } - - @SuppressWarnings("unchecked") - public void testAppliesMatchersInAnyOrder() { - assertMatches("in order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); - assertMatches("out of order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {3, 2, 1}); - assertMatches("single", arrayContainingInAnyOrder(equalTo(1)), new Integer[] {1}); - } - - public void testMismatchesItemsInAnyOrder() { - Matcher matcher = arrayContainingInAnyOrder(1, 2, 3); - assertMismatchDescription("was null", matcher, null); - assertMismatchDescription("no item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); - assertMismatchDescription("no item matches: <2>, <3> in [<1>]", matcher, new Integer[] {1}); - assertMismatchDescription("not matched: <4>", matcher, new Integer[] {4,3,2,1}); - } +public class IsArrayContainingInAnyOrderTest extends AbstractMatcherTest +{ + + @SuppressWarnings("unchecked") + @Override + protected Matcher createMatcher() + { + return arrayContainingInAnyOrder(equalTo(1), equalTo(2)); + } + + @SuppressWarnings("unchecked") + public void testHasAReadableDescription() + { + assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(equalTo(1), equalTo(2))); + assertDescription("[<1>, <2>] in any order", arrayContainingInAnyOrder(1, 2)); + } + + public void testMatchesItemsInAnyOrder() + { + assertMatches("in order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] { 1, 2, 3 }); + assertMatches("out of order", arrayContainingInAnyOrder(1, 2, 3), new Integer[] { 3, 2, 1 }); + assertMatches("single", arrayContainingInAnyOrder(1), new Integer[] { 1 }); + } + + @SuppressWarnings("unchecked") + public void testAppliesMatchersInAnyOrder() + { + assertMatches("in order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] { 1, 2, 3 }); + assertMatches("out of order", arrayContainingInAnyOrder(equalTo(1), equalTo(2), equalTo(3)), new Integer[] { 3, 2, 1 }); + assertMatches("single", arrayContainingInAnyOrder(equalTo(1)), new Integer[] { 1 }); + } + + public void testMismatchesItemsInAnyOrder() + { + Matcher matcher = arrayContainingInAnyOrder(1, 2, 3); + assertMismatchDescription("was null", matcher, null); + assertMismatchDescription("no item matches: <1>, <2>, <3> in []", matcher, new Integer[] {}); + assertMismatchDescription("no item matches: <2>, <3> in [<1>]", matcher, new Integer[] { 1 }); + assertMismatchDescription("not matched: <4>", matcher, new Integer[] { 4, 3, 2, 1 }); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java index b719dd14..61c63667 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java @@ -6,36 +6,42 @@ import org.hamcrest.AbstractMatcherTest; import org.hamcrest.Matcher; -public class IsArrayContainingInOrderTest extends AbstractMatcherTest { - - @SuppressWarnings("unchecked") - @Override - protected Matcher createMatcher() { - return arrayContaining(equalTo(1), equalTo(2)); - } - - @SuppressWarnings("unchecked") - public void testHasAReadableDescription() { - assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); - } - - public void testMatchesItemsInOrder() { - assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] {1, 2, 3}); - assertMatches("single", arrayContaining(1), new Integer[] {1}); - } - - @SuppressWarnings("unchecked") - public void testAppliesMatchersInOrder() { - assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] {1, 2, 3}); - assertMatches("single", arrayContaining(equalTo(1)), new Integer[] {1}); - } - - public void testMismatchesItemsInOrder() { - Matcher matcher = arrayContaining(1, 2, 3); - assertMismatchDescription("was null", matcher, null); - assertMismatchDescription("no item was <1>", matcher, new Integer[] {}); - assertMismatchDescription("no item was <2>", matcher, new Integer[] {1}); - assertMismatchDescription("item 0: was <4>", matcher, new Integer[] {4,3,2,1}); - assertMismatchDescription("item 2: was <4>", matcher, new Integer[] {1,2, 4}); - } +public class IsArrayContainingInOrderTest extends AbstractMatcherTest +{ + + @SuppressWarnings("unchecked") + @Override + protected Matcher createMatcher() + { + return arrayContaining(equalTo(1), equalTo(2)); + } + + @SuppressWarnings("unchecked") + public void testHasAReadableDescription() + { + assertDescription("[<1>, <2>]", arrayContaining(equalTo(1), equalTo(2))); + } + + public void testMatchesItemsInOrder() + { + assertMatches("in order", arrayContaining(1, 2, 3), new Integer[] { 1, 2, 3 }); + assertMatches("single", arrayContaining(1), new Integer[] { 1 }); + } + + @SuppressWarnings("unchecked") + public void testAppliesMatchersInOrder() + { + assertMatches("in order", arrayContaining(equalTo(1), equalTo(2), equalTo(3)), new Integer[] { 1, 2, 3 }); + assertMatches("single", arrayContaining(equalTo(1)), new Integer[] { 1 }); + } + + public void testMismatchesItemsInOrder() + { + Matcher matcher = arrayContaining(1, 2, 3); + assertMismatchDescription("was null", matcher, null); + assertMismatchDescription("no item was <1>", matcher, new Integer[] {}); + assertMismatchDescription("no item was <2>", matcher, new Integer[] { 1 }); + assertMismatchDescription("item 0: was <4>", matcher, new Integer[] { 4, 3, 2, 1 }); + assertMismatchDescription("item 2: was <4>", matcher, new Integer[] { 1, 2, 4 }); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java index 4135d9f5..a2788e6a 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java @@ -9,51 +9,70 @@ import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") -public class IsArrayTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return array(equalTo("irrelevant")); - } - - public void testMatchesAnArrayThatMatchesAllTheElementMatchers() { - assertMatches("should match array with matching elements", - array(equalTo("a"), equalTo("b"), equalTo("c")), new String[]{"a", "b", "c"}); - } - - public void testDoesNotMatchAnArrayWhenElementsDoNotMatch() { - assertDoesNotMatch("should not match array with different elements", - array(equalTo("a"), equalTo("b")), new String[]{"b", "c"}); - } - - public void testDoesNotMatchAnArrayOfDifferentSize() { - assertDoesNotMatch("should not match larger array", - array(equalTo("a"), equalTo("b")), new String[]{"a", "b", "c"}); - assertDoesNotMatch("should not match smaller array", - array(equalTo("a"), equalTo("b")), new String[]{"a"}); - } - - public void testDoesNotMatchNull() { - assertDoesNotMatch("should not match null", - array(equalTo("a")), null); - } - - public void testHasAReadableDescription() { - assertDescription("[\"a\", \"b\"]", array(equalTo("a"), equalTo("b"))); - } - - public void testHasAReadableMismatchDescriptionUsing() { - assertMismatchDescription("element <0> was \"c\"", array(equalTo("a"), equalTo("b")), new String[]{"c", "b"}); - } - - public void testHasAReadableMismatchDescriptionUsingCustomMatchers() { - final BaseMatcher m = new BaseMatcher() { - @Override public boolean matches(Object item) { return false; } - @Override public void describeTo(Description description) { description.appendText("c"); } - @Override public void describeMismatch(Object item, Description description) { - description.appendText("didn't match"); - } - }; - assertMismatchDescription("element <0> didn't match", array(m, equalTo("b")), new String[]{"c", "b"}); - } +public class IsArrayTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return array(equalTo("irrelevant")); + } + + public void testMatchesAnArrayThatMatchesAllTheElementMatchers() + { + assertMatches("should match array with matching elements", + array(equalTo("a"), equalTo("b"), equalTo("c")), new String[] { "a", "b", "c" }); + } + + public void testDoesNotMatchAnArrayWhenElementsDoNotMatch() + { + assertDoesNotMatch("should not match array with different elements", + array(equalTo("a"), equalTo("b")), new String[] { "b", "c" }); + } + + public void testDoesNotMatchAnArrayOfDifferentSize() + { + assertDoesNotMatch("should not match larger array", + array(equalTo("a"), equalTo("b")), new String[] { "a", "b", "c" }); + assertDoesNotMatch("should not match smaller array", + array(equalTo("a"), equalTo("b")), new String[] { "a" }); + } + + public void testDoesNotMatchNull() + { + assertDoesNotMatch("should not match null", + array(equalTo("a")), null); + } + + public void testHasAReadableDescription() + { + assertDescription("[\"a\", \"b\"]", array(equalTo("a"), equalTo("b"))); + } + + public void testHasAReadableMismatchDescriptionUsing() + { + assertMismatchDescription("element <0> was \"c\"", array(equalTo("a"), equalTo("b")), new String[] { "c", "b" }); + } + + public void testHasAReadableMismatchDescriptionUsingCustomMatchers() + { + final BaseMatcher m = new BaseMatcher() + { + @Override public boolean matches(Object item) + { + return false; + } + + @Override public void describeTo(Description description) + { + description.appendText("c"); + } + + @Override public void describeMismatch(Object item, Description description) + { + description.appendText("didn't match"); + } + }; + assertMismatchDescription("element <0> didn't match", array(m, equalTo("b")), new String[] { "c", "b" }); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java index 18f607ec..bf04a14b 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java @@ -7,30 +7,36 @@ import static org.hamcrest.collection.IsArrayWithSize.emptyArray; import static org.hamcrest.core.IsEqual.equalTo; -public class IsArrayWithSizeTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return arrayWithSize(equalTo(2)); - } - - public void testMatchesWhenSizeIsCorrect() { - assertMatches("correct size", arrayWithSize(equalTo(3)), new Object[] {1, 2, 3}); - assertDoesNotMatch("incorrect size", arrayWithSize(equalTo(2)), new Object[] {1, 2, 3}); - } - - public void testProvidesConvenientShortcutForArrayWithSizeEqualTo() { - assertMatches("correct size", arrayWithSize(3), new Object[] {1, 2, 3}); - assertDoesNotMatch("incorrect size", arrayWithSize(2), new Object[] {1, 2, 3}); - } - - public void testEmptyArray() { - assertMatches("correct size", emptyArray(), new Object[] {}); - assertDoesNotMatch("incorrect size", emptyArray(), new Object[] {1}); - } - - public void testHasAReadableDescription() { - assertDescription("an array with size <3>", arrayWithSize(equalTo(3))); - assertDescription("an empty array", emptyArray()); - } +public class IsArrayWithSizeTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return arrayWithSize(equalTo(2)); + } + + public void testMatchesWhenSizeIsCorrect() + { + assertMatches("correct size", arrayWithSize(equalTo(3)), new Object[] { 1, 2, 3 }); + assertDoesNotMatch("incorrect size", arrayWithSize(equalTo(2)), new Object[] { 1, 2, 3 }); + } + + public void testProvidesConvenientShortcutForArrayWithSizeEqualTo() + { + assertMatches("correct size", arrayWithSize(3), new Object[] { 1, 2, 3 }); + assertDoesNotMatch("incorrect size", arrayWithSize(2), new Object[] { 1, 2, 3 }); + } + + public void testEmptyArray() + { + assertMatches("correct size", emptyArray(), new Object[] {}); + assertDoesNotMatch("incorrect size", emptyArray(), new Object[] { 1 }); + } + + public void testHasAReadableDescription() + { + assertDescription("an array with size <3>", arrayWithSize(equalTo(3))); + assertDescription("an empty array", emptyArray()); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java index b04a0c5c..8f776215 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java @@ -12,66 +12,78 @@ import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.IsEqual.equalTo; -public class IsCollectionWithSizeTest extends AbstractMatcherTest { +public class IsCollectionWithSizeTest extends AbstractMatcherTest +{ - @Override - protected Matcher createMatcher() { - return hasSize(7); - } + @Override + protected Matcher createMatcher() + { + return hasSize(7); + } - public void testMatchesWhenSizeIsCorrect() { - assertMatches("correct size", hasSize(equalTo(2)), asList(null, null)); - assertMismatchDescription("collection size was <3>", hasSize(equalTo(2)), asList(null, null, null)); - } + public void testMatchesWhenSizeIsCorrect() + { + assertMatches("correct size", hasSize(equalTo(2)), asList(null, null)); + assertMismatchDescription("collection size was <3>", hasSize(equalTo(2)), asList(null, null, null)); + } - public void testMatchesCollectionWhenSizeIsCorrectUsingObjectElementType() { - Collection list = asList(null, null); - assertMatches("correct size", hasSize(equalTo(2)), list); - assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); - } + public void testMatchesCollectionWhenSizeIsCorrectUsingObjectElementType() + { + Collection list = asList(null, null); + assertMatches("correct size", hasSize(equalTo(2)), list); + assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); + } - public void testMatchesCollectionWhenSizeIsCorrectUsingStringElementType() { - Collection list = asList("a", "b"); - assertMatches("correct size", hasSize(equalTo(2)), list); - assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); - } + public void testMatchesCollectionWhenSizeIsCorrectUsingStringElementType() + { + Collection list = asList("a", "b"); + assertMatches("correct size", hasSize(equalTo(2)), list); + assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); + } - public void testMatchesCollectionWhenSizeIsCorrectUsingWildcardElementType() { - Collection list = asList("a", "b"); - assertMatches("correct size", hasSize(equalTo(2)), list); - assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); - } + public void testMatchesCollectionWhenSizeIsCorrectUsingWildcardElementType() + { + Collection list = asList("a", "b"); + assertMatches("correct size", hasSize(equalTo(2)), list); + assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); + } - public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() { - List list = asList(null, null); - assertMatches("correct size", hasSize(equalTo(2)), list); - assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); - } + public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() + { + List list = asList(null, null); + assertMatches("correct size", hasSize(equalTo(2)), list); + assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); + } - public void testMatchesListWhenSizeIsCorrectUsingStringElementType() { - List list = asList("a", "b"); - assertMatches("correct size", hasSize(equalTo(2)), list); - assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); - } + public void testMatchesListWhenSizeIsCorrectUsingStringElementType() + { + List list = asList("a", "b"); + assertMatches("correct size", hasSize(equalTo(2)), list); + assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); + } - public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() { - List list = asList("a", "b"); - assertMatches("correct size", hasSize(equalTo(2)), list); - assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); - } + public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() + { + List list = asList("a", "b"); + assertMatches("correct size", hasSize(equalTo(2)), list); + assertMismatchDescription("collection size was <2>", hasSize(equalTo(3)), list); + } - public void testProvidesConvenientShortcutForHasSizeEqualTo() { - assertMatches("correct size", hasSize(2), asList(null, null)); - assertMismatchDescription("collection size was <3>", hasSize(2), asList(null, null, null)); - } + public void testProvidesConvenientShortcutForHasSizeEqualTo() + { + assertMatches("correct size", hasSize(2), asList(null, null)); + assertMismatchDescription("collection size was <3>", hasSize(2), asList(null, null, null)); + } - public void testHasAReadableDescription() { - assertDescription("a collection with size <3>", hasSize(equalTo(3))); - } - - public void testCompilesWithATypedCollection() { - // To prove Issue 43 - ArrayList arrayList = new ArrayList(); - MatcherAssert.assertThat(arrayList, hasSize(0)); - } + public void testHasAReadableDescription() + { + assertDescription("a collection with size <3>", hasSize(equalTo(3))); + } + + public void testCompilesWithATypedCollection() + { + // To prove Issue 43 + ArrayList arrayList = new ArrayList(); + MatcherAssert.assertThat(arrayList, hasSize(0)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java index ea875e8a..49368afc 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java @@ -10,36 +10,46 @@ import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.core.Is.is; -public class IsEmptyCollectionTest extends AbstractMatcherTest { - - @Override - protected Matcher> createMatcher() { - return empty(); - } - - public void testMatchesAnEmptyCollection() { - assertMatches("empty collection", createMatcher(), emptyCollection()); - } - - public void testDoesNotMatchACollectionWithAnItem() { - assertMismatchDescription("<[one, three]>", is(createMatcher()), collectionOfValues()); - } - - public void testHasAReadableDescription() { - assertDescription("an empty collection", createMatcher()); - } - - public void testCompiles() { - needs(IsEmptyCollection.emptyCollectionOf(String.class)); - } - - private void needs(@SuppressWarnings("unused") Matcher> bar) { } - - private static Collection collectionOfValues() { - return new ArrayList(asList("one", "three")); - } - - private static Collection emptyCollection() { - return new ArrayList(); - } +public class IsEmptyCollectionTest extends AbstractMatcherTest +{ + + @Override + protected Matcher> createMatcher() + { + return empty(); + } + + public void testMatchesAnEmptyCollection() + { + assertMatches("empty collection", createMatcher(), emptyCollection()); + } + + public void testDoesNotMatchACollectionWithAnItem() + { + assertMismatchDescription("<[one, three]>", is(createMatcher()), collectionOfValues()); + } + + public void testHasAReadableDescription() + { + assertDescription("an empty collection", createMatcher()); + } + + public void testCompiles() + { + needs(IsEmptyCollection.emptyCollectionOf(String.class)); + } + + private void needs(@SuppressWarnings("unused") Matcher> bar) + { + } + + private static Collection collectionOfValues() + { + return new ArrayList(asList("one", "three")); + } + + private static Collection emptyCollection() + { + return new ArrayList(); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java index 600b5760..b01a3e8e 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java @@ -9,36 +9,46 @@ import static java.util.Arrays.asList; import static org.hamcrest.collection.IsEmptyIterable.emptyIterable; -public class IsEmptyIterableTest extends AbstractMatcherTest { - - @Override - protected Matcher> createMatcher() { - return emptyIterable(); - } - - public void testMatchesAnEmptyIterable() { - assertMatches("empty iterable", createMatcher(), emptyCollection()); - } - - public void testDoesNotMatchAnIterableWithItems() { - assertDoesNotMatch("iterable with an item", createMatcher(), collectionOfValues()); - } - - public void testHasAReadableDescription() { - assertDescription("an empty iterable", createMatcher()); - } - - public void testCompiles() { - needs(IsEmptyIterable.emptyIterableOf(String.class)); - } - - private void needs(@SuppressWarnings("unused") Matcher> bar) { } - - private static Collection collectionOfValues() { - return new ArrayList(asList("one", "three")); - } - - private static Collection emptyCollection() { - return new ArrayList(); - } +public class IsEmptyIterableTest extends AbstractMatcherTest +{ + + @Override + protected Matcher> createMatcher() + { + return emptyIterable(); + } + + public void testMatchesAnEmptyIterable() + { + assertMatches("empty iterable", createMatcher(), emptyCollection()); + } + + public void testDoesNotMatchAnIterableWithItems() + { + assertDoesNotMatch("iterable with an item", createMatcher(), collectionOfValues()); + } + + public void testHasAReadableDescription() + { + assertDescription("an empty iterable", createMatcher()); + } + + public void testCompiles() + { + needs(IsEmptyIterable.emptyIterableOf(String.class)); + } + + private void needs(@SuppressWarnings("unused") Matcher> bar) + { + } + + private static Collection collectionOfValues() + { + return new ArrayList(asList("one", "three")); + } + + private static Collection emptyCollection() + { + return new ArrayList(); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java index e9fcbdcb..967cd8a5 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java @@ -7,38 +7,43 @@ import java.util.Arrays; import java.util.Collection; -public class IsInTest extends AbstractMatcherTest { - String[] elements = {"a", "b", "c"}; - - @Override - protected Matcher createMatcher() { - return new IsIn(elements); - } - - public void testReturnsTrueIfArgumentIsInCollection() { - Collection collection = Arrays.asList(elements); - Matcher isIn = new IsIn(collection); - - assertMatches("a", isIn, "a"); - assertMatches("b", isIn, "b"); - assertMatches("c", isIn, "c"); - assertDoesNotMatch("d", isIn, "d"); - } - - public void testReturnsTrueIfArgumentIsInArray() { - Matcher isIn = new IsIn(elements); - - assertMatches("a", isIn, "a"); - assertMatches("b", isIn, "b"); - assertMatches("c", isIn, "c"); - assertDoesNotMatch("d", isIn, "d"); - } - - public void testHasReadableDescription() { - Matcher isIn = new IsIn(elements); - - assertEquals("description", - "one of {\"a\", \"b\", \"c\"}", - StringDescription.toString(isIn)); - } +public class IsInTest extends AbstractMatcherTest +{ + String[] elements = { "a", "b", "c" }; + + @Override + protected Matcher createMatcher() + { + return new IsIn(elements); + } + + public void testReturnsTrueIfArgumentIsInCollection() + { + Collection collection = Arrays.asList(elements); + Matcher isIn = new IsIn(collection); + + assertMatches("a", isIn, "a"); + assertMatches("b", isIn, "b"); + assertMatches("c", isIn, "c"); + assertDoesNotMatch("d", isIn, "d"); + } + + public void testReturnsTrueIfArgumentIsInArray() + { + Matcher isIn = new IsIn(elements); + + assertMatches("a", isIn, "a"); + assertMatches("b", isIn, "b"); + assertMatches("c", isIn, "c"); + assertDoesNotMatch("d", isIn, "d"); + } + + public void testHasReadableDescription() + { + Matcher isIn = new IsIn(elements); + + assertEquals("description", + "one of {\"a\", \"b\", \"c\"}", + StringDescription.toString(isIn)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.java index 091c3475..44354071 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.java @@ -11,44 +11,54 @@ import static org.hamcrest.collection.IsIterableContainingInOrderTest.make; import static org.hamcrest.collection.IsIterableContainingInOrderTest.value; -public class IsIterableContainingInAnyOrderTest extends AbstractMatcherTest { +public class IsIterableContainingInAnyOrderTest extends AbstractMatcherTest +{ @Override - protected Matcher createMatcher() { + protected Matcher createMatcher() + { return containsInAnyOrder(1, 2); - } + } - public void testMatchesSingleItemIterable() { - assertMatches("single item", containsInAnyOrder(1), asList(1)); + public void testMatchesSingleItemIterable() + { + assertMatches("single item", containsInAnyOrder(1), asList(1)); } - public void testDoesNotMatchEmpty() { + public void testDoesNotMatchEmpty() + { assertMismatchDescription("no item matches: <1>, <2> in []", containsInAnyOrder(1, 2), Collections.emptyList()); } - - public void testMatchesIterableOutOfOrder() { + + public void testMatchesIterableOutOfOrder() + { assertMatches("Out of order", containsInAnyOrder(1, 2), asList(2, 1)); } - - public void testMatchesIterableInOrder() { + + public void testMatchesIterableInOrder() + { assertMatches("In order", containsInAnyOrder(1, 2), asList(1, 2)); } - - public void testDoesNotMatchIfOneOfMultipleElementsMismatches() { + + public void testDoesNotMatchIfOneOfMultipleElementsMismatches() + { assertMismatchDescription("not matched: <4>", containsInAnyOrder(1, 2, 3), asList(1, 2, 4)); } @SuppressWarnings("unchecked") - public void testDoesNotMatchIfThereAreMoreElementsThanMatchers() { + public void testDoesNotMatchIfThereAreMoreElementsThanMatchers() + { final Matcher> helpTheCompilerOut = containsInAnyOrder(value(1), value(3)); assertMismatchDescription("not matched: ", helpTheCompilerOut, asList(make(1), make(2), make(3))); } - - public void testDoesNotMatchIfThereAreMoreMatchersThanElements() { + + public void testDoesNotMatchIfThereAreMoreMatchersThanElements() + { assertMismatchDescription("no item matches: <4> in [<1>, <2>, <3>]", containsInAnyOrder(1, 2, 3, 4), asList(1, 2, 3)); } - public void testHasAReadableDescription() { + public void testHasAReadableDescription() + { assertDescription("iterable with items [<1>, <2>] in any order", containsInAnyOrder(1, 2)); } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java index e71abbfd..142f5d6e 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java @@ -13,65 +13,95 @@ import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") -public class IsIterableContainingInOrderTest extends AbstractMatcherTest { - // temporary hack until the Java type system works - private final Matcher> contains123 = contains(value(1), value(2), value(3)); - - @Override - protected Matcher createMatcher() { - return contains(1, 2); - } - - public void testMatchingSingleItemIterable() throws Exception { - assertMatches("Single item iterable", contains(1), singletonList(1)); - } - - public void testMatchingMultipleItemIterable() throws Exception { - assertMatches("Multiple item iterable", contains(1, 2, 3), asList(1, 2, 3)); - } - - public void testDoesNotMatchWithMoreElementsThanExpected() throws Exception { - assertMismatchDescription("not matched: <4>", contains(1, 2, 3), asList(1, 2, 3, 4)); - } - - public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception { - assertMismatchDescription("no item was value with <3>", contains123, asList(make(1), make(2))); - } - - public void testDoesNotMatchIfSingleItemMismatches() throws Exception { - assertMismatchDescription("item 0: value was <3>", contains(value(4)), singletonList(make(3))); - } - - public void testDoesNotMatchIfOneOfMultipleItemsMismatch() throws Exception { - assertMismatchDescription("item 2: value was <4>", contains123, asList(make(1), make(2), make(4))); - } - - public void testDoesNotMatchEmptyIterable() throws Exception { - assertMismatchDescription("no item was value with <4>", contains(value(4)), new ArrayList()); - } - - public void testHasAReadableDescription() { - assertDescription("iterable containing [<1>, <2>]", contains(1, 2)); - } - - public void testCanHandleNullMatchers() { - assertMatches(contains(null, null), asList(null, null)); - } - - public static class WithValue { - private final int value; - public WithValue(int value) { this.value = value; } - public int getValue() { return value; } - @Override public String toString() { return "WithValue " + value; } +public class IsIterableContainingInOrderTest extends AbstractMatcherTest +{ + // temporary hack until the Java type system works + private final Matcher> contains123 = contains(value(1), value(2), value(3)); + + @Override + protected Matcher createMatcher() + { + return contains(1, 2); + } + + public void testMatchingSingleItemIterable() throws Exception + { + assertMatches("Single item iterable", contains(1), singletonList(1)); + } + + public void testMatchingMultipleItemIterable() throws Exception + { + assertMatches("Multiple item iterable", contains(1, 2, 3), asList(1, 2, 3)); + } + + public void testDoesNotMatchWithMoreElementsThanExpected() throws Exception + { + assertMismatchDescription("not matched: <4>", contains(1, 2, 3), asList(1, 2, 3, 4)); + } + + public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception + { + assertMismatchDescription("no item was value with <3>", contains123, asList(make(1), make(2))); + } + + public void testDoesNotMatchIfSingleItemMismatches() throws Exception + { + assertMismatchDescription("item 0: value was <3>", contains(value(4)), singletonList(make(3))); + } + + public void testDoesNotMatchIfOneOfMultipleItemsMismatch() throws Exception + { + assertMismatchDescription("item 2: value was <4>", contains123, asList(make(1), make(2), make(4))); + } + + public void testDoesNotMatchEmptyIterable() throws Exception + { + assertMismatchDescription("no item was value with <4>", contains(value(4)), new ArrayList()); + } + + public void testHasAReadableDescription() + { + assertDescription("iterable containing [<1>, <2>]", contains(1, 2)); + } + + public void testCanHandleNullMatchers() + { + assertMatches(contains(null, null), asList(null, null)); + } + + public static class WithValue + { + private final int value; + + public WithValue(int value) + { + this.value = value; } - public static WithValue make(int value) { - return new WithValue(value); + public int getValue() + { + return value; } - public static Matcher value(int value) { - return new FeatureMatcher(equalTo(value), "value with", "value") { - @Override protected Integer featureValueOf(WithValue actual) { return actual.getValue(); } - }; + @Override public String toString() + { + return "WithValue " + value; } + } + + public static WithValue make(int value) + { + return new WithValue(value); + } + + public static Matcher value(int value) + { + return new FeatureMatcher(equalTo(value), "value with", "value") + { + @Override protected Integer featureValueOf(WithValue actual) + { + return actual.getValue(); + } + }; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInRelativeOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInRelativeOrderTest.java index 8192c8bf..578a4bc1 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInRelativeOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInRelativeOrderTest.java @@ -12,82 +12,116 @@ import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("unchecked") -public class IsIterableContainingInRelativeOrderTest extends AbstractMatcherTest { - // temporary hack until the Java type system works - private final Matcher> contains123 = containsInRelativeOrder(value(1), value(2), value(3)); - - @Override - protected Matcher createMatcher() { - return containsInRelativeOrder(1, 2); - } - - public void testMatchingSingleItemIterable() throws Exception { - assertMatches("Single item iterable", containsInRelativeOrder(1), asList(1)); - } - - public void testMatchingMultipleItemIterable() throws Exception { - assertMatches("Multiple item iterable", containsInRelativeOrder(1, 2, 3), asList(1, 2, 3)); - } - - public void testMatchesWithMoreElementsThanExpectedAtBeginning() throws Exception { - assertMatches("More elements at beginning", containsInRelativeOrder(2, 3, 4), asList(1, 2, 3, 4)); - } - - public void testMatchesWithMoreElementsThanExpectedAtEnd() throws Exception { - assertMatches("More elements at end", containsInRelativeOrder(1, 2, 3), asList(1, 2, 3, 4)); - } - - public void testMatchesWithMoreElementsThanExpectedInBetween() throws Exception { - assertMatches("More elements in between", containsInRelativeOrder(1, 3), asList(1, 2, 3)); - } - - public void testMatchesSubSection() throws Exception { - assertMatches("Sub section of iterable", containsInRelativeOrder(2, 3), asList(1, 2, 3, 4)); - } - - public void testMatchesWithSingleGapAndNotFirstOrLast() throws Exception { - assertMatches("Sub section with single gaps without a first or last match", containsInRelativeOrder(2, 4), asList(1, 2, 3, 4, 5)); - } - - public void testMatchingSubSectionWithManyGaps() throws Exception { - assertMatches("Sub section with many gaps iterable", containsInRelativeOrder(2, 4, 6), asList(1, 2, 3, 4, 5, 6, 7)); - } - - public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception { - List valueList = asList(make(1), make(2)); - assertMismatchDescription("value with <3> was not found after ", contains123, valueList); - } - - public void testDoesNotMatchIfSingleItemNotFound() throws Exception { - assertMismatchDescription("value with <4> was not found", containsInRelativeOrder(value(4)), asList(make(3))); - } - - public void testDoesNotMatchIfOneOfMultipleItemsNotFound() throws Exception { - assertMismatchDescription("value with <3> was not found after ", contains123, asList(make(1), make(2), make(4))); - } - - public void testDoesNotMatchEmptyIterable() throws Exception { - assertMismatchDescription("value with <4> was not found", containsInRelativeOrder(value(4)), new ArrayList()); - } - - public void testHasAReadableDescription() { - assertDescription("iterable containing [<1>, <2>] in relative order", containsInRelativeOrder(1, 2)); - } - - public static class WithValue { - private final int value; - public WithValue(int value) { this.value = value; } - public int getValue() { return value; } - @Override public String toString() { return "WithValue " + value; } - } - - public static WithValue make(int value) { - return new WithValue(value); - } - - public static Matcher value(int value) { - return new FeatureMatcher(equalTo(value), "value with", "value") { - @Override protected Integer featureValueOf(WithValue actual) { return actual.getValue(); } - }; - } +public class IsIterableContainingInRelativeOrderTest extends AbstractMatcherTest +{ + // temporary hack until the Java type system works + private final Matcher> contains123 = containsInRelativeOrder(value(1), value(2), value(3)); + + @Override + protected Matcher createMatcher() + { + return containsInRelativeOrder(1, 2); + } + + public void testMatchingSingleItemIterable() throws Exception + { + assertMatches("Single item iterable", containsInRelativeOrder(1), asList(1)); + } + + public void testMatchingMultipleItemIterable() throws Exception + { + assertMatches("Multiple item iterable", containsInRelativeOrder(1, 2, 3), asList(1, 2, 3)); + } + + public void testMatchesWithMoreElementsThanExpectedAtBeginning() throws Exception + { + assertMatches("More elements at beginning", containsInRelativeOrder(2, 3, 4), asList(1, 2, 3, 4)); + } + + public void testMatchesWithMoreElementsThanExpectedAtEnd() throws Exception + { + assertMatches("More elements at end", containsInRelativeOrder(1, 2, 3), asList(1, 2, 3, 4)); + } + + public void testMatchesWithMoreElementsThanExpectedInBetween() throws Exception + { + assertMatches("More elements in between", containsInRelativeOrder(1, 3), asList(1, 2, 3)); + } + + public void testMatchesSubSection() throws Exception + { + assertMatches("Sub section of iterable", containsInRelativeOrder(2, 3), asList(1, 2, 3, 4)); + } + + public void testMatchesWithSingleGapAndNotFirstOrLast() throws Exception + { + assertMatches("Sub section with single gaps without a first or last match", containsInRelativeOrder(2, 4), asList(1, 2, 3, 4, 5)); + } + + public void testMatchingSubSectionWithManyGaps() throws Exception + { + assertMatches("Sub section with many gaps iterable", containsInRelativeOrder(2, 4, 6), asList(1, 2, 3, 4, 5, 6, 7)); + } + + public void testDoesNotMatchWithFewerElementsThanExpected() throws Exception + { + List valueList = asList(make(1), make(2)); + assertMismatchDescription("value with <3> was not found after ", contains123, valueList); + } + + public void testDoesNotMatchIfSingleItemNotFound() throws Exception + { + assertMismatchDescription("value with <4> was not found", containsInRelativeOrder(value(4)), asList(make(3))); + } + + public void testDoesNotMatchIfOneOfMultipleItemsNotFound() throws Exception + { + assertMismatchDescription("value with <3> was not found after ", contains123, asList(make(1), make(2), make(4))); + } + + public void testDoesNotMatchEmptyIterable() throws Exception + { + assertMismatchDescription("value with <4> was not found", containsInRelativeOrder(value(4)), new ArrayList()); + } + + public void testHasAReadableDescription() + { + assertDescription("iterable containing [<1>, <2>] in relative order", containsInRelativeOrder(1, 2)); + } + + public static class WithValue + { + private final int value; + + public WithValue(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + @Override public String toString() + { + return "WithValue " + value; + } + } + + public static WithValue make(int value) + { + return new WithValue(value); + } + + public static Matcher value(int value) + { + return new FeatureMatcher(equalTo(value), "value with", "value") + { + @Override protected Integer featureValueOf(WithValue actual) + { + return actual.getValue(); + } + }; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java index 8bf65d14..5db9a610 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java @@ -8,30 +8,37 @@ import static org.hamcrest.collection.IsIterableWithSize.iterableWithSize; -public class IsIterableWithSizeTest extends AbstractMatcherTest { +public class IsIterableWithSizeTest extends AbstractMatcherTest +{ @Override - protected Matcher createMatcher() { + protected Matcher createMatcher() + { return iterableWithSize(7); } - public void testMatchesEmptyIterable() throws Exception { + public void testMatchesEmptyIterable() throws Exception + { assertMatches("Empty iterable", iterableWithSize(0), Collections.emptyList()); } - public void testMatchingSingleItemIterable() throws Exception { + public void testMatchingSingleItemIterable() throws Exception + { assertMatches("Single item iterable", iterableWithSize(1), Arrays.asList(1)); } - public void testMatchingMultipleItemIterable() throws Exception { + public void testMatchingMultipleItemIterable() throws Exception + { assertMatches("Multiple item iterable", iterableWithSize(3), Arrays.asList(1, 2, 3)); } - public void testDoesNotMatchIncorrectSize() throws Exception { + public void testDoesNotMatchIncorrectSize() throws Exception + { assertDoesNotMatch("Incorrect size", iterableWithSize(3), Arrays.asList(1)); } - public void testHasAReadableDescription() { + public void testHasAReadableDescription() + { assertDescription("an iterable with size <4>", iterableWithSize(4)); } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java index 13f067c8..373232da 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java @@ -10,43 +10,48 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsMapContaining.hasKey; -public class IsMapContainingKeyTest extends AbstractMatcherTest { +public class IsMapContainingKeyTest extends AbstractMatcherTest +{ @Override - protected Matcher createMatcher() { + protected Matcher createMatcher() + { return hasKey("foo"); } - public void testMatchesSingletonMapContainingKey() { - Map map = new HashMap(); + public void testMatchesSingletonMapContainingKey() + { + Map map = new HashMap(); map.put("a", 1); - + assertMatches("Matches single key", hasKey("a"), map); } - - public void testMatchesMapContainingKey() { - Map map = new HashMap(); + + public void testMatchesMapContainingKey() + { + Map map = new HashMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); - + assertMatches("Matches a", hasKey("a"), map); assertMatches("Matches c", hasKey("c"), map); } - - -// No longer compiles -// public void testMatchesMapContainingKeyWithNoGenerics() { -// Map map = new HashMap(); -// map.put("a", 1); -// map.put("b", 2); -// map.put("c", 3); -// -// assertMatches("Matches a", hasKey("a"), map); -// assertMatches("Matches c", hasKey("c"), map); -// } - - public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception { + + + // No longer compiles + // public void testMatchesMapContainingKeyWithNoGenerics() { + // Map map = new HashMap(); + // map.put("a", 1); + // map.put("b", 2); + // map.put("c", 3); + // + // assertMatches("Matches a", hasKey("a"), map); + // assertMatches("Matches c", hasKey("c"), map); + // } + + public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception + { Map map = new HashMap(); map.put(1, "A"); map.put(2, "B"); @@ -54,31 +59,35 @@ public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception { assertThat(map, hasKey(1)); } - public void testMatchesMapContainingKeyWithNumberKeys() throws Exception { + public void testMatchesMapContainingKeyWithNumberKeys() throws Exception + { Map map = new HashMap(); map.put(1, "A"); map.put(2, "B"); - assertThat(map, hasKey((Number)1)); + assertThat(map, hasKey((Number) 1)); // TODO: work out the correct sprinkling of wildcards to get this to work! -// assertThat(map, hasKey(1)); + // assertThat(map, hasKey(1)); } - public void testHasReadableDescription() { + public void testHasReadableDescription() + { assertDescription("map containing [\"a\"->ANYTHING]", hasKey("a")); } - - public void testDoesNotMatchEmptyMap() { - assertMismatchDescription("map was []", hasKey("Foo"), new HashMap()); + + public void testDoesNotMatchEmptyMap() + { + assertMismatchDescription("map was []", hasKey("Foo"), new HashMap()); } - - public void testDoesNotMatchMapMissingKey() { - Map map = new TreeMap(); + + public void testDoesNotMatchMapMissingKey() + { + Map map = new TreeMap(); map.put("a", 1); map.put("b", 2); map.put("c", 3); - + assertMismatchDescription("map was [, , ]", hasKey("d"), map); } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java index 3eed3463..fd8f78f8 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java @@ -11,39 +11,45 @@ import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; -public class IsMapContainingTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return IsMapContaining.hasEntry("irrelevant", "irrelevant"); - } - - public void testMatchesMapContainingMatchingKeyAndValue() { - Map map = new TreeMap<>(); - map.put("a", 1); - map.put("b", 2); - - assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); - assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); - assertMismatchDescription("map was [, ]", hasEntry(equalTo("c"), equalTo(3)), map); - } - - @SuppressWarnings("unchecked") - public void testMatchesMapContainingMatchingKeyAndValueWithoutGenerics() { - Map map = new HashMap(); - map.put("a", 1); - map.put("b", 2); - - assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); - assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); - assertFalse("matcherC", hasEntry(equalTo("c"), equalTo(3)).matches(map)); // working around generics problem - } - - public void testDoesNotMatchNull() { - assertMismatchDescription("was null", hasEntry(anything(), anything()), null); - } - - public void testHasReadableDescription() { - assertDescription("map containing [\"a\"-><2>]", hasEntry(equalTo("a"), (equalTo(2)))); - } +public class IsMapContainingTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return IsMapContaining.hasEntry("irrelevant", "irrelevant"); + } + + public void testMatchesMapContainingMatchingKeyAndValue() + { + Map map = new TreeMap<>(); + map.put("a", 1); + map.put("b", 2); + + assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); + assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); + assertMismatchDescription("map was [, ]", hasEntry(equalTo("c"), equalTo(3)), map); + } + + @SuppressWarnings("unchecked") + public void testMatchesMapContainingMatchingKeyAndValueWithoutGenerics() + { + Map map = new HashMap(); + map.put("a", 1); + map.put("b", 2); + + assertMatches("matcherA", hasEntry(equalTo("a"), equalTo(1)), map); + assertMatches("matcherB", hasEntry(equalTo("b"), equalTo(2)), map); + assertFalse("matcherC", hasEntry(equalTo("c"), equalTo(3)).matches(map)); // working around generics problem + } + + public void testDoesNotMatchNull() + { + assertMismatchDescription("was null", hasEntry(anything(), anything()), null); + } + + public void testHasReadableDescription() + { + assertDescription("map containing [\"a\"-><2>]", hasEntry(equalTo("a"), (equalTo(2)))); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java index a2d7f908..86acfb73 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java @@ -10,37 +10,43 @@ import static org.hamcrest.collection.IsMapContaining.hasValue; -public class IsMapContainingValueTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return hasValue("foo"); - } - - public void testHasReadableDescription() { - assertDescription("map containing [ANYTHING->\"a\"]", hasValue("a")); - } - - public void testDoesNotMatchEmptyMap() { - Map map = new HashMap(); - assertMismatchDescription("map was []", hasValue(1), map); - } - - public void testMatchesSingletonMapContainingValue() { - Map map = new HashMap(); - map.put("a", 1); - - assertMatches("Singleton map", hasValue(1), map); - } - - public void testMatchesMapContainingValue() { - Map map = new TreeMap(); - map.put("a", 1); - map.put("b", 2); - map.put("c", 3); - - assertMatches("hasValue 1", hasValue(1), map); - assertMatches("hasValue 3", hasValue(3), map); - assertMismatchDescription("map was [, , ]", hasValue(4), map); - } +public class IsMapContainingValueTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return hasValue("foo"); + } + + public void testHasReadableDescription() + { + assertDescription("map containing [ANYTHING->\"a\"]", hasValue("a")); + } + + public void testDoesNotMatchEmptyMap() + { + Map map = new HashMap(); + assertMismatchDescription("map was []", hasValue(1), map); + } + + public void testMatchesSingletonMapContainingValue() + { + Map map = new HashMap(); + map.put("a", 1); + + assertMatches("Singleton map", hasValue(1), map); + } + + public void testMatchesMapContainingValue() + { + Map map = new TreeMap(); + map.put("a", 1); + map.put("b", 2); + map.put("c", 3); + + assertMatches("hasValue 1", hasValue(1), map); + assertMatches("hasValue 3", hasValue(3), map); + assertMismatchDescription("map was [, , ]", hasValue(4), map); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java index c050924c..f042640b 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java @@ -10,73 +10,87 @@ import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; import static org.hamcrest.core.IsEqual.equalTo; -public final class IsMapWithSizeTest extends AbstractMatcherTest { +public final class IsMapWithSizeTest extends AbstractMatcherTest +{ - @Override - protected Matcher createMatcher() { - return aMapWithSize(7); - } + @Override + protected Matcher createMatcher() + { + return aMapWithSize(7); + } - public void testMatchesWhenSizeIsCorrect() { - assertMatches("correct size", aMapWithSize(equalTo(2)), mapWithKeys("a", "b")); - assertMismatchDescription("map size was <3>", aMapWithSize(equalTo(2)), mapWithKeys("a", "b", "c")); - } + public void testMatchesWhenSizeIsCorrect() + { + assertMatches("correct size", aMapWithSize(equalTo(2)), mapWithKeys("a", "b")); + assertMismatchDescription("map size was <3>", aMapWithSize(equalTo(2)), mapWithKeys("a", "b", "c")); + } - public void testMatchesMapWhenSizeIsCorrectUsingObjectElementType() { - Map map = mapWithKeys(new Object(), new Object()); - assertMatches("correct size", aMapWithSize(equalTo(2)), map); - assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); - } + public void testMatchesMapWhenSizeIsCorrectUsingObjectElementType() + { + Map map = mapWithKeys(new Object(), new Object()); + assertMatches("correct size", aMapWithSize(equalTo(2)), map); + assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); + } - public void testMatchesMapWhenSizeIsCorrectUsingStringElementType() { - Map map = mapWithKeys("a", "b"); - assertMatches("correct size", aMapWithSize(equalTo(2)), map); - assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); - } + public void testMatchesMapWhenSizeIsCorrectUsingStringElementType() + { + Map map = mapWithKeys("a", "b"); + assertMatches("correct size", aMapWithSize(equalTo(2)), map); + assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); + } - public void testMatchesMapWhenSizeIsCorrectUsingWildcardElementType() { - Map map = mapWithKeys("a", "b"); - assertMatches("correct size", aMapWithSize(equalTo(2)), map); - assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); - } + public void testMatchesMapWhenSizeIsCorrectUsingWildcardElementType() + { + Map map = mapWithKeys("a", "b"); + assertMatches("correct size", aMapWithSize(equalTo(2)), map); + assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); + } - public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() { - Map map = mapWithKeys(new Object(), new Object()); - assertMatches("correct size", aMapWithSize(equalTo(2)), map); - assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); - } + public void testMatchesListWhenSizeIsCorrectUsingObjectElementType() + { + Map map = mapWithKeys(new Object(), new Object()); + assertMatches("correct size", aMapWithSize(equalTo(2)), map); + assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), map); + } - public void testMatchesListWhenSizeIsCorrectUsingStringElementType() { - Map list = mapWithKeys("a", "b"); - assertMatches("correct size", aMapWithSize(equalTo(2)), list); - assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), list); - } + public void testMatchesListWhenSizeIsCorrectUsingStringElementType() + { + Map list = mapWithKeys("a", "b"); + assertMatches("correct size", aMapWithSize(equalTo(2)), list); + assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), list); + } - public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() { - Map list = mapWithKeys("a", "b"); - assertMatches("correct size", aMapWithSize(equalTo(2)), list); - assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), list); - } + public void testMatchesListWhenSizeIsCorrectUsingWildcardElementType() + { + Map list = mapWithKeys("a", "b"); + assertMatches("correct size", aMapWithSize(equalTo(2)), list); + assertMismatchDescription("map size was <2>", aMapWithSize(equalTo(3)), list); + } - public void testProvidesConvenientShortcutForHasSizeEqualTo() { - assertMatches("correct size", aMapWithSize(2), mapWithKeys(new Object(), new Object())); - assertMismatchDescription("map size was <3>", aMapWithSize(2), mapWithKeys(new Object(), new Object(), new Object())); - } + public void testProvidesConvenientShortcutForHasSizeEqualTo() + { + assertMatches("correct size", aMapWithSize(2), mapWithKeys(new Object(), new Object())); + assertMismatchDescription("map size was <3>", aMapWithSize(2), mapWithKeys(new Object(), new Object(), new Object())); + } - public void testHasAReadableDescription() { - assertDescription("a map with size <3>", aMapWithSize(equalTo(3))); - } - - public void testCompilesWithATypedMap() { - Map arrayList = new HashMap(); - MatcherAssert.assertThat(arrayList, aMapWithSize(0)); - } - - private static Map mapWithKeys(K... keys) { - final Map result = new HashMap(); - for (K key : keys) { - result.put(key, null); - } - return result; + public void testHasAReadableDescription() + { + assertDescription("a map with size <3>", aMapWithSize(equalTo(3))); + } + + public void testCompilesWithATypedMap() + { + Map arrayList = new HashMap(); + MatcherAssert.assertThat(arrayList, aMapWithSize(0)); + } + + private static Map mapWithKeys(K... keys) + { + final Map result = new HashMap(); + for (K key : keys) + { + result.put(key, null); } + return result; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java b/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java index a5fdb4ac..9c605dbc 100644 --- a/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java @@ -10,119 +10,140 @@ import static org.hamcrest.comparator.ComparatorMatcherBuilder.comparedBy; import static org.hamcrest.core.IsNot.not; -public class ComparatorMatcherBuilderTest extends AbstractMatcherTest { - - private final ComparatorMatcherBuilder integerComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); - private final ComparatorMatcherBuilder doubleComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); - private final ComparatorMatcherBuilder stringComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); - private final ComparatorMatcherBuilder bigDecimalComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); - private final Comparator backwardsIntegerComparator = new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return -o1.compareTo(o2); - } - - @Override - public String toString() { - return "backwards integer comparator"; - } - }; - +public class ComparatorMatcherBuilderTest extends AbstractMatcherTest +{ + + private final ComparatorMatcherBuilder integerComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); + private final ComparatorMatcherBuilder doubleComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); + private final ComparatorMatcherBuilder stringComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); + private final ComparatorMatcherBuilder bigDecimalComparatorMatcherBuilder = ComparatorMatcherBuilder.usingNaturalOrdering(); + private final Comparator backwardsIntegerComparator = new Comparator() + { @Override - protected Matcher createMatcher() { - return integerComparatorMatcherBuilder.greaterThan(1); - } - - public void testDescription() { - assertDescription("a value greater than <1>", integerComparatorMatcherBuilder.greaterThan(1)); - assertDescription("a value equal to or greater than <1>", integerComparatorMatcherBuilder.greaterThanOrEqualTo(1)); - assertDescription("a value equal to <1>", integerComparatorMatcherBuilder.comparesEqualTo(1)); - assertDescription("a value less than or equal to <1>", integerComparatorMatcherBuilder.lessThanOrEqualTo(1)); - assertDescription("a value less than <1>", integerComparatorMatcherBuilder.lessThan(1)); - - assertDescription("a value greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(1)); - assertDescription("a value equal to or greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThanOrEqualTo(1)); - assertDescription("a value equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).comparesEqualTo(1)); - assertDescription("a value less than or equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThanOrEqualTo(1)); - assertDescription("a value less than <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(1)); - } - - public void testMismatchDescriptions() { - assertMismatchDescription("<0> was less than <1>", integerComparatorMatcherBuilder.greaterThan(1), 0); - assertMismatchDescription("<1> was equal to <1>", integerComparatorMatcherBuilder.greaterThan(1), 1); - assertMismatchDescription("<1> was greater than <0>", integerComparatorMatcherBuilder.lessThan(0), 1); - assertMismatchDescription("<2> was equal to <2>", integerComparatorMatcherBuilder.lessThan(2), 2); - - assertMismatchDescription("<1> was less than <0> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(0), 1); - assertMismatchDescription("<1> was equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(1), 1); - assertMismatchDescription("<0> was greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(1), 0); - assertMismatchDescription("<2> was equal to <2> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(2), 2); - } - - public void testComparesObjectsForGreaterThan() { - assertThat(2, integerComparatorMatcherBuilder.greaterThan(1)); - assertThat(0, not(integerComparatorMatcherBuilder.greaterThan(1))); - } - - public void testComparesObjectsForLessThan() { - assertThat(2, integerComparatorMatcherBuilder.lessThan(3)); - assertThat(0, integerComparatorMatcherBuilder.lessThan(1)); - } - - - public void testComparesObjectsForEquality() { - assertThat(3, integerComparatorMatcherBuilder.comparesEqualTo(3)); - assertThat("aa", stringComparatorMatcherBuilder.comparesEqualTo("aa")); + public int compare(Integer o1, Integer o2) + { + return -o1.compareTo(o2); } - public void testAllowsForInclusiveComparisons() { - assertThat("less", 1, integerComparatorMatcherBuilder.lessThanOrEqualTo(1)); - assertThat("greater", 1, integerComparatorMatcherBuilder.greaterThanOrEqualTo(1)); - } - - public void testSupportsDifferentTypesOfComparableObjects() { - assertThat(1.1, doubleComparatorMatcherBuilder.greaterThan(1.0)); - assertThat("cc", stringComparatorMatcherBuilder.greaterThan("bb")); - } - - public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { - assertThat(new BigDecimal("10.0"), bigDecimalComparatorMatcherBuilder.greaterThanOrEqualTo(new BigDecimal("10"))); - assertThat(new BigDecimal(10), bigDecimalComparatorMatcherBuilder.greaterThanOrEqualTo(new BigDecimal("10.0"))); - assertThat(new BigDecimal("2"), bigDecimalComparatorMatcherBuilder.comparesEqualTo(new BigDecimal("2.000"))); - } - - public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { - assertThat(new CustomInt(5), ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(new CustomInt(10))); - } - - public void testComparesByCustomComparator() { - assertThat(5, comparedBy(backwardsIntegerComparator).lessThan(4)); + @Override + public String toString() + { + return "backwards integer comparator"; } - - public void testJavadocExamples() { - assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().comparesEqualTo(1)); - assertThat(2, ComparatorMatcherBuilder.usingNaturalOrdering().greaterThan(1)); - assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().greaterThanOrEqualTo(1)); - assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(2)); - assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().lessThanOrEqualTo(1)); - assertThat(5, comparedBy(new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return -o1.compareTo(o2); - } - }).lessThan(4)); + }; + + @Override + protected Matcher createMatcher() + { + return integerComparatorMatcherBuilder.greaterThan(1); + } + + public void testDescription() + { + assertDescription("a value greater than <1>", integerComparatorMatcherBuilder.greaterThan(1)); + assertDescription("a value equal to or greater than <1>", integerComparatorMatcherBuilder.greaterThanOrEqualTo(1)); + assertDescription("a value equal to <1>", integerComparatorMatcherBuilder.comparesEqualTo(1)); + assertDescription("a value less than or equal to <1>", integerComparatorMatcherBuilder.lessThanOrEqualTo(1)); + assertDescription("a value less than <1>", integerComparatorMatcherBuilder.lessThan(1)); + + assertDescription("a value greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(1)); + assertDescription("a value equal to or greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThanOrEqualTo(1)); + assertDescription("a value equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).comparesEqualTo(1)); + assertDescription("a value less than or equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThanOrEqualTo(1)); + assertDescription("a value less than <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(1)); + } + + public void testMismatchDescriptions() + { + assertMismatchDescription("<0> was less than <1>", integerComparatorMatcherBuilder.greaterThan(1), 0); + assertMismatchDescription("<1> was equal to <1>", integerComparatorMatcherBuilder.greaterThan(1), 1); + assertMismatchDescription("<1> was greater than <0>", integerComparatorMatcherBuilder.lessThan(0), 1); + assertMismatchDescription("<2> was equal to <2>", integerComparatorMatcherBuilder.lessThan(2), 2); + + assertMismatchDescription("<1> was less than <0> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(0), 1); + assertMismatchDescription("<1> was equal to <1> when compared by ", comparedBy(backwardsIntegerComparator).greaterThan(1), 1); + assertMismatchDescription("<0> was greater than <1> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(1), 0); + assertMismatchDescription("<2> was equal to <2> when compared by ", comparedBy(backwardsIntegerComparator).lessThan(2), 2); + } + + public void testComparesObjectsForGreaterThan() + { + assertThat(2, integerComparatorMatcherBuilder.greaterThan(1)); + assertThat(0, not(integerComparatorMatcherBuilder.greaterThan(1))); + } + + public void testComparesObjectsForLessThan() + { + assertThat(2, integerComparatorMatcherBuilder.lessThan(3)); + assertThat(0, integerComparatorMatcherBuilder.lessThan(1)); + } + + + public void testComparesObjectsForEquality() + { + assertThat(3, integerComparatorMatcherBuilder.comparesEqualTo(3)); + assertThat("aa", stringComparatorMatcherBuilder.comparesEqualTo("aa")); + } + + public void testAllowsForInclusiveComparisons() + { + assertThat("less", 1, integerComparatorMatcherBuilder.lessThanOrEqualTo(1)); + assertThat("greater", 1, integerComparatorMatcherBuilder.greaterThanOrEqualTo(1)); + } + + public void testSupportsDifferentTypesOfComparableObjects() + { + assertThat(1.1, doubleComparatorMatcherBuilder.greaterThan(1.0)); + assertThat("cc", stringComparatorMatcherBuilder.greaterThan("bb")); + } + + public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() + { + assertThat(new BigDecimal("10.0"), bigDecimalComparatorMatcherBuilder.greaterThanOrEqualTo(new BigDecimal("10"))); + assertThat(new BigDecimal(10), bigDecimalComparatorMatcherBuilder.greaterThanOrEqualTo(new BigDecimal("10.0"))); + assertThat(new BigDecimal("2"), bigDecimalComparatorMatcherBuilder.comparesEqualTo(new BigDecimal("2.000"))); + } + + public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() + { + assertThat(new CustomInt(5), ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(new CustomInt(10))); + } + + public void testComparesByCustomComparator() + { + assertThat(5, comparedBy(backwardsIntegerComparator).lessThan(4)); + } + + public void testJavadocExamples() + { + assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().comparesEqualTo(1)); + assertThat(2, ComparatorMatcherBuilder.usingNaturalOrdering().greaterThan(1)); + assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().greaterThanOrEqualTo(1)); + assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().lessThan(2)); + assertThat(1, ComparatorMatcherBuilder.usingNaturalOrdering().lessThanOrEqualTo(1)); + assertThat(5, comparedBy(new Comparator() + { + @Override + public int compare(Integer o1, Integer o2) + { + return -o1.compareTo(o2); + } + }).lessThan(4)); + } + + private static final class CustomInt implements Comparable + { + private final int value; + + public CustomInt(int value) + { + this.value = value; } - private static final class CustomInt implements Comparable { - private final int value; - - public CustomInt(int value) { - this.value = value; - } - - @Override - public int compareTo(CustomInt other) { - return value - other.value; - } + @Override + public int compareTo(CustomInt other) + { + return value - other.value; } + } } diff --git a/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java b/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java index 2bc53d4c..0c256ac3 100644 --- a/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java @@ -10,78 +10,94 @@ import static org.hamcrest.core.IsNot.not; import static org.hamcrest.number.OrderingComparison.*; -public class ComparatorMatcherTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return ComparatorMatcherBuilder.comparedBy(new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return o1.compareTo(o2); - } - }).greaterThan(1); +public class ComparatorMatcherTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return ComparatorMatcherBuilder.comparedBy(new Comparator() + { + @Override + public int compare(Integer o1, Integer o2) + { + return o1.compareTo(o2); + } + }).greaterThan(1); + } + + public void testDescription() + { + assertDescription("a value greater than <1>", greaterThan(1)); + assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); + assertDescription("a value equal to <1>", comparesEqualTo(1)); + assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); + assertDescription("a value less than <1>", lessThan(1)); + } + + public void testMismatchDescriptions() + { + assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); + assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); + assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); + assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); + } + + public void testComparesObjectsForGreaterThan() + { + assertThat(2, greaterThan(1)); + assertThat(0, not(greaterThan(1))); + } + + public void testComparesObjectsForLessThan() + { + assertThat(2, lessThan(3)); + assertThat(0, lessThan(1)); + } + + + public void testComparesObjectsForEquality() + { + assertThat(3, comparesEqualTo(3)); + assertThat("aa", comparesEqualTo("aa")); + } + + public void testAllowsForInclusiveComparisons() + { + assertThat("less", 1, lessThanOrEqualTo(1)); + assertThat("greater", 1, greaterThanOrEqualTo(1)); + } + + public void testSupportsDifferentTypesOfComparableObjects() + { + assertThat(1.1, greaterThan(1.0)); + assertThat("cc", greaterThan("bb")); + } + + public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() + { + assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); + assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); + assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); + } + + public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() + { + assertThat(new CustomInt(5), lessThan(new CustomInt(10))); + } + + private static final class CustomInt implements Comparable + { + private final int value; + + public CustomInt(int value) + { + this.value = value; } - public void testDescription() { - assertDescription("a value greater than <1>", greaterThan(1)); - assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); - assertDescription("a value equal to <1>", comparesEqualTo(1)); - assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); - assertDescription("a value less than <1>", lessThan(1)); - } - - public void testMismatchDescriptions() { - assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); - assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); - assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); - assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); - } - - public void testComparesObjectsForGreaterThan() { - assertThat(2, greaterThan(1)); - assertThat(0, not(greaterThan(1))); - } - - public void testComparesObjectsForLessThan() { - assertThat(2, lessThan(3)); - assertThat(0, lessThan(1)); - } - - - public void testComparesObjectsForEquality() { - assertThat(3, comparesEqualTo(3)); - assertThat("aa", comparesEqualTo("aa")); - } - - public void testAllowsForInclusiveComparisons() { - assertThat("less", 1, lessThanOrEqualTo(1)); - assertThat("greater", 1, greaterThanOrEqualTo(1)); - } - - public void testSupportsDifferentTypesOfComparableObjects() { - assertThat(1.1, greaterThan(1.0)); - assertThat("cc", greaterThan("bb")); - } - - public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { - assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); - assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); - assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); - } - - public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { - assertThat(new CustomInt(5), lessThan(new CustomInt(10))); - } - - private static final class CustomInt implements Comparable { - private final int value; - - public CustomInt(int value) { - this.value = value; - } - - public int compareTo(CustomInt other) { - return value - other.value; - } + public int compareTo(CustomInt other) + { + return value - other.value; } + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java b/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java index 0387207c..62879ba1 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java @@ -13,58 +13,66 @@ import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; -public final class AllOfTest { +public final class AllOfTest +{ - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = allOf(equalTo("irrelevant"), startsWith("irr")); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - evaluatesToTheTheLogicalConjunctionOfTwoOtherMatchers() { - Matcher matcher = allOf(startsWith("goo"), endsWith("ood")); - - assertMatches("didn't pass both sub-matchers", matcher, "good"); - assertDoesNotMatch("didn't fail first sub-matcher", matcher, "mood"); - assertDoesNotMatch("didn't fail second sub-matcher", matcher, "goon"); - assertDoesNotMatch("didn't fail both sub-matchers", matcher, "fred"); - } + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = allOf(equalTo("irrelevant"), startsWith("irr")); - @Test public void - evaluatesToTheTheLogicalConjunctionOfManyOtherMatchers() { - Matcher matcher = allOf(startsWith("g"), startsWith("go"), endsWith("d"), startsWith("go"), startsWith("goo")); - - assertMatches("didn't pass all sub-matchers", matcher, "good"); - assertDoesNotMatch("didn't fail middle sub-matcher", matcher, "goon"); - } - - @Test public void - supportsMixedTypes() { - final Matcher matcher = allOf( - equalTo(new SampleBaseClass("bad")), - is(notNullValue()), - equalTo(new SampleBaseClass("good")), - equalTo(new SampleSubClass("ugly"))); - - assertDoesNotMatch("didn't fail last sub-matcher", matcher, new SampleSubClass("good")); - } - - @Test public void - hasAReadableDescription() { - assertDescription("(\"good\" and \"bad\" and \"ugly\")", - allOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); - } + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } - @Test public void - hasAMismatchDescriptionDescribingTheFirstFailingMatch() { - assertMismatchDescription("\"good\" was \"bad\"", allOf(equalTo("bad"), equalTo("good")), "bad"); - } + @Test public void + evaluatesToTheTheLogicalConjunctionOfTwoOtherMatchers() + { + Matcher matcher = allOf(startsWith("goo"), endsWith("ood")); - @Test public void - varargs(){ - assertThat("the text!", new AllOf<>(startsWith("the"), containsString("text"), endsWith("!"))); - } + assertMatches("didn't pass both sub-matchers", matcher, "good"); + assertDoesNotMatch("didn't fail first sub-matcher", matcher, "mood"); + assertDoesNotMatch("didn't fail second sub-matcher", matcher, "goon"); + assertDoesNotMatch("didn't fail both sub-matchers", matcher, "fred"); + } + + @Test public void + evaluatesToTheTheLogicalConjunctionOfManyOtherMatchers() + { + Matcher matcher = allOf(startsWith("g"), startsWith("go"), endsWith("d"), startsWith("go"), startsWith("goo")); + + assertMatches("didn't pass all sub-matchers", matcher, "good"); + assertDoesNotMatch("didn't fail middle sub-matcher", matcher, "goon"); + } + + @Test public void + supportsMixedTypes() + { + final Matcher matcher = allOf( + equalTo(new SampleBaseClass("bad")), + is(notNullValue()), + equalTo(new SampleBaseClass("good")), + equalTo(new SampleSubClass("ugly"))); + + assertDoesNotMatch("didn't fail last sub-matcher", matcher, new SampleSubClass("good")); + } + + @Test public void + hasAReadableDescription() + { + assertDescription("(\"good\" and \"bad\" and \"ugly\")", + allOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); + } + + @Test public void + hasAMismatchDescriptionDescribingTheFirstFailingMatch() + { + assertMismatchDescription("\"good\" was \"bad\"", allOf(equalTo("bad"), equalTo("good")), "bad"); + } + + @Test public void + varargs() + { + assertThat("the text!", new AllOf<>(startsWith("the"), containsString("text"), endsWith("!"))); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java b/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java index e2d9a9ee..70d070e6 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java @@ -10,53 +10,60 @@ import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; -public final class AnyOfTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = anyOf(equalTo("irrelevant"), startsWith("irr")); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - evaluatesToTheTheLogicalDisjunctionOfTwoOtherMatchers() { - Matcher matcher = anyOf(startsWith("goo"), endsWith("ood")); - - assertMatches("didn't pass both sub-matchers", matcher, "good"); - assertMatches("didn't pass second sub-matcher", matcher, "mood"); - assertMatches("didn't pass first sub-matcher", matcher, "goon"); - assertDoesNotMatch("didn't fail both sub-matchers", matcher, "flan"); - } - - @Test public void - evaluatesToTheTheLogicalDisjunctionOfManyOtherMatchers() { - Matcher matcher = anyOf(startsWith("g"), startsWith("go"), endsWith("d"), startsWith("go"), startsWith("goo")); - - assertMatches("didn't pass middle sub-matcher", matcher, "vlad"); - assertDoesNotMatch("didn't fail all sub-matchers", matcher, "flan"); - } - - @SuppressWarnings("unchecked") - @Test public void - supportsMixedTypes() { - final Matcher matcher = anyOf( - equalTo(new SampleBaseClass("bad")), - equalTo(new SampleBaseClass("good")), - equalTo(new SampleSubClass("ugly"))); - - assertMatches("didn't pass middle sub-matcher", matcher, new SampleSubClass("good")); - } - - @Test public void - hasAReadableDescription() { - assertDescription("(\"good\" or \"bad\" or \"ugly\")", - anyOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); - } - - @Test public void - varargs(){ - assertThat("the text!", new AnyOf<>(startsWith("the"), endsWith("."))); - } +public final class AnyOfTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = anyOf(equalTo("irrelevant"), startsWith("irr")); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + evaluatesToTheTheLogicalDisjunctionOfTwoOtherMatchers() + { + Matcher matcher = anyOf(startsWith("goo"), endsWith("ood")); + + assertMatches("didn't pass both sub-matchers", matcher, "good"); + assertMatches("didn't pass second sub-matcher", matcher, "mood"); + assertMatches("didn't pass first sub-matcher", matcher, "goon"); + assertDoesNotMatch("didn't fail both sub-matchers", matcher, "flan"); + } + + @Test public void + evaluatesToTheTheLogicalDisjunctionOfManyOtherMatchers() + { + Matcher matcher = anyOf(startsWith("g"), startsWith("go"), endsWith("d"), startsWith("go"), startsWith("goo")); + + assertMatches("didn't pass middle sub-matcher", matcher, "vlad"); + assertDoesNotMatch("didn't fail all sub-matchers", matcher, "flan"); + } + + @SuppressWarnings("unchecked") + @Test public void + supportsMixedTypes() + { + final Matcher matcher = anyOf( + equalTo(new SampleBaseClass("bad")), + equalTo(new SampleBaseClass("good")), + equalTo(new SampleSubClass("ugly"))); + + assertMatches("didn't pass middle sub-matcher", matcher, new SampleSubClass("good")); + } + + @Test public void + hasAReadableDescription() + { + assertDescription("(\"good\" or \"bad\" or \"ugly\")", + anyOf(equalTo("good"), equalTo("bad"), equalTo("ugly"))); + } + + @Test public void + varargs() + { + assertThat("the text!", new AnyOf<>(startsWith("the"), endsWith("."))); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java b/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java index 7a209b62..3c5b0b88 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java @@ -8,61 +8,70 @@ import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; -public final class CombinableTest { - private static final CombinableMatcher EITHER_3_OR_4 = CombinableMatcher.either(equalTo(3)).or(equalTo(4)); - private static final CombinableMatcher NOT_3_AND_NOT_4 = CombinableMatcher.both(not(equalTo(3))).and(not(equalTo(4))); +public final class CombinableTest +{ + private static final CombinableMatcher EITHER_3_OR_4 = CombinableMatcher.either(equalTo(3)).or(equalTo(4)); + private static final CombinableMatcher NOT_3_AND_NOT_4 = CombinableMatcher.both(not(equalTo(3))).and(not(equalTo(4))); - @Test public void - copesWithNullsAndUnknownTypes() { - assertNullSafe(EITHER_3_OR_4); - assertNullSafe(NOT_3_AND_NOT_4); - assertUnknownTypeSafe(EITHER_3_OR_4); - assertUnknownTypeSafe(NOT_3_AND_NOT_4); - } + @Test public void + copesWithNullsAndUnknownTypes() + { + assertNullSafe(EITHER_3_OR_4); + assertNullSafe(NOT_3_AND_NOT_4); + assertUnknownTypeSafe(EITHER_3_OR_4); + assertUnknownTypeSafe(NOT_3_AND_NOT_4); + } - @Test public void - bothAcceptsAndRejects() { - assertMatches("both didn't pass", NOT_3_AND_NOT_4, 2); - assertDoesNotMatch("both didn't fail", NOT_3_AND_NOT_4, 3); - } + @Test public void + bothAcceptsAndRejects() + { + assertMatches("both didn't pass", NOT_3_AND_NOT_4, 2); + assertDoesNotMatch("both didn't fail", NOT_3_AND_NOT_4, 3); + } - @Test public void - acceptsAndRejectsThreeAnds() { - CombinableMatcher tripleAnd = NOT_3_AND_NOT_4.and(equalTo(2)); - - assertMatches("tripleAnd didn't pass", tripleAnd, 2); - assertDoesNotMatch("tripleAnd didn't fail", tripleAnd, 3); - } + @Test public void + acceptsAndRejectsThreeAnds() + { + CombinableMatcher tripleAnd = NOT_3_AND_NOT_4.and(equalTo(2)); - @Test public void - bothDescribesItself() { - assertDescription("(not <3> and not <4>)", NOT_3_AND_NOT_4); - assertMismatchDescription("not <3> was <3>", NOT_3_AND_NOT_4, 3); - } + assertMatches("tripleAnd didn't pass", tripleAnd, 2); + assertDoesNotMatch("tripleAnd didn't fail", tripleAnd, 3); + } - @Test public void - eitherAcceptsAndRejects() { - assertMatches("either didn't pass", EITHER_3_OR_4, 3); - assertDoesNotMatch("either didn't fail", EITHER_3_OR_4, 6); - } + @Test public void + bothDescribesItself() + { + assertDescription("(not <3> and not <4>)", NOT_3_AND_NOT_4); + assertMismatchDescription("not <3> was <3>", NOT_3_AND_NOT_4, 3); + } - @Test public void - acceptsAndRejectsThreeOrs() { - final CombinableMatcher tripleOr = EITHER_3_OR_4.or(equalTo(11)); - - assertMatches("tripleOr didn't pass", tripleOr, 11); - assertDoesNotMatch("tripleOr didn't fail", tripleOr, 9); - } + @Test public void + eitherAcceptsAndRejects() + { + assertMatches("either didn't pass", EITHER_3_OR_4, 3); + assertDoesNotMatch("either didn't fail", EITHER_3_OR_4, 6); + } - @Test public void - eitherDescribesItself() { - assertDescription("(<3> or <4>)", EITHER_3_OR_4); - assertMismatchDescription("was <6>", EITHER_3_OR_4, 6); - } + @Test public void + acceptsAndRejectsThreeOrs() + { + final CombinableMatcher tripleOr = EITHER_3_OR_4.or(equalTo(11)); - @Test public void - picksUpTypeFromLeftHandSideOfExpression() { - @SuppressWarnings("unused") - Matcher matcher = CombinableMatcher.both(equalTo("yellow")).and(notNullValue(String.class)); - } + assertMatches("tripleOr didn't pass", tripleOr, 11); + assertDoesNotMatch("tripleOr didn't fail", tripleOr, 9); + } + + @Test public void + eitherDescribesItself() + { + assertDescription("(<3> or <4>)", EITHER_3_OR_4); + assertMismatchDescription("was <6>", EITHER_3_OR_4, 6); + } + + @Test public void + picksUpTypeFromLeftHandSideOfExpression() + { + @SuppressWarnings("unused") + Matcher matcher = CombinableMatcher.both(equalTo("yellow")).and(notNullValue(String.class)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java b/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java index 5c76af90..33f42712 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java @@ -8,42 +8,48 @@ import static org.hamcrest.core.IsAnything.anything; import static org.hamcrest.core.IsEqual.equalTo; -public final class DescribedAsTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = describedAs("irrelevant", anything()); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - overridesDescriptionOfOtherMatcherWithThatPassedToConstructor() { - Matcher matcher = describedAs("my description", anything()); - - assertDescription("my description", matcher); - } - - @Test public void - appendsValuesToDescription() { - Matcher matcher = describedAs("value 1 = %0, value 2 = %1", anything(), 33, 97); - - assertDescription("value 1 = <33>, value 2 = <97>", matcher); - } - - @Test public void - celegatesMatchingToAnotherMatcher() { - Matcher matcher = describedAs("irrelevant", equalTo("hi")); - - assertMatches(matcher, "hi"); - assertDoesNotMatch("matched", matcher, "oi"); - } - - @Test public void - delegatesMismatchDescriptionToAnotherMatcher() { - Matcher matcher = describedAs("irrelevant", equalTo(2)); - - assertMismatchDescription("was <1>", matcher, 1); - } +public final class DescribedAsTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = describedAs("irrelevant", anything()); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + overridesDescriptionOfOtherMatcherWithThatPassedToConstructor() + { + Matcher matcher = describedAs("my description", anything()); + + assertDescription("my description", matcher); + } + + @Test public void + appendsValuesToDescription() + { + Matcher matcher = describedAs("value 1 = %0, value 2 = %1", anything(), 33, 97); + + assertDescription("value 1 = <33>, value 2 = <97>", matcher); + } + + @Test public void + celegatesMatchingToAnotherMatcher() + { + Matcher matcher = describedAs("irrelevant", equalTo("hi")); + + assertMatches(matcher, "hi"); + assertDoesNotMatch("matched", matcher, "oi"); + } + + @Test public void + delegatesMismatchDescriptionToAnotherMatcher() + { + Matcher matcher = describedAs("irrelevant", equalTo(2)); + + assertMismatchDescription("was <1>", matcher, 1); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java b/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java index ff9f1772..bd15adaa 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java @@ -10,35 +10,41 @@ import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.core.StringContains.containsString; -public final class EveryTest { - - private final Matcher> matcher = Every.everyItem(containsString("a")); - - @Test public void - copesWithNullsAndUnknownTypes() { - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesOnlyWhenEveryItemMatches() { - assertMatches(matcher, asList("AaA", "BaB", "CaC")); - assertDoesNotMatch(matcher, asList("AaA", "BXB", "CaC")); - } - - @Test public void - matchesEmptyLists() { - assertMatches("didn't match empty list", matcher, new ArrayList()); - } - - @Test public void - describesItself() { - assertDescription("every item is a string containing \"a\"", matcher); - } - - @Test public void - describesAMismatch() { - assertMismatchDescription("an item was \"BXB\"", matcher, singletonList("BXB")); - } +public final class EveryTest +{ + + private final Matcher> matcher = Every.everyItem(containsString("a")); + + @Test public void + copesWithNullsAndUnknownTypes() + { + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesOnlyWhenEveryItemMatches() + { + assertMatches(matcher, asList("AaA", "BaB", "CaC")); + assertDoesNotMatch(matcher, asList("AaA", "BXB", "CaC")); + } + + @Test public void + matchesEmptyLists() + { + assertMatches("didn't match empty list", matcher, new ArrayList()); + } + + @Test public void + describesItself() + { + assertDescription("every item is a string containing \"a\"", matcher); + } + + @Test public void + describesAMismatch() + { + assertMismatchDescription("an item was \"BXB\"", matcher, singletonList("BXB")); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java index 80a8444c..049bb645 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java @@ -9,36 +9,42 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsAnything.anything; -public final class IsAnythingTest { - - private final Matcher matcher = anything(); - - private static class CustomThing { - } - - @Test - public void - alwaysEvaluatesToTrue() { - assertMatches("didn't match null", matcher, null); - assertMatches("didn't match Object", matcher, new Object()); - assertMatches("didn't match custom object", matcher, new CustomThing()); - assertMatches("didn't match String", matcher, "hi"); - } - - @Test - public void compilesWithoutTypeWarnings() { - assertThat(new CustomThing(), is(anything())); - } - - @Test public void - hasUsefulDefaultDescription() { - assertDescription("ANYTHING", matcher); - } - - @Test public void - canOverrideDescription() { - String description = "description"; - assertDescription(description, anything(description)); - } +public final class IsAnythingTest +{ + + private final Matcher matcher = anything(); + + private static class CustomThing + { + } + + @Test + public void + alwaysEvaluatesToTrue() + { + assertMatches("didn't match null", matcher, null); + assertMatches("didn't match Object", matcher, new Object()); + assertMatches("didn't match custom object", matcher, new CustomThing()); + assertMatches("didn't match String", matcher, "hi"); + } + + @Test + public void compilesWithoutTypeWarnings() + { + assertThat(new CustomThing(), is(anything())); + } + + @Test public void + hasUsefulDefaultDescription() + { + assertDescription("ANYTHING", matcher); + } + + @Test public void + canOverrideDescription() + { + String description = "description"; + assertDescription(description, anything(description)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java index db76bb1d..05e6146d 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java @@ -15,89 +15,102 @@ import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; -public class IsCollectionContainingTest extends AbstractMatcherTest { - @Override - protected Matcher createMatcher() { - return hasItem(equalTo("irrelevant")); - } - - public void testMatchesACollectionThatContainsAnElementMatchingTheGivenMatcher() { - Matcher> itemMatcher = hasItem(equalTo("a")); - - assertMatches("should match list that contains 'a'", - itemMatcher, asList("a", "b", "c")); - } - - public void testDoesNotMatchCollectionThatDoesntContainAnElementMatchingTheGivenMatcher() { - final Matcher> matcher1 = hasItem(mismatchable("a")); - assertMismatchDescription("mismatches were: [mismatched: b, mismatched: c]", matcher1, asList("b", "c")); - - - final Matcher> matcher2 = hasItem(equalTo("a")); - assertMismatchDescription("was empty", matcher2, new ArrayList()); - } - - public void testDoesNotMatchNull() { - assertDoesNotMatch("should not matches null", hasItem(equalTo("a")), null); - } - - public void testHasAReadableDescription() { - assertDescription("a collection containing \"a\"", hasItem(equalTo("a"))); - } - - public void testCanMatchItemWhenCollectionHoldsSuperclass() // Issue 24 +public class IsCollectionContainingTest extends AbstractMatcherTest +{ + @Override + protected Matcher createMatcher() + { + return hasItem(equalTo("irrelevant")); + } + + public void testMatchesACollectionThatContainsAnElementMatchingTheGivenMatcher() + { + Matcher> itemMatcher = hasItem(equalTo("a")); + + assertMatches("should match list that contains 'a'", + itemMatcher, asList("a", "b", "c")); + } + + public void testDoesNotMatchCollectionThatDoesntContainAnElementMatchingTheGivenMatcher() + { + final Matcher> matcher1 = hasItem(mismatchable("a")); + assertMismatchDescription("mismatches were: [mismatched: b, mismatched: c]", matcher1, asList("b", "c")); + + + final Matcher> matcher2 = hasItem(equalTo("a")); + assertMismatchDescription("was empty", matcher2, new ArrayList()); + } + + public void testDoesNotMatchNull() + { + assertDoesNotMatch("should not matches null", hasItem(equalTo("a")), null); + } + + public void testHasAReadableDescription() + { + assertDescription("a collection containing \"a\"", hasItem(equalTo("a"))); + } + + public void testCanMatchItemWhenCollectionHoldsSuperclass() // Issue 24 + { + final Set s = new HashSet(); + s.add(Integer.valueOf(2)); + assertThat(s, new IsCollectionContaining(new IsEqual(Integer.valueOf(2)))); + assertThat(s, IsCollectionContaining.hasItem(Integer.valueOf(2))); + } + + @SuppressWarnings("unchecked") + public void testMatchesAllItemsInCollection() + { + final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertMatches("should match list containing all items", + matcher1, + asList("a", "b", "c")); + + final Matcher> matcher2 = hasItems("a", "b", "c"); + assertMatches("should match list containing all items (without matchers)", + matcher2, + asList("a", "b", "c")); + + final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertMatches("should match list containing all items in any order", + matcher3, + asList("c", "b", "a")); + + final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertMatches("should match list containing all items plus others", + matcher4, + asList("e", "c", "b", "a", "d")); + + final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertDoesNotMatch("should not match list unless it contains all items", + matcher5, + asList("e", "c", "b", "d")); // 'a' missing + } + + + private static Matcher mismatchable(final String string) + { + return new TypeSafeDiagnosingMatcher() { - final Set s = new HashSet(); - s.add(Integer.valueOf(2)); - assertThat(s, new IsCollectionContaining(new IsEqual(Integer.valueOf(2)))); - assertThat(s, IsCollectionContaining.hasItem(Integer.valueOf(2))); - } - - @SuppressWarnings("unchecked") - public void testMatchesAllItemsInCollection() { - final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertMatches("should match list containing all items", - matcher1, - asList("a", "b", "c")); - - final Matcher> matcher2 = hasItems("a", "b", "c"); - assertMatches("should match list containing all items (without matchers)", - matcher2, - asList("a", "b", "c")); - - final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertMatches("should match list containing all items in any order", - matcher3, - asList("c", "b", "a")); - - final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertMatches("should match list containing all items plus others", - matcher4, - asList("e", "c", "b", "a", "d")); - - final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertDoesNotMatch("should not match list unless it contains all items", - matcher5, - asList("e", "c", "b", "d")); // 'a' missing - } - - - private static Matcher mismatchable(final String string) { - return new TypeSafeDiagnosingMatcher() { - @Override - protected boolean matchesSafely(String item, Description mismatchDescription) { - if (string.equals(item)) - return true; - - mismatchDescription.appendText("mismatched: " + item); - return false; + @Override + protected boolean matchesSafely(String item, Description mismatchDescription) + { + if (string.equals(item)) + { + return true; } - @Override - public void describeTo(Description description) { - description.appendText("mismatchable: " + string); - } - }; - } + mismatchDescription.appendText("mismatched: " + item); + return false; + } + + @Override + public void describeTo(Description description) + { + description.appendText("mismatchable: " + string); + } + }; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java index d3ff21c5..5cacff0f 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java @@ -7,151 +7,170 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsEqual.equalToObject; -public final class IsEqualTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = equalTo("irrelevant"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - comparesObjectsUsingEqualsMethod() { - final Matcher matcher1 = equalTo("hi"); - assertMatches(matcher1, "hi"); - assertDoesNotMatch(matcher1, "bye"); - assertDoesNotMatch(matcher1, null); - - final Matcher matcher2 = equalTo(1); - assertMatches(matcher2, 1); - assertDoesNotMatch(matcher2, 2); - assertDoesNotMatch(matcher2, null); - } - - @Test public void - canCompareNullValues() { - final Matcher matcher = equalTo(null); - - assertMatches(matcher, null); - assertDoesNotMatch(matcher, 2); - assertDoesNotMatch(matcher, "hi"); - assertDoesNotMatch(matcher, new String[] {"a", "b"}); - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Test public void - honoursIsEqualImplementationEvenWithNullValues() { - Object alwaysEqual = new Object() { - @Override - public boolean equals(Object obj) { - return true; - } - }; - Object neverEqual = new Object() { - @Override - public boolean equals(Object obj) { - return false; - } - }; - - Matcher matcher = equalTo(null); - - assertMatches(matcher, alwaysEqual); - assertDoesNotMatch(matcher, neverEqual); - } - - @Test public void - comparesTheElementsOfAnObjectArray() { - String[] s1 = {"a", "b"}; - String[] s2 = {"a", "b"}; - String[] s3 = {"c", "d"}; - String[] s4 = {"a", "b", "c", "d"}; - - final Matcher matcher = equalTo(s1); - assertMatches(matcher, s1); - assertMatches(matcher, s2); - assertDoesNotMatch(matcher, s3); - assertDoesNotMatch(matcher, s4); - assertDoesNotMatch(matcher, null); - } - - @Test public void - comparesTheElementsOfArraysWithNulls() { - String[] s1 = {"a", null, "b"}; - String[] s2 = {"a", null, "b"}; - String[] s3 = {"c", "d"}; - String[] s4 = {"a", "b", "c", "d"}; - - final Matcher matcher = equalTo(s1); - assertMatches(matcher, s1); - assertMatches(matcher, s2); - assertDoesNotMatch(matcher, s3); - assertDoesNotMatch(matcher, s4); - } - - @Test public void - comparesTheElementsOfAnArrayOfPrimitiveTypes() { - int[] i1 = new int[]{1, 2}; - int[] i2 = new int[]{1, 2}; - int[] i3 = new int[]{3, 4}; - int[] i4 = new int[]{1, 2, 3, 4}; - - final Matcher matcher = equalTo(i1); - assertMatches(matcher, i1); - assertMatches(matcher, i2); - assertDoesNotMatch(matcher, i3); - assertDoesNotMatch(matcher, i4); - assertDoesNotMatch(matcher, null); - } - - @Test public void - recursivelyTestsElementsOfArrays() { - int[][] i1 = new int[][]{{1, 2}, {3, 4}}; - int[][] i2 = new int[][]{{1, 2}, {3, 4}}; - int[][] i3 = new int[][]{{5, 6}, {7, 8}}; - int[][] i4 = new int[][]{{1, 2, 3, 4}, {3, 4}}; - - final Matcher matcher = equalTo(i1); - assertMatches(matcher, i1); - assertMatches(matcher, i2); - assertDoesNotMatch(matcher, i3); - assertDoesNotMatch(matcher, i4); - assertDoesNotMatch(matcher, null); - } - - @Test public void - hasUntypedVariant() { - Object original = 10; - - assertMatches(equalToObject(10), original); - assertDoesNotMatch(equalToObject(0), original); - assertDoesNotMatch(equalToObject("10"), original); - assertDoesNotMatch(equalToObject(10), "10"); - } - - @Test public void - includesTheResultOfCallingToStringOnItsArgumentInTheDescription() { - final String argumentDescription = "ARGUMENT DESCRIPTION"; - Object argument = new Object() { - @Override - public String toString() { - return argumentDescription; - } - }; - assertDescription("<" + argumentDescription + ">", equalTo(argument)); - } - - @Test public void - returnsAnObviousDescriptionIfCreatedWithANestedMatcherByMistake() { - Matcher innerMatcher = equalTo("NestedMatcher"); - assertDescription("<" + innerMatcher.toString() + ">", equalTo(innerMatcher)); - } - - @Test public void - returnsGoodDescriptionIfCreatedWithNullReference() { - assertDescription("null", equalTo(null)); - } +public final class IsEqualTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = equalTo("irrelevant"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + comparesObjectsUsingEqualsMethod() + { + final Matcher matcher1 = equalTo("hi"); + assertMatches(matcher1, "hi"); + assertDoesNotMatch(matcher1, "bye"); + assertDoesNotMatch(matcher1, null); + + final Matcher matcher2 = equalTo(1); + assertMatches(matcher2, 1); + assertDoesNotMatch(matcher2, 2); + assertDoesNotMatch(matcher2, null); + } + + @Test public void + canCompareNullValues() + { + final Matcher matcher = equalTo(null); + + assertMatches(matcher, null); + assertDoesNotMatch(matcher, 2); + assertDoesNotMatch(matcher, "hi"); + assertDoesNotMatch(matcher, new String[] { "a", "b" }); + } + + @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") + @Test public void + honoursIsEqualImplementationEvenWithNullValues() + { + Object alwaysEqual = new Object() + { + @Override + public boolean equals(Object obj) + { + return true; + } + }; + Object neverEqual = new Object() + { + @Override + public boolean equals(Object obj) + { + return false; + } + }; + + Matcher matcher = equalTo(null); + + assertMatches(matcher, alwaysEqual); + assertDoesNotMatch(matcher, neverEqual); + } + + @Test public void + comparesTheElementsOfAnObjectArray() + { + String[] s1 = { "a", "b" }; + String[] s2 = { "a", "b" }; + String[] s3 = { "c", "d" }; + String[] s4 = { "a", "b", "c", "d" }; + + final Matcher matcher = equalTo(s1); + assertMatches(matcher, s1); + assertMatches(matcher, s2); + assertDoesNotMatch(matcher, s3); + assertDoesNotMatch(matcher, s4); + assertDoesNotMatch(matcher, null); + } + + @Test public void + comparesTheElementsOfArraysWithNulls() + { + String[] s1 = { "a", null, "b" }; + String[] s2 = { "a", null, "b" }; + String[] s3 = { "c", "d" }; + String[] s4 = { "a", "b", "c", "d" }; + + final Matcher matcher = equalTo(s1); + assertMatches(matcher, s1); + assertMatches(matcher, s2); + assertDoesNotMatch(matcher, s3); + assertDoesNotMatch(matcher, s4); + } + + @Test public void + comparesTheElementsOfAnArrayOfPrimitiveTypes() + { + int[] i1 = new int[] { 1, 2 }; + int[] i2 = new int[] { 1, 2 }; + int[] i3 = new int[] { 3, 4 }; + int[] i4 = new int[] { 1, 2, 3, 4 }; + + final Matcher matcher = equalTo(i1); + assertMatches(matcher, i1); + assertMatches(matcher, i2); + assertDoesNotMatch(matcher, i3); + assertDoesNotMatch(matcher, i4); + assertDoesNotMatch(matcher, null); + } + + @Test public void + recursivelyTestsElementsOfArrays() + { + int[][] i1 = new int[][] { { 1, 2 }, { 3, 4 } }; + int[][] i2 = new int[][] { { 1, 2 }, { 3, 4 } }; + int[][] i3 = new int[][] { { 5, 6 }, { 7, 8 } }; + int[][] i4 = new int[][] { { 1, 2, 3, 4 }, { 3, 4 } }; + + final Matcher matcher = equalTo(i1); + assertMatches(matcher, i1); + assertMatches(matcher, i2); + assertDoesNotMatch(matcher, i3); + assertDoesNotMatch(matcher, i4); + assertDoesNotMatch(matcher, null); + } + + @Test public void + hasUntypedVariant() + { + Object original = 10; + + assertMatches(equalToObject(10), original); + assertDoesNotMatch(equalToObject(0), original); + assertDoesNotMatch(equalToObject("10"), original); + assertDoesNotMatch(equalToObject(10), "10"); + } + + @Test public void + includesTheResultOfCallingToStringOnItsArgumentInTheDescription() + { + final String argumentDescription = "ARGUMENT DESCRIPTION"; + Object argument = new Object() + { + @Override + public String toString() + { + return argumentDescription; + } + }; + assertDescription("<" + argumentDescription + ">", equalTo(argument)); + } + + @Test public void + returnsAnObviousDescriptionIfCreatedWithANestedMatcherByMistake() + { + Matcher innerMatcher = equalTo("NestedMatcher"); + assertDescription("<" + innerMatcher.toString() + ">", equalTo(innerMatcher)); + } + + @Test public void + returnsGoodDescriptionIfCreatedWithNullReference() + { + assertDescription("null", equalTo(null)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java index 8dd85af1..cb71c9c9 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java @@ -7,63 +7,72 @@ import static org.hamcrest.core.IsInstanceOf.any; import static org.hamcrest.core.IsInstanceOf.instanceOf; -public final class IsInstanceOfTest { +public final class IsInstanceOfTest +{ - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = instanceOf(Number.class); + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = instanceOf(Number.class); - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } - @Test public void - evaluatesToTrueIfArgumentIsInstanceOfASpecificClass() { - final Matcher matcher = instanceOf(Number.class); + @Test public void + evaluatesToTrueIfArgumentIsInstanceOfASpecificClass() + { + final Matcher matcher = instanceOf(Number.class); - assertMatches(matcher, 1); - assertMatches(matcher, 1.1); - assertDoesNotMatch(matcher, null); - assertDoesNotMatch(matcher, new Object()); - } + assertMatches(matcher, 1); + assertMatches(matcher, 1.1); + assertDoesNotMatch(matcher, null); + assertDoesNotMatch(matcher, new Object()); + } - @Test public void - hasAReadableDescription() { - assertDescription("an instance of java.lang.Number", instanceOf(Number.class)); - } + @Test public void + hasAReadableDescription() + { + assertDescription("an instance of java.lang.Number", instanceOf(Number.class)); + } - @Test public void - describesActualClassInMismatchMessage() { - assertMismatchDescription("\"some text\" is a java.lang.String", instanceOf(Number.class), "some text"); - } + @Test public void + describesActualClassInMismatchMessage() + { + assertMismatchDescription("\"some text\" is a java.lang.String", instanceOf(Number.class), "some text"); + } - @Test public void - matchesPrimitiveTypes() { - assertMatches(any(boolean.class), true); - assertMatches(any(byte.class), (byte)1); - assertMatches(any(char.class), 'x'); - assertMatches(any(double.class), 5.0); - assertMatches(any(float.class), 5.0f); - assertMatches(any(int.class), 2); - assertMatches(any(long.class), 4L); - assertMatches(any(short.class), (short)1); - } + @Test public void + matchesPrimitiveTypes() + { + assertMatches(any(boolean.class), true); + assertMatches(any(byte.class), (byte) 1); + assertMatches(any(char.class), 'x'); + assertMatches(any(double.class), 5.0); + assertMatches(any(float.class), 5.0f); + assertMatches(any(int.class), 2); + assertMatches(any(long.class), 4L); + assertMatches(any(short.class), (short) 1); + } - @Test public void - instanceOfRequiresACastToReturnTheCorrectTypeForUseInJMock() { - @SuppressWarnings("unused") - Integer anInteger = (Integer)with(instanceOf(Integer.class)); - } + @Test public void + instanceOfRequiresACastToReturnTheCorrectTypeForUseInJMock() + { + @SuppressWarnings("unused") + Integer anInteger = (Integer) with(instanceOf(Integer.class)); + } - @Test public void - anyWillReturnTheCorrectTypeForUseInJMock() { - @SuppressWarnings("unused") - Integer anInteger = with(any(Integer.class)); - } + @Test public void + anyWillReturnTheCorrectTypeForUseInJMock() + { + @SuppressWarnings("unused") + Integer anInteger = with(any(Integer.class)); + } - private static T with(@SuppressWarnings("unused") Matcher matcher) { - return null; - } + private static T with(@SuppressWarnings("unused") Matcher matcher) + { + return null; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java index 02148b81..df5492d9 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java @@ -15,93 +15,108 @@ import static org.hamcrest.core.IsIterableContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; -public final class IsIterableContainingTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = hasItem(equalTo("irrelevant")); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesACollectionThatContainsAnElementForTheGivenMatcher() { - final Matcher> itemMatcher = hasItem(equalTo("a")); - - assertMatches("list containing 'a'", itemMatcher, asList("a", "b", "c")); - } - - @Test public void - doesNotMatchCollectionWithoutAnElementForGivenMatcher() { - final Matcher> matcher = hasItem(mismatchable("a")); - - assertMismatchDescription("mismatches were: [mismatched: b, mismatched: c]", matcher, asList("b", "c")); - assertMismatchDescription("was empty", matcher, new ArrayList()); - } - - @Test public void - doesNotMatchNull() { - assertDoesNotMatch("doesn't match null", hasItem(equalTo("a")), null); - } - - @Test public void - hasAReadableDescription() { - assertDescription("a collection containing mismatchable: a", hasItem(mismatchable("a"))); - } - - @Test public void - canMatchItemWhenCollectionHoldsSuperclass() { // Issue 24 - final Set s = new HashSet<>(); - s.add(2); - - assertMatches(new IsIterableContaining<>(new IsEqual(2)), s); - assertMatches(IsIterableContaining.hasItem(2), s); - } - - @SuppressWarnings("unchecked") - @Test public void - matchesMultipleItemsInCollection() { - final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertMatches("list containing all items", matcher1, asList("a", "b", "c")); - - final Matcher> matcher2 = hasItems("a", "b", "c"); - assertMatches("list containing all items (without matchers)", matcher2, asList("a", "b", "c")); - - final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertMatches("list containing all items in any order", matcher3, asList("c", "b", "a")); - - final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertMatches("list containing all items plus others", matcher4, asList("e", "c", "b", "a", "d")); - - final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); - assertDoesNotMatch("not match list unless it contains all items", matcher5, asList("e", "c", "b", "d")); // 'a' missing - } - - @Test public void - reportsMismatchWithAReadableDescriptionForMultipleItems() { - final Matcher> matcher = hasItems(3, 4); - - assertMismatchDescription("a collection containing <4> mismatches were: [was <1>, was <2>, was <3>]", - matcher, asList(1, 2, 3)); - } - - private static Matcher mismatchable(final String string) { - return new TypeSafeDiagnosingMatcher() { - @Override - protected boolean matchesSafely(String item, Description mismatchDescription) { - if (string.equals(item)) - return true; - - mismatchDescription.appendText("mismatched: " + item); - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText("mismatchable: " + string); - } - }; - } +public final class IsIterableContainingTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = hasItem(equalTo("irrelevant")); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesACollectionThatContainsAnElementForTheGivenMatcher() + { + final Matcher> itemMatcher = hasItem(equalTo("a")); + + assertMatches("list containing 'a'", itemMatcher, asList("a", "b", "c")); + } + + @Test public void + doesNotMatchCollectionWithoutAnElementForGivenMatcher() + { + final Matcher> matcher = hasItem(mismatchable("a")); + + assertMismatchDescription("mismatches were: [mismatched: b, mismatched: c]", matcher, asList("b", "c")); + assertMismatchDescription("was empty", matcher, new ArrayList()); + } + + @Test public void + doesNotMatchNull() + { + assertDoesNotMatch("doesn't match null", hasItem(equalTo("a")), null); + } + + @Test public void + hasAReadableDescription() + { + assertDescription("a collection containing mismatchable: a", hasItem(mismatchable("a"))); + } + + @Test public void + canMatchItemWhenCollectionHoldsSuperclass() + { // Issue 24 + final Set s = new HashSet<>(); + s.add(2); + + assertMatches(new IsIterableContaining<>(new IsEqual(2)), s); + assertMatches(IsIterableContaining.hasItem(2), s); + } + + @SuppressWarnings("unchecked") + @Test public void + matchesMultipleItemsInCollection() + { + final Matcher> matcher1 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertMatches("list containing all items", matcher1, asList("a", "b", "c")); + + final Matcher> matcher2 = hasItems("a", "b", "c"); + assertMatches("list containing all items (without matchers)", matcher2, asList("a", "b", "c")); + + final Matcher> matcher3 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertMatches("list containing all items in any order", matcher3, asList("c", "b", "a")); + + final Matcher> matcher4 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertMatches("list containing all items plus others", matcher4, asList("e", "c", "b", "a", "d")); + + final Matcher> matcher5 = hasItems(equalTo("a"), equalTo("b"), equalTo("c")); + assertDoesNotMatch("not match list unless it contains all items", matcher5, asList("e", "c", "b", "d")); // 'a' missing + } + + @Test public void + reportsMismatchWithAReadableDescriptionForMultipleItems() + { + final Matcher> matcher = hasItems(3, 4); + + assertMismatchDescription("a collection containing <4> mismatches were: [was <1>, was <2>, was <3>]", + matcher, asList(1, 2, 3)); + } + + private static Matcher mismatchable(final String string) + { + return new TypeSafeDiagnosingMatcher() + { + @Override + protected boolean matchesSafely(String item, Description mismatchDescription) + { + if (string.equals(item)) + { + return true; + } + + mismatchDescription.appendText("mismatched: " + item); + return false; + } + + @Override + public void describeTo(Description description) + { + description.appendText("mismatchable: " + string); + } + }; + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java index 79f46837..2401eddc 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java @@ -8,35 +8,40 @@ import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNot.not; -public final class IsNotTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = not("something"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - evaluatesToTheTheLogicalNegationOfAnotherMatcher() { - final Matcher matcher = not(equalTo("A")); - - assertMatches(matcher, "B"); - assertDoesNotMatch(matcher, "A"); - } - - @Test public void - providesConvenientShortcutForNotEqualTo() { - final Matcher matcher = not("A"); - - assertMatches(matcher, "B"); - assertDoesNotMatch(matcher, "A"); - } - - @Test public void - usesDescriptionOfNegatedMatcherWithPrefix() { - assertDescription("not an instance of java.lang.String", not(instanceOf(String.class))); - assertDescription("not \"A\"", not("A")); - } +public final class IsNotTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = not("something"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + evaluatesToTheTheLogicalNegationOfAnotherMatcher() + { + final Matcher matcher = not(equalTo("A")); + + assertMatches(matcher, "B"); + assertDoesNotMatch(matcher, "A"); + } + + @Test public void + providesConvenientShortcutForNotEqualTo() + { + final Matcher matcher = not("A"); + + assertMatches(matcher, "B"); + assertDoesNotMatch(matcher, "A"); + } + + @Test public void + usesDescriptionOfNegatedMatcherWithPrefix() + { + assertDescription("not an instance of java.lang.String", not(instanceOf(String.class))); + assertDescription("not \"A\"", not("A")); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java index 74b046b5..c6f8073d 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java @@ -8,36 +8,41 @@ import static org.hamcrest.core.IsNull.nullValue; -public final class IsNullTest { - - private final Matcher nullMatcher = nullValue(); - private final Matcher notNullMatcher = notNullValue(); - - @Test public void - copesWithNullsAndUnknownTypes() { - assertNullSafe(nullMatcher); - assertUnknownTypeSafe(nullMatcher); - - assertNullSafe(notNullMatcher); - assertUnknownTypeSafe(notNullMatcher); - } - - @Test public void - evaluatesToTrueIfArgumentIsNull() { - assertMatches(nullMatcher, null); - assertDoesNotMatch(nullMatcher, new Object()); - - assertMatches(notNullMatcher, new Object()); - assertDoesNotMatch(notNullMatcher, null); - } - - @Test public void - supportsStaticTyping() { - requiresStringMatcher(nullValue(String.class)); - requiresStringMatcher(notNullValue(String.class)); - } - - private void requiresStringMatcher(@SuppressWarnings("unused") Matcher arg) { - // no-op - } +public final class IsNullTest +{ + + private final Matcher nullMatcher = nullValue(); + private final Matcher notNullMatcher = notNullValue(); + + @Test public void + copesWithNullsAndUnknownTypes() + { + assertNullSafe(nullMatcher); + assertUnknownTypeSafe(nullMatcher); + + assertNullSafe(notNullMatcher); + assertUnknownTypeSafe(notNullMatcher); + } + + @Test public void + evaluatesToTrueIfArgumentIsNull() + { + assertMatches(nullMatcher, null); + assertDoesNotMatch(nullMatcher, new Object()); + + assertMatches(notNullMatcher, new Object()); + assertDoesNotMatch(notNullMatcher, null); + } + + @Test public void + supportsStaticTyping() + { + requiresStringMatcher(nullValue(String.class)); + requiresStringMatcher(notNullValue(String.class)); + } + + private void requiresStringMatcher(@SuppressWarnings("unused") Matcher arg) + { + // no-op + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java index a4a20105..6ab8e4b9 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java @@ -8,41 +8,47 @@ import static org.hamcrest.core.IsSame.theInstance; -public final class IsSameTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = sameInstance("irrelevant"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - evaluatesToTrueIfArgumentIsReferenceToASpecifiedObject() { - Object o1 = new Object(); - Matcher matcher = sameInstance(o1); - - assertMatches(matcher, o1); - assertDoesNotMatch(matcher, new Object()); - } - - @Test public void - alternativeFactoryMethodAlsoMatchesOnlyIfArgumentIsReferenceToASpecifiedObject() { - Object o1 = new Object(); - Matcher matcher = theInstance(o1); - - assertMatches(matcher, o1); - assertDoesNotMatch(matcher, new Object()); - } - - @Test public void - returnsReadableDescriptionFromToString() { - assertDescription("sameInstance(\"ARG\")", sameInstance("ARG")); - } - - @Test public void - returnsReadableDescriptionFromToStringWhenInitialisedWithNull() { - assertDescription("sameInstance(null)", sameInstance(null)); - } +public final class IsSameTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = sameInstance("irrelevant"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + evaluatesToTrueIfArgumentIsReferenceToASpecifiedObject() + { + Object o1 = new Object(); + Matcher matcher = sameInstance(o1); + + assertMatches(matcher, o1); + assertDoesNotMatch(matcher, new Object()); + } + + @Test public void + alternativeFactoryMethodAlsoMatchesOnlyIfArgumentIsReferenceToASpecifiedObject() + { + Object o1 = new Object(); + Matcher matcher = theInstance(o1); + + assertMatches(matcher, o1); + assertDoesNotMatch(matcher, new Object()); + } + + @Test public void + returnsReadableDescriptionFromToString() + { + assertDescription("sameInstance(\"ARG\")", sameInstance("ARG")); + } + + @Test public void + returnsReadableDescriptionFromToStringWhenInitialisedWithNull() + { + assertDescription("sameInstance(null)", sameInstance(null)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/IsTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsTest.java index d5220bde..a3de91df 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsTest.java @@ -8,44 +8,50 @@ import static org.hamcrest.core.Is.isA; import static org.hamcrest.core.IsEqual.equalTo; -public final class IsTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = is("something"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesTheSameWayTheUnderlyingMatcherDoes() { - final Matcher matcher = is(equalTo(true)); - - assertMatches(matcher, true); - assertDoesNotMatch(matcher, false); - } - - @Test public void - generatesIsPrefixInDescription() { - assertDescription("is ", is(equalTo(true))); - assertDescription("is \"A\"", is("A")); - } - - @Test public void - providesConvenientShortcutForIsEqualTo() { - final Matcher matcher = is("A"); - - assertMatches(matcher, "A"); - assertDoesNotMatch(is("A"), "B"); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test public void - providesConvenientShortcutForIsInstanceOf() { - final Matcher matcher = isA(Number.class); - assertMatches(matcher, 1); - assertDoesNotMatch(matcher, new Object()); - assertDoesNotMatch(matcher, null); - } +public final class IsTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = is("something"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesTheSameWayTheUnderlyingMatcherDoes() + { + final Matcher matcher = is(equalTo(true)); + + assertMatches(matcher, true); + assertDoesNotMatch(matcher, false); + } + + @Test public void + generatesIsPrefixInDescription() + { + assertDescription("is ", is(equalTo(true))); + assertDescription("is \"A\"", is("A")); + } + + @Test public void + providesConvenientShortcutForIsEqualTo() + { + final Matcher matcher = is("A"); + + assertMatches(matcher, "A"); + assertDoesNotMatch(is("A"), "B"); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test public void + providesConvenientShortcutForIsInstanceOf() + { + final Matcher matcher = isA(Number.class); + assertMatches(matcher, 1); + assertDoesNotMatch(matcher, new Object()); + assertDoesNotMatch(matcher, null); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java b/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java index baf4d8e9..eb6e9728 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java +++ b/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java @@ -1,24 +1,29 @@ package org.hamcrest.core; -public class SampleBaseClass { - String value; +public class SampleBaseClass +{ + String value; - public SampleBaseClass(String value) { - this.value = value; - } + public SampleBaseClass(String value) + { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() + { + return value; + } - @Override - public boolean equals(Object obj) { - return obj instanceof SampleBaseClass && value.equals(((SampleBaseClass) obj).value); - } + @Override + public boolean equals(Object obj) + { + return obj instanceof SampleBaseClass && value.equals(((SampleBaseClass) obj).value); + } - @Override - public int hashCode() { - return value.hashCode(); - } + @Override + public int hashCode() + { + return value.hashCode(); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java b/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java index bdaa160f..211606ec 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java +++ b/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java @@ -1,9 +1,11 @@ package org.hamcrest.core; -public class SampleSubClass extends SampleBaseClass { - - public SampleSubClass(String value) { - super(value); - } +public class SampleSubClass extends SampleBaseClass +{ + + public SampleSubClass(String value) + { + super(value); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java b/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java index 1fc269ef..e7f8415f 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java @@ -7,39 +7,43 @@ import static org.hamcrest.core.StringContains.containsStringIgnoringCase; -public class StringContainsTest extends AbstractMatcherTest { - static final String EXCERPT = "EXCERPT"; - final Matcher stringContains = containsString(EXCERPT); - - @Override - protected Matcher createMatcher() { - return stringContains; - } - - public void testMatchesSubstrings() { - assertMatches(stringContains, EXCERPT + "END"); - assertMatches(stringContains, "START" + EXCERPT); - assertMatches(stringContains, "START" + EXCERPT + "END"); - assertMatches(stringContains, EXCERPT); - assertDoesNotMatch(stringContains, EXCERPT.toLowerCase()); - assertMatches(stringContains, EXCERPT + EXCERPT); - assertDoesNotMatch(stringContains, "XC"); - - assertMismatchDescription("was \"Something else\"", stringContains, "Something else"); - assertDescription("a string containing \"EXCERPT\"", stringContains); - } - - public void testMatchesSubstringsIgnoringCase() { - final Matcher ignoringCase = containsStringIgnoringCase("ExCert"); - assertMatches(ignoringCase, "eXcERT" + "END"); - assertMatches(ignoringCase, "START" + "EXCert"); - assertMatches(ignoringCase, "START" + "excERT" + "END"); - assertMatches(ignoringCase, "eXCert" + "excErt"); - assertDoesNotMatch(ignoringCase, "xc"); - - assertMismatchDescription("was \"Something else\"", ignoringCase, "Something else"); - assertDescription("a string containing \"ExCert\" ignoring case", ignoringCase); - } +public class StringContainsTest extends AbstractMatcherTest +{ + static final String EXCERPT = "EXCERPT"; + final Matcher stringContains = containsString(EXCERPT); + + @Override + protected Matcher createMatcher() + { + return stringContains; + } + + public void testMatchesSubstrings() + { + assertMatches(stringContains, EXCERPT + "END"); + assertMatches(stringContains, "START" + EXCERPT); + assertMatches(stringContains, "START" + EXCERPT + "END"); + assertMatches(stringContains, EXCERPT); + assertDoesNotMatch(stringContains, EXCERPT.toLowerCase()); + assertMatches(stringContains, EXCERPT + EXCERPT); + assertDoesNotMatch(stringContains, "XC"); + + assertMismatchDescription("was \"Something else\"", stringContains, "Something else"); + assertDescription("a string containing \"EXCERPT\"", stringContains); + } + + public void testMatchesSubstringsIgnoringCase() + { + final Matcher ignoringCase = containsStringIgnoringCase("ExCert"); + assertMatches(ignoringCase, "eXcERT" + "END"); + assertMatches(ignoringCase, "START" + "EXCert"); + assertMatches(ignoringCase, "START" + "excERT" + "END"); + assertMatches(ignoringCase, "eXCert" + "excErt"); + assertDoesNotMatch(ignoringCase, "xc"); + + assertMismatchDescription("was \"Something else\"", ignoringCase, "Something else"); + assertDescription("a string containing \"ExCert\" ignoring case", ignoringCase); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java b/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java index f482cbfa..eef5e4e8 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java @@ -7,39 +7,43 @@ import static org.hamcrest.core.StringEndsWith.endsWithIgnoringCase; -public class StringEndsWithTest extends AbstractMatcherTest { - static final String EXCERPT = "EXCERPT"; - final Matcher stringEndsWith = endsWith(EXCERPT); - - @Override - protected Matcher createMatcher() { - return stringEndsWith; - } - - public void testMatchesSubstringAtEnd() { - assertDoesNotMatch(stringEndsWith, EXCERPT + "END"); - assertMatches(stringEndsWith, "START" + EXCERPT); - assertMatches(stringEndsWith, EXCERPT); - assertDoesNotMatch(stringEndsWith, EXCERPT.toLowerCase()); - assertDoesNotMatch(stringEndsWith, "START" + EXCERPT + "END"); - assertMatches(stringEndsWith, EXCERPT + EXCERPT); - assertDoesNotMatch(stringEndsWith, "EXCER"); - - assertMismatchDescription("was \"Something else\"", stringEndsWith, "Something else"); - assertDescription("a string ending with \"EXCERPT\"", stringEndsWith); - } - - public void testMatchesSubstringAtEndIngoringCase() { - final Matcher ignoringCase = endsWithIgnoringCase("EXCERpt"); - assertDoesNotMatch(ignoringCase, "eXCErpt" + "END"); - assertMatches(ignoringCase, "START" + "EXceRpt"); - assertMatches(ignoringCase, "EXcerPT"); - assertDoesNotMatch(ignoringCase, "START" + "ExcERpt" + "END"); - assertMatches(ignoringCase, "exCERpt" + "EXCerPt"); - assertDoesNotMatch(ignoringCase, "ExcER"); - - assertMismatchDescription("was \"Something else\"", ignoringCase, "Something else"); - assertDescription("a string ending with \"EXCERpt\" ignoring case", ignoringCase); - } +public class StringEndsWithTest extends AbstractMatcherTest +{ + static final String EXCERPT = "EXCERPT"; + final Matcher stringEndsWith = endsWith(EXCERPT); + + @Override + protected Matcher createMatcher() + { + return stringEndsWith; + } + + public void testMatchesSubstringAtEnd() + { + assertDoesNotMatch(stringEndsWith, EXCERPT + "END"); + assertMatches(stringEndsWith, "START" + EXCERPT); + assertMatches(stringEndsWith, EXCERPT); + assertDoesNotMatch(stringEndsWith, EXCERPT.toLowerCase()); + assertDoesNotMatch(stringEndsWith, "START" + EXCERPT + "END"); + assertMatches(stringEndsWith, EXCERPT + EXCERPT); + assertDoesNotMatch(stringEndsWith, "EXCER"); + + assertMismatchDescription("was \"Something else\"", stringEndsWith, "Something else"); + assertDescription("a string ending with \"EXCERPT\"", stringEndsWith); + } + + public void testMatchesSubstringAtEndIngoringCase() + { + final Matcher ignoringCase = endsWithIgnoringCase("EXCERpt"); + assertDoesNotMatch(ignoringCase, "eXCErpt" + "END"); + assertMatches(ignoringCase, "START" + "EXceRpt"); + assertMatches(ignoringCase, "EXcerPT"); + assertDoesNotMatch(ignoringCase, "START" + "ExcERpt" + "END"); + assertMatches(ignoringCase, "exCERpt" + "EXCerPt"); + assertDoesNotMatch(ignoringCase, "ExcER"); + + assertMismatchDescription("was \"Something else\"", ignoringCase, "Something else"); + assertDescription("a string ending with \"EXCERpt\" ignoring case", ignoringCase); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java b/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java index 7c2e5cd0..0cf15747 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java @@ -11,23 +11,27 @@ /** * @author Steve Freeman 2016 http://www.hamcrest.com */ -public class StringMatchingTest { +public class StringMatchingTest +{ @Rule public final ExpectedException thrown = ExpectedException.none(); @Test public void - startsWithFailsWithNullSubstring() { + startsWithFailsWithNullSubstring() + { thrown.expect(IllegalArgumentException.class); startsWith(null); } @Test public void - endWithFailsWithNullSubstring() { + endWithFailsWithNullSubstring() + { thrown.expect(IllegalArgumentException.class); endsWith(null); } @Test public void - containsFailsWithNullSubstring() { + containsFailsWithNullSubstring() + { thrown.expect(IllegalArgumentException.class); containsString(null); } diff --git a/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java b/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java index 2b2991bf..eed55836 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java @@ -8,14 +8,19 @@ /** * @author Steve Freeman 2016 http://www.hamcrest.com */ -public class StringRegularExpressionTest extends AbstractMatcherTest { +public class StringRegularExpressionTest extends AbstractMatcherTest +{ public final Matcher matcher = matchesRegex("^[0-9]+$"); @Override - protected Matcher createMatcher() { return matcher; } + protected Matcher createMatcher() + { + return matcher; + } - public void testMatchingRegex() { + public void testMatchingRegex() + { assertMatches(matcher, "12"); assertDoesNotMatch(matcher, "abc"); diff --git a/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java b/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java index f093acb4..07112000 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java @@ -7,40 +7,44 @@ import static org.hamcrest.core.StringStartsWith.startsWithIgnoringCase; -public class StringStartsWithTest extends AbstractMatcherTest { - static final String EXCERPT = "EXCERPT"; - final Matcher stringStartsWith = startsWith(EXCERPT); - - @Override - protected Matcher createMatcher() { - return stringStartsWith; - } - - public void testMatchesStringAtStart() { - assertMatches(stringStartsWith, EXCERPT + "END"); - assertDoesNotMatch(stringStartsWith, "START" + EXCERPT); - assertDoesNotMatch(stringStartsWith, "START" + EXCERPT + "END"); - assertMatches(stringStartsWith, EXCERPT); - assertDoesNotMatch(stringStartsWith, EXCERPT.toLowerCase()); - assertMatches(stringStartsWith, EXCERPT + EXCERPT); - assertDoesNotMatch(stringStartsWith, "EXCER"); - - assertDescription("a string starting with \"EXCERPT\"", stringStartsWith); - assertMismatchDescription("was \"Something else\"", stringStartsWith, "Something else"); - } - - public void testMatchesStringAtStartIgnoringCase() { - final Matcher ignoreCase = startsWithIgnoringCase("EXCerPT"); - - assertMatches(ignoreCase, "exCerPT" + "END"); - assertDoesNotMatch(ignoreCase, "START" + "EXCerpt"); - assertDoesNotMatch(ignoreCase, "START" + "EXcerpT" + "END"); - assertMatches(ignoreCase, "excERPT"); - assertMatches(ignoreCase, "ExcerPT" + "EXCerpt"); - assertDoesNotMatch(ignoreCase, "ExcER"); - - assertDescription("a string starting with \"EXCerPT\" ignoring case", ignoreCase); - assertMismatchDescription("was \"Something else\"", ignoreCase, "Something else"); - } +public class StringStartsWithTest extends AbstractMatcherTest +{ + static final String EXCERPT = "EXCERPT"; + final Matcher stringStartsWith = startsWith(EXCERPT); + + @Override + protected Matcher createMatcher() + { + return stringStartsWith; + } + + public void testMatchesStringAtStart() + { + assertMatches(stringStartsWith, EXCERPT + "END"); + assertDoesNotMatch(stringStartsWith, "START" + EXCERPT); + assertDoesNotMatch(stringStartsWith, "START" + EXCERPT + "END"); + assertMatches(stringStartsWith, EXCERPT); + assertDoesNotMatch(stringStartsWith, EXCERPT.toLowerCase()); + assertMatches(stringStartsWith, EXCERPT + EXCERPT); + assertDoesNotMatch(stringStartsWith, "EXCER"); + + assertDescription("a string starting with \"EXCERPT\"", stringStartsWith); + assertMismatchDescription("was \"Something else\"", stringStartsWith, "Something else"); + } + + public void testMatchesStringAtStartIgnoringCase() + { + final Matcher ignoreCase = startsWithIgnoringCase("EXCerPT"); + + assertMatches(ignoreCase, "exCerPT" + "END"); + assertDoesNotMatch(ignoreCase, "START" + "EXCerpt"); + assertDoesNotMatch(ignoreCase, "START" + "EXcerpT" + "END"); + assertMatches(ignoreCase, "excERPT"); + assertMatches(ignoreCase, "ExcerPT" + "EXCerpt"); + assertDoesNotMatch(ignoreCase, "ExcER"); + + assertDescription("a string starting with \"EXCerPT\" ignoring case", ignoreCase); + assertMismatchDescription("was \"Something else\"", ignoreCase, "Something else"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java b/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java index c94e147d..3ff009a2 100644 --- a/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java +++ b/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java @@ -9,83 +9,97 @@ import static org.hamcrest.core.IsEqual.equalTo; @SuppressWarnings("ResultOfMethodCallIgnored") -public class FileMatchersTest extends AbstractMatcherTest { - - private File directory; - private File file; - - @Override - protected void setUp() throws IOException { - directory = File.createTempFile("myDir", ""); - assertTrue("deleting " + directory, directory.delete()); - assertTrue("mkdir " + directory, directory.mkdirs()); - - file = new File(directory, "myFile"); - file.createNewFile(); - } - - public void testAnExistingDirectory() { - assertMatches("matches existing directory", FileMatchers.anExistingDirectory(), directory); - assertDoesNotMatch("doesn't match existing file", FileMatchers.anExistingDirectory(), file); - assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingDirectory(), new File("foo")); - } - - public void testAnExistingFileOrDirectory() { - assertMatches("matches existing file", FileMatchers.anExistingFileOrDirectory(), file); - assertMatches("matches existing directory", FileMatchers.anExistingFileOrDirectory(), directory); - assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingFileOrDirectory(), new File("foo")); - } - - public void testAnExistingFile() { - assertMatches("matches existing file", FileMatchers.anExistingFile(), file); - assertDoesNotMatch("doesn't match existing directory", FileMatchers.anExistingFile(), directory); - assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingFile(), new File("foo")); - } - - public void testAReadableFile() { // Not all OSes will allow setting readability so have to be forgiving here. - file.setReadable(true); - assertMatches("matches readable file", FileMatchers.aReadableFile(), file); - - if (file.setReadable(false)) { - assertDoesNotMatch("doesn't match unreadable file", FileMatchers.aReadableFile(), file); - } - } - - public void testAWritableFile() { - assertMatches("matches writable file", FileMatchers.aWritableFile(), file); - - assertTrue("set writable off " + file, file.setWritable(false)); - assertDoesNotMatch("doesn't match unwritable file", FileMatchers.aWritableFile(), file); - } - - public void testAFileWithSizeLong() { - assertMatches("matches file size", FileMatchers.aFileWithSize(0L), file); - assertDoesNotMatch("doesn't match incorrect file size", FileMatchers.aFileWithSize(34L), file); - } - - public void testAFileWithSizeMatcherOfLong() { - assertMatches("matches file size", FileMatchers.aFileWithSize(equalTo(0L)), file); - assertDoesNotMatch("doesn't match incorrect file size", FileMatchers.aFileWithSize(equalTo(23L)), file); - } - - public void testAFileNamed() { - assertMatches("matches file name", FileMatchers.aFileNamed(equalTo(file.getName())), file); - assertDoesNotMatch("doesn't match incorrect file name", FileMatchers.aFileNamed(equalTo("foo")), file); - } - - public void testAFileWithCanonicalPath() throws Exception { - assertMatches("matches file canonical path", FileMatchers.aFileWithCanonicalPath(equalTo(file.getCanonicalPath())), file); - assertDoesNotMatch("doesn't match incorrect canonical path", FileMatchers.aFileWithCanonicalPath(equalTo("foo")), file); - } - - public void testAFileWithAbsolutePath() { - assertMatches("matches file absolute path", FileMatchers.aFileWithAbsolutePath(equalTo(file.getAbsolutePath())), file); - assertDoesNotMatch("doesn't match incorrect absolute path", FileMatchers.aFileWithAbsolutePath(equalTo("foo")), file); - } - - @Override - protected Matcher createMatcher() { - return FileMatchers.aFileWithSize(1L); +public class FileMatchersTest extends AbstractMatcherTest +{ + + private File directory; + private File file; + + @Override + protected void setUp() throws IOException + { + directory = File.createTempFile("myDir", ""); + assertTrue("deleting " + directory, directory.delete()); + assertTrue("mkdir " + directory, directory.mkdirs()); + + file = new File(directory, "myFile"); + file.createNewFile(); + } + + public void testAnExistingDirectory() + { + assertMatches("matches existing directory", FileMatchers.anExistingDirectory(), directory); + assertDoesNotMatch("doesn't match existing file", FileMatchers.anExistingDirectory(), file); + assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingDirectory(), new File("foo")); + } + + public void testAnExistingFileOrDirectory() + { + assertMatches("matches existing file", FileMatchers.anExistingFileOrDirectory(), file); + assertMatches("matches existing directory", FileMatchers.anExistingFileOrDirectory(), directory); + assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingFileOrDirectory(), new File("foo")); + } + + public void testAnExistingFile() + { + assertMatches("matches existing file", FileMatchers.anExistingFile(), file); + assertDoesNotMatch("doesn't match existing directory", FileMatchers.anExistingFile(), directory); + assertDoesNotMatch("doesn't match missing file", FileMatchers.anExistingFile(), new File("foo")); + } + + public void testAReadableFile() + { // Not all OSes will allow setting readability so have to be forgiving here. + file.setReadable(true); + assertMatches("matches readable file", FileMatchers.aReadableFile(), file); + + if (file.setReadable(false)) + { + assertDoesNotMatch("doesn't match unreadable file", FileMatchers.aReadableFile(), file); } + } + + public void testAWritableFile() + { + assertMatches("matches writable file", FileMatchers.aWritableFile(), file); + + assertTrue("set writable off " + file, file.setWritable(false)); + assertDoesNotMatch("doesn't match unwritable file", FileMatchers.aWritableFile(), file); + } + + public void testAFileWithSizeLong() + { + assertMatches("matches file size", FileMatchers.aFileWithSize(0L), file); + assertDoesNotMatch("doesn't match incorrect file size", FileMatchers.aFileWithSize(34L), file); + } + + public void testAFileWithSizeMatcherOfLong() + { + assertMatches("matches file size", FileMatchers.aFileWithSize(equalTo(0L)), file); + assertDoesNotMatch("doesn't match incorrect file size", FileMatchers.aFileWithSize(equalTo(23L)), file); + } + + public void testAFileNamed() + { + assertMatches("matches file name", FileMatchers.aFileNamed(equalTo(file.getName())), file); + assertDoesNotMatch("doesn't match incorrect file name", FileMatchers.aFileNamed(equalTo("foo")), file); + } + + public void testAFileWithCanonicalPath() throws Exception + { + assertMatches("matches file canonical path", FileMatchers.aFileWithCanonicalPath(equalTo(file.getCanonicalPath())), file); + assertDoesNotMatch("doesn't match incorrect canonical path", FileMatchers.aFileWithCanonicalPath(equalTo("foo")), file); + } + + public void testAFileWithAbsolutePath() + { + assertMatches("matches file absolute path", FileMatchers.aFileWithAbsolutePath(equalTo(file.getAbsolutePath())), file); + assertDoesNotMatch("doesn't match incorrect absolute path", FileMatchers.aFileWithAbsolutePath(equalTo("foo")), file); + } + + @Override + protected Matcher createMatcher() + { + return FileMatchers.aFileWithSize(1L); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java b/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java index c82e6f4e..1809666c 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java @@ -7,16 +7,19 @@ import static org.hamcrest.number.BigDecimalCloseTo.closeTo; -public class BigDecimalCloseToTest extends AbstractMatcherTest { +public class BigDecimalCloseToTest extends AbstractMatcherTest +{ private final Matcher matcher = closeTo(new BigDecimal("1.0"), new BigDecimal("0.5")); @Override - protected Matcher createMatcher() { + protected Matcher createMatcher() + { BigDecimal irrelevant = new BigDecimal("0.01"); return closeTo(irrelevant, irrelevant); } - - public void testEvaluatesToTrueIfArgumentIsEqualToABigDecimalWithinSomeError() { + + public void testEvaluatesToTrueIfArgumentIsEqualToABigDecimalWithinSomeError() + { assertTrue(matcher.matches(new BigDecimal("1.0"))); assertTrue(matcher.matches(new BigDecimal("0.5"))); assertTrue(matcher.matches(new BigDecimal("1.5"))); @@ -26,8 +29,9 @@ public void testEvaluatesToTrueIfArgumentIsEqualToABigDecimalWithinSomeError() { assertDoesNotMatch("number too small", matcher, new BigDecimal("0.0")); assertMismatchDescription("<0.0> differed by <0.5> more than delta <0.5>", matcher, new BigDecimal("0.0")); } - - public void testEvaluatesToTrueIfArgumentHasDifferentScale() { + + public void testEvaluatesToTrueIfArgumentHasDifferentScale() + { assertTrue(matcher.matches(new BigDecimal("1.000000"))); assertTrue(matcher.matches(new BigDecimal("0.500000"))); assertTrue(matcher.matches(new BigDecimal("1.500000"))); @@ -38,7 +42,8 @@ public void testEvaluatesToTrueIfArgumentHasDifferentScale() { assertMismatchDescription("<0.000000> differed by <0.5> more than delta <0.5>", matcher, new BigDecimal("0.000000")); } - public void test_is_self_describing() { + public void test_is_self_describing() + { assertDescription("a numeric value within <0.5> of <1.0>", matcher); } diff --git a/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java b/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java index 8b0e244b..ff2cd11c 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java @@ -5,28 +5,32 @@ import static org.hamcrest.number.IsCloseTo.closeTo; -public class IsCloseToTest extends AbstractMatcherTest { +public class IsCloseToTest extends AbstractMatcherTest +{ private final Matcher matcher = closeTo(1.0d, 0.5d); @Override - protected Matcher createMatcher() { - final double irrelevant = 0.1; - return closeTo(irrelevant, irrelevant); - } - - public void test_matchesIfArgumentIsEqualToADoubleValueWithinSomeError() { - assertMatches("1.0", matcher, 1.0); - assertMatches("0.5d", matcher, 0.5d); - assertMatches("1.5d", matcher, 1.5d); - - assertDoesNotMatch("too large", matcher, 2.0); - assertMismatchDescription("<3.0> differed by <1.5> more than delta <0.5>", matcher, 3.0d); - assertDoesNotMatch("number too small", matcher, 0.0); - assertMismatchDescription("<0.1> differed by <0.4> more than delta <0.5>", matcher, 0.1); - } - - public void test_is_self_describing() { - assertDescription("a numeric value within <0.5> of <1.0>", matcher); - } + protected Matcher createMatcher() + { + final double irrelevant = 0.1; + return closeTo(irrelevant, irrelevant); + } + + public void test_matchesIfArgumentIsEqualToADoubleValueWithinSomeError() + { + assertMatches("1.0", matcher, 1.0); + assertMatches("0.5d", matcher, 0.5d); + assertMatches("1.5d", matcher, 1.5d); + + assertDoesNotMatch("too large", matcher, 2.0); + assertMismatchDescription("<3.0> differed by <1.5> more than delta <0.5>", matcher, 3.0d); + assertDoesNotMatch("number too small", matcher, 0.0); + assertMismatchDescription("<0.1> differed by <0.4> more than delta <0.5>", matcher, 0.1); + } + + public void test_is_self_describing() + { + assertDescription("a numeric value within <0.5> of <1.0>", matcher); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java b/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java index c9b39568..4e6ac965 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java @@ -6,38 +6,45 @@ import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.number.IsNaN.notANumber; -public final class IsNanTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = notANumber(); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesNaN() { - assertMatches(notANumber(), Double.NaN); - } - - @Test public void - doesNotMatchDoubleValue() { - assertDoesNotMatch(notANumber(), 1.25); - } - - @Test public void - doesNotMatchInfinity() { - assertDoesNotMatch(notANumber(), Double.POSITIVE_INFINITY); - } - - @Test public void - describesItself() { - assertDescription("a double value of NaN", notANumber()); - } - - @Test public void - describesAMismatch() { - assertMismatchDescription("was <1.25>", notANumber(), 1.25); - } +public final class IsNanTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = notANumber(); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesNaN() + { + assertMatches(notANumber(), Double.NaN); + } + + @Test public void + doesNotMatchDoubleValue() + { + assertDoesNotMatch(notANumber(), 1.25); + } + + @Test public void + doesNotMatchInfinity() + { + assertDoesNotMatch(notANumber(), Double.POSITIVE_INFINITY); + } + + @Test public void + describesItself() + { + assertDescription("a double value of NaN", notANumber()); + } + + @Test public void + describesAMismatch() + { + assertMismatchDescription("was <1.25>", notANumber(), 1.25); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java b/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java index 5953bd0b..4df7bfa9 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java @@ -9,72 +9,87 @@ import static org.hamcrest.core.IsNot.not; import static org.hamcrest.number.OrderingComparison.*; -public class OrderingComparisonTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return greaterThan(1); - } - - public void testDescription() { - assertDescription("a value greater than <1>", greaterThan(1)); - assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); - assertDescription("a value equal to <1>", comparesEqualTo(1)); - assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); - assertDescription("a value less than <1>", lessThan(1)); - } - - public void testMismatchDescriptions() { - assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); - assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); - assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); - assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); - } - - public void testComparesObjectsForGreaterThan() { - assertThat(2, greaterThan(1)); - assertThat(0, not(greaterThan(1))); - } - - public void testComparesObjectsForLessThan() { - assertThat(2, lessThan(3)); - assertThat(0, lessThan(1)); - } - - - public void testComparesObjectsForEquality() { - assertThat(3, comparesEqualTo(3)); - assertThat("aa", comparesEqualTo("aa")); - } - - public void testAllowsForInclusiveComparisons() { - assertThat("less", 1, lessThanOrEqualTo(1)); - assertThat("greater", 1, greaterThanOrEqualTo(1)); - } - - public void testSupportsDifferentTypesOfComparableObjects() { - assertThat(1.1, greaterThan(1.0)); - assertThat("cc", greaterThan("bb")); - } - - public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() { - assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); - assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); - assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); +public class OrderingComparisonTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return greaterThan(1); + } + + public void testDescription() + { + assertDescription("a value greater than <1>", greaterThan(1)); + assertDescription("a value equal to or greater than <1>", greaterThanOrEqualTo(1)); + assertDescription("a value equal to <1>", comparesEqualTo(1)); + assertDescription("a value less than or equal to <1>", lessThanOrEqualTo(1)); + assertDescription("a value less than <1>", lessThan(1)); + } + + public void testMismatchDescriptions() + { + assertMismatchDescription("<0> was less than <1>", greaterThan(1), 0); + assertMismatchDescription("<1> was equal to <1>", greaterThan(1), 1); + assertMismatchDescription("<1> was greater than <0>", lessThan(0), 1); + assertMismatchDescription("<2> was equal to <2>", lessThan(2), 2); + } + + public void testComparesObjectsForGreaterThan() + { + assertThat(2, greaterThan(1)); + assertThat(0, not(greaterThan(1))); + } + + public void testComparesObjectsForLessThan() + { + assertThat(2, lessThan(3)); + assertThat(0, lessThan(1)); + } + + + public void testComparesObjectsForEquality() + { + assertThat(3, comparesEqualTo(3)); + assertThat("aa", comparesEqualTo("aa")); + } + + public void testAllowsForInclusiveComparisons() + { + assertThat("less", 1, lessThanOrEqualTo(1)); + assertThat("greater", 1, greaterThanOrEqualTo(1)); + } + + public void testSupportsDifferentTypesOfComparableObjects() + { + assertThat(1.1, greaterThan(1.0)); + assertThat("cc", greaterThan("bb")); + } + + public void testComparesBigDecimalsWithDifferentScalesCorrectlyForIssue20() + { + assertThat(new BigDecimal("10.0"), greaterThanOrEqualTo(new BigDecimal("10"))); + assertThat(new BigDecimal(10), greaterThanOrEqualTo(new BigDecimal("10.0"))); + assertThat(new BigDecimal("2"), comparesEqualTo(new BigDecimal("2.000"))); + } + + public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() + { + assertThat(new CustomInt(5), lessThan(new CustomInt(10))); + } + + private static final class CustomInt implements Comparable + { + private final int value; + + public CustomInt(int value) + { + this.value = value; } - - public void testComparesCustomTypesWhoseCompareToReturnsValuesGreaterThatOne() { - assertThat(new CustomInt(5), lessThan(new CustomInt(10))); - } - - private static final class CustomInt implements Comparable { - private final int value; - public CustomInt(int value) { - this.value = value; - } - public int compareTo(CustomInt other) { - return value - other.value; - } + public int compareTo(CustomInt other) + { + return value - other.value; } + } } diff --git a/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java b/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java index 44aa7619..63b63acc 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java @@ -4,53 +4,63 @@ import org.hamcrest.Matcher; @SuppressWarnings("WeakerAccess") -public class HasEqualsValuesTest extends AbstractMatcherTest { - private static final WithPublicFields WITH_PUBLIC_FIELDS = new WithPublicFields('x', 666, "a string"); - private static final HasEqualValues WITH_PUBLIC_FIELDS_MATCHER = new HasEqualValues<>(WITH_PUBLIC_FIELDS); +public class HasEqualsValuesTest extends AbstractMatcherTest +{ + private static final WithPublicFields WITH_PUBLIC_FIELDS = new WithPublicFields('x', 666, "a string"); + private static final HasEqualValues WITH_PUBLIC_FIELDS_MATCHER = new HasEqualValues<>(WITH_PUBLIC_FIELDS); - @Override - protected Matcher createMatcher() { - return WITH_PUBLIC_FIELDS_MATCHER; - } + @Override + protected Matcher createMatcher() + { + return WITH_PUBLIC_FIELDS_MATCHER; + } - public void test_describes_itself() { - assertDescription( - "WithPublicFields has values [i: <666>, s: \"a string\", c: \"x\"]", - WITH_PUBLIC_FIELDS_MATCHER); - } + public void test_describes_itself() + { + assertDescription( + "WithPublicFields has values [i: <666>, s: \"a string\", c: \"x\"]", + WITH_PUBLIC_FIELDS_MATCHER); + } - public void test_matches_equivalent_object() { - assertMatches(WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('x', 666, "a string")); - } + public void test_matches_equivalent_object() + { + assertMatches(WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('x', 666, "a string")); + } - public void test_mismatches_on_first_field_inequality() { - assertMismatchDescription( - "'s' was \"different\"", - WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('x', 666, "different")); - } + public void test_mismatches_on_first_field_inequality() + { + assertMismatchDescription( + "'s' was \"different\"", + WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('x', 666, "different")); + } - public void test_mismatches_on_inherited_field() { - assertMismatchDescription( - "'c' was \"y\"", - WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('y', 666, "a string")); - } + public void test_mismatches_on_inherited_field() + { + assertMismatchDescription( + "'c' was \"y\"", + WITH_PUBLIC_FIELDS_MATCHER, new WithPublicFields('y', 666, "a string")); + } - public static class WithPublicFields extends Parent { - public final int i; - public final String s; + public static class WithPublicFields extends Parent + { + public final int i; + public final String s; - public WithPublicFields(char c, int i, String s) { - super(c); - this.i = i; - this.s = s; - } + public WithPublicFields(char c, int i, String s) + { + super(c); + this.i = i; + this.s = s; } + } - public static class Parent { - public final char c; + public static class Parent + { + public final char c; - public Parent(char c) { - this.c = c; - } + public Parent(char c) + { + this.c = c; } + } } diff --git a/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java b/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java index 122e19b5..d7e501ff 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java @@ -7,49 +7,57 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.object.HasToString.hasToString; -public final class HasToStringTest { - private static final String TO_STRING_RESULT = "toString result"; - private static final Object TEST_OBJECT = new Object() { - @Override - public String toString() { - return TO_STRING_RESULT; - } - }; - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = hasToString(equalTo("irrelevant")); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesWhenUtilisingANestedMatcher() { - final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); - - assertMatches(matcher, TEST_OBJECT); - assertDoesNotMatch(matcher, new Object()); - } - - @Test public void - matchesWhenUsingShortcutForHasToStringEqualTo() { - final Matcher matcher = hasToString(TO_STRING_RESULT); - - assertMatches(matcher, TEST_OBJECT); - assertDoesNotMatch(matcher, new Object()); - } - - @Test public void - describesItself() { - final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); - assertDescription("with toString() \"toString result\"", matcher); - } - - @Test public void - describesAMismatch() { - final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); - String expectedMismatchString = "toString() was \"Cheese\""; - assertMismatchDescription(expectedMismatchString, matcher, "Cheese"); +public final class HasToStringTest +{ + private static final String TO_STRING_RESULT = "toString result"; + private static final Object TEST_OBJECT = new Object() + { + @Override + public String toString() + { + return TO_STRING_RESULT; } + }; + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = hasToString(equalTo("irrelevant")); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesWhenUtilisingANestedMatcher() + { + final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); + + assertMatches(matcher, TEST_OBJECT); + assertDoesNotMatch(matcher, new Object()); + } + + @Test public void + matchesWhenUsingShortcutForHasToStringEqualTo() + { + final Matcher matcher = hasToString(TO_STRING_RESULT); + + assertMatches(matcher, TEST_OBJECT); + assertDoesNotMatch(matcher, new Object()); + } + + @Test public void + describesItself() + { + final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); + assertDescription("with toString() \"toString result\"", matcher); + } + + @Test public void + describesAMismatch() + { + final Matcher matcher = hasToString(equalTo(TO_STRING_RESULT)); + String expectedMismatchString = "toString() was \"Cheese\""; + assertMismatchDescription(expectedMismatchString, matcher, "Cheese"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java b/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java index 62a3637c..1055aa72 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java @@ -6,48 +6,61 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; -public class IsCompatibleTypeTest extends AbstractMatcherTest { - static class BaseClass { - } +public class IsCompatibleTypeTest extends AbstractMatcherTest +{ + static class BaseClass + { + } - private static class ExtendedClass extends BaseClass { - } + private static class ExtendedClass extends BaseClass + { + } - interface BaseInterface { - } + interface BaseInterface + { + } - interface ExtendedInterface extends BaseInterface { - } + interface ExtendedInterface extends BaseInterface + { + } - private static class ClassImplementingBaseInterface implements BaseInterface { - } + private static class ClassImplementingBaseInterface implements BaseInterface + { + } - @Override - protected Matcher createMatcher() { - return typeCompatibleWith(BaseClass.class); - } + @Override + protected Matcher createMatcher() + { + return typeCompatibleWith(BaseClass.class); + } - public void testMatchesSameClass() { - assertThat(BaseClass.class, typeCompatibleWith(BaseClass.class)); - } + public void testMatchesSameClass() + { + assertThat(BaseClass.class, typeCompatibleWith(BaseClass.class)); + } - public void testMatchesSameInterface() { - assertThat(BaseInterface.class, typeCompatibleWith(BaseInterface.class)); - } + public void testMatchesSameInterface() + { + assertThat(BaseInterface.class, typeCompatibleWith(BaseInterface.class)); + } - public void testMatchesExtendedClass() { - assertThat(ExtendedClass.class, typeCompatibleWith(BaseClass.class)); - } + public void testMatchesExtendedClass() + { + assertThat(ExtendedClass.class, typeCompatibleWith(BaseClass.class)); + } - public void testMatchesClassImplementingInterface() { - assertThat(ClassImplementingBaseInterface.class, typeCompatibleWith(BaseInterface.class)); - } + public void testMatchesClassImplementingInterface() + { + assertThat(ClassImplementingBaseInterface.class, typeCompatibleWith(BaseInterface.class)); + } - public void testMatchesExtendedInterface() { - assertThat(ExtendedInterface.class, typeCompatibleWith(BaseInterface.class)); - } + public void testMatchesExtendedInterface() + { + assertThat(ExtendedInterface.class, typeCompatibleWith(BaseInterface.class)); + } - public void testHasReadableDescription() { - assertDescription("type < java.lang.Runnable", typeCompatibleWith(Runnable.class)); - } + public void testHasReadableDescription() + { + assertDescription("type < java.lang.Runnable", typeCompatibleWith(Runnable.class)); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java b/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java index b3c4a3a5..05edf669 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java @@ -9,44 +9,50 @@ import static org.hamcrest.object.IsEventFrom.eventFrom; -public class IsEventFromTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return eventFrom(null); - } - - public void testEvaluatesToTrueIfArgumentIsAnEventObjectFiredByASpecifiedSource() { - Object o = "Source"; - EventObject ev = new EventObject(o); - EventObject ev2 = new EventObject("source 2"); - - Matcher isEventMatcher = eventFrom(o); - - assertThat(ev, isEventMatcher); - assertMismatchDescription("source was \"source 2\"", isEventMatcher, ev2); - } - - private static class DerivedEvent extends EventObject { - private static final long serialVersionUID = 1L; - - public DerivedEvent(Object source) { - super(source); - } - } - - public void testCanTestForSpecificEventClasses() { - Object o = new Object(); - DerivedEvent goodEv = new DerivedEvent(o); - DerivedEvent wrongSource = new DerivedEvent("wrong source"); - EventObject wrongType = new EventObject(o); - EventObject wrongSourceAndType = new EventObject(new Object()); - - Matcher isEventMatcher = IsEventFrom.eventFrom(DerivedEvent.class, o); - - assertThat(goodEv, isEventMatcher); - assertMismatchDescription("source was \"wrong source\"", isEventMatcher, wrongSource); - assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongType); - assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongSourceAndType); +public class IsEventFromTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return eventFrom(null); + } + + public void testEvaluatesToTrueIfArgumentIsAnEventObjectFiredByASpecifiedSource() + { + Object o = "Source"; + EventObject ev = new EventObject(o); + EventObject ev2 = new EventObject("source 2"); + + Matcher isEventMatcher = eventFrom(o); + + assertThat(ev, isEventMatcher); + assertMismatchDescription("source was \"source 2\"", isEventMatcher, ev2); + } + + private static class DerivedEvent extends EventObject + { + private static final long serialVersionUID = 1L; + + public DerivedEvent(Object source) + { + super(source); } + } + + public void testCanTestForSpecificEventClasses() + { + Object o = new Object(); + DerivedEvent goodEv = new DerivedEvent(o); + DerivedEvent wrongSource = new DerivedEvent("wrong source"); + EventObject wrongType = new EventObject(o); + EventObject wrongSourceAndType = new EventObject(new Object()); + + Matcher isEventMatcher = IsEventFrom.eventFrom(DerivedEvent.class, o); + + assertThat(goodEv, isEventMatcher); + assertMismatchDescription("source was \"wrong source\"", isEventMatcher, wrongSource); + assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongType); + assertMismatchDescription("item type was java.util.EventObject", isEventMatcher, wrongSourceAndType); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java b/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java index 3e2d9114..15c5f11e 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java @@ -9,51 +9,60 @@ import static org.hamcrest.AbstractMatcherTest.*; import static org.junit.Assert.assertThat; -public class MatchesPatternTest { - @Test - public void copesWithNullsAndUnknownTypes() { - Matcher matcher = new MatchesPattern(Pattern.compile(".")); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test - public void matchesExactString() { - assertThat("a", new MatchesPattern(Pattern.compile("a"))); - } - - @Test - public void doesNotMatchADifferentString() { - assertDoesNotMatch("A different string does not match", new MatchesPattern(Pattern.compile("a")), "b"); - } - - @Test - public void doesNotMatchSubstring() { - assertDoesNotMatch("A substring does not match", new MatchesPattern(Pattern.compile("a")), "ab"); - } - - @Test - public void hasAReadableDescription() { - Matcher m = new MatchesPattern(Pattern.compile("a[bc](d|e)")); - assertDescription("a string matching the pattern 'a[bc](d|e)'", m ); - } - - @Test - public void describesAMismatch() { - final Matcher matcher = new MatchesPattern(Pattern.compile("a")); - assertMismatchDescription("was \"Cheese\"", matcher, "Cheese"); - } - - @Test - public void factoryMethodAllowsCreationWithPattern() { - Matcher m = MatchesPattern.matchesPattern(Pattern.compile("a[bc](d|e)")); - assertDescription("a string matching the pattern 'a[bc](d|e)'", m ); - } - - @Test - public void factoryMethodAllowsCreationWithString() { - Matcher m = MatchesPattern.matchesPattern("a[bc](d|e)"); - assertDescription("a string matching the pattern 'a[bc](d|e)'", m ); - } +public class MatchesPatternTest +{ + @Test + public void copesWithNullsAndUnknownTypes() + { + Matcher matcher = new MatchesPattern(Pattern.compile(".")); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test + public void matchesExactString() + { + assertThat("a", new MatchesPattern(Pattern.compile("a"))); + } + + @Test + public void doesNotMatchADifferentString() + { + assertDoesNotMatch("A different string does not match", new MatchesPattern(Pattern.compile("a")), "b"); + } + + @Test + public void doesNotMatchSubstring() + { + assertDoesNotMatch("A substring does not match", new MatchesPattern(Pattern.compile("a")), "ab"); + } + + @Test + public void hasAReadableDescription() + { + Matcher m = new MatchesPattern(Pattern.compile("a[bc](d|e)")); + assertDescription("a string matching the pattern 'a[bc](d|e)'", m); + } + + @Test + public void describesAMismatch() + { + final Matcher matcher = new MatchesPattern(Pattern.compile("a")); + assertMismatchDescription("was \"Cheese\"", matcher, "Cheese"); + } + + @Test + public void factoryMethodAllowsCreationWithPattern() + { + Matcher m = MatchesPattern.matchesPattern(Pattern.compile("a[bc](d|e)")); + assertDescription("a string matching the pattern 'a[bc](d|e)'", m); + } + + @Test + public void factoryMethodAllowsCreationWithString() + { + Matcher m = MatchesPattern.matchesPattern("a[bc](d|e)"); + assertDescription("a string matching the pattern 'a[bc](d|e)'", m); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java b/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java index 76629465..b802010f 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java @@ -10,29 +10,33 @@ * @author Marco Leichsenring * @author Steve Freeman */ -public class CharSequenceLengthTest extends AbstractMatcherTest { - - @Override - protected Matcher createMatcher() { - return hasLength(4); - } - - public void test_matchesExactLengthOf_CharSequence() { - final Matcher matcher = hasLength(4); - assertMatches(matcher, "aaaa"); - assertMatches(matcher, "a b "); - - assertMismatchDescription("length was <6>", matcher, "aaaaaa"); - } - - - public void test_matchesRelativeLengthOf_CharSequence() { - final Matcher matcher = hasLength(lessThan(4)); - assertMatches(matcher, "aaa"); - assertMatches(matcher, "a b"); - - assertMismatchDescription("length <4> was equal to <4>", matcher, "aaaa"); - assertMismatchDescription("length <5> was greater than <4>", matcher, "aaaaa"); - } +public class CharSequenceLengthTest extends AbstractMatcherTest +{ + + @Override + protected Matcher createMatcher() + { + return hasLength(4); + } + + public void test_matchesExactLengthOf_CharSequence() + { + final Matcher matcher = hasLength(4); + assertMatches(matcher, "aaaa"); + assertMatches(matcher, "a b "); + + assertMismatchDescription("length was <6>", matcher, "aaaaaa"); + } + + + public void test_matchesRelativeLengthOf_CharSequence() + { + final Matcher matcher = hasLength(lessThan(4)); + assertMatches(matcher, "aaa"); + assertMatches(matcher, "a b"); + + assertMismatchDescription("length <4> was equal to <4>", matcher, "aaaa"); + assertMismatchDescription("length <5> was greater than <4>", matcher, "aaaaa"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java b/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java index c5f35f1c..75d6b4c8 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java @@ -7,49 +7,57 @@ import static org.hamcrest.text.IsBlankString.blankOrNullString; import static org.hamcrest.text.IsBlankString.blankString; -public final class IsBlankStringTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = blankString(); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesEmptyString() { - assertMatches(blankOrNullString(), ""); - assertMatches(blankString(), ""); - } - - @Test public void - matchesNullAppropriately() { - assertMatches(blankOrNullString(), null); - assertDoesNotMatch(blankString(), null); - } - - @Test public void - matchesBlankStringAppropriately() { - assertMatches(blankString(), " \t"); - assertMatches(blankOrNullString(), " \t"); - } - - @Test public void - doesNotMatchFilledString() { - assertDoesNotMatch(blankString(), "a"); - assertDoesNotMatch(blankOrNullString(), "a"); - } - - @Test public void - describesItself() { - assertDescription("a blank string", blankString()); - assertDescription("(null or a blank string)", blankOrNullString()); - } - - @Test public void - describesAMismatch() { - assertMismatchDescription("was \"a\"", blankString(), "a"); - assertMismatchDescription("was \"a\"", blankOrNullString(), "a"); - } +public final class IsBlankStringTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = blankString(); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesEmptyString() + { + assertMatches(blankOrNullString(), ""); + assertMatches(blankString(), ""); + } + + @Test public void + matchesNullAppropriately() + { + assertMatches(blankOrNullString(), null); + assertDoesNotMatch(blankString(), null); + } + + @Test public void + matchesBlankStringAppropriately() + { + assertMatches(blankString(), " \t"); + assertMatches(blankOrNullString(), " \t"); + } + + @Test public void + doesNotMatchFilledString() + { + assertDoesNotMatch(blankString(), "a"); + assertDoesNotMatch(blankOrNullString(), "a"); + } + + @Test public void + describesItself() + { + assertDescription("a blank string", blankString()); + assertDescription("(null or a blank string)", blankOrNullString()); + } + + @Test public void + describesAMismatch() + { + assertMismatchDescription("was \"a\"", blankString(), "a"); + assertMismatchDescription("was \"a\"", blankOrNullString(), "a"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java b/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java index 62e30535..b53eb301 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java @@ -7,49 +7,57 @@ import static org.hamcrest.text.IsEmptyString.emptyOrNullString; import static org.hamcrest.text.IsEmptyString.emptyString; -public final class IsEmptyStringTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = emptyString(); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - matchesEmptyString() { - assertMatches(emptyOrNullString(), ""); - assertMatches(emptyString(), ""); - } - - @Test public void - matchesNullAppropriately() { - assertMatches(emptyOrNullString(), null); - assertDoesNotMatch(emptyString(), null); - } - - @Test public void - matchesBlankStringAppropriately() { - assertDoesNotMatch(emptyString(), " "); - assertDoesNotMatch(emptyOrNullString(), " "); - } - - @Test public void - doesNotMatchFilledString() { - assertDoesNotMatch(emptyString(), "a"); - assertDoesNotMatch(emptyOrNullString(), "a"); - } - - @Test public void - describesItself() { - assertDescription("an empty string", emptyString()); - assertDescription("(null or an empty string)", emptyOrNullString()); - } - - @Test public void - describesAMismatch() { - assertMismatchDescription("was \"a\"", emptyString(), "a"); - assertMismatchDescription("was \"a\"", emptyOrNullString(), "a"); - } +public final class IsEmptyStringTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = emptyString(); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + matchesEmptyString() + { + assertMatches(emptyOrNullString(), ""); + assertMatches(emptyString(), ""); + } + + @Test public void + matchesNullAppropriately() + { + assertMatches(emptyOrNullString(), null); + assertDoesNotMatch(emptyString(), null); + } + + @Test public void + matchesBlankStringAppropriately() + { + assertDoesNotMatch(emptyString(), " "); + assertDoesNotMatch(emptyOrNullString(), " "); + } + + @Test public void + doesNotMatchFilledString() + { + assertDoesNotMatch(emptyString(), "a"); + assertDoesNotMatch(emptyOrNullString(), "a"); + } + + @Test public void + describesItself() + { + assertDescription("an empty string", emptyString()); + assertDescription("(null or an empty string)", emptyOrNullString()); + } + + @Test public void + describesAMismatch() + { + assertMismatchDescription("was \"a\"", emptyString(), "a"); + assertMismatchDescription("was \"a\"", emptyOrNullString(), "a"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java b/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java index 2f09c136..3bbe18f1 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java @@ -5,40 +5,48 @@ import static org.hamcrest.text.IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace; -public class IsEqualCompressingWhiteSpaceTest extends AbstractMatcherTest { - - private final Matcher matcher = equalToCompressingWhiteSpace(" Hello World how\n are we? "); - - @Override - protected Matcher createMatcher() { - return matcher; - } - - public void testPassesIfWordsAreSameButWhitespaceDiffers() { - assertMatches(matcher, "Hello World how are we?"); - assertMatches(matcher, " Hello World how are \n\n\twe?"); - } - - public void testFailsIfTextOtherThanWhitespaceDiffers() { - assertDoesNotMatch(matcher, "Hello PLANET how are we?"); - assertDoesNotMatch(matcher, "Hello World how are we"); - } - - public void testFailsIfWhitespaceIsAddedOrRemovedInMidWord() { - assertDoesNotMatch(matcher, "HelloWorld how are we?"); - assertDoesNotMatch(matcher, "Hello Wo rld how are we?"); - } - - public void test_has_a_readable_mismatch() { - assertMismatchDescription("was \"Hello World how are we \"", matcher, "Hello World how are we "); - } - - public void testFailsIfMatchingAgainstNull() { - assertDoesNotMatch(matcher, null); - } - - public void testHasAReadableDescription() { - assertDescription("a string equal to \" Hello World how\\n are we? \" compressing white space", - matcher); - } +public class IsEqualCompressingWhiteSpaceTest extends AbstractMatcherTest +{ + + private final Matcher matcher = equalToCompressingWhiteSpace(" Hello World how\n are we? "); + + @Override + protected Matcher createMatcher() + { + return matcher; + } + + public void testPassesIfWordsAreSameButWhitespaceDiffers() + { + assertMatches(matcher, "Hello World how are we?"); + assertMatches(matcher, " Hello World how are \n\n\twe?"); + } + + public void testFailsIfTextOtherThanWhitespaceDiffers() + { + assertDoesNotMatch(matcher, "Hello PLANET how are we?"); + assertDoesNotMatch(matcher, "Hello World how are we"); + } + + public void testFailsIfWhitespaceIsAddedOrRemovedInMidWord() + { + assertDoesNotMatch(matcher, "HelloWorld how are we?"); + assertDoesNotMatch(matcher, "Hello Wo rld how are we?"); + } + + public void test_has_a_readable_mismatch() + { + assertMismatchDescription("was \"Hello World how are we \"", matcher, "Hello World how are we "); + } + + public void testFailsIfMatchingAgainstNull() + { + assertDoesNotMatch(matcher, null); + } + + public void testHasAReadableDescription() + { + assertDescription("a string equal to \" Hello World how\\n are we? \" compressing white space", + matcher); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java b/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java index b2b73917..ce45320e 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java @@ -6,57 +6,65 @@ import static org.hamcrest.AbstractMatcherTest.*; import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; -public final class IsEqualIgnoringCaseTest { - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = equalToIgnoringCase("irrelevant"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); - } - - @Test public void - ignoresCaseOfCharsInString() { - final Matcher matcher = equalToIgnoringCase("heLLo"); - - assertMatches(matcher, "HELLO"); - assertMatches(matcher, "hello"); - assertMatches(matcher, "HelLo"); - assertDoesNotMatch(matcher, "bye"); - } - - @Test public void - mismatchesIfAdditionalWhitespaceIsPresent() { - final Matcher matcher = equalToIgnoringCase("heLLo"); - - assertDoesNotMatch(matcher, "hello "); - assertDoesNotMatch(matcher, " hello"); - } - - @Test public void - mismatchesNull() { - final Matcher matcher = equalToIgnoringCase("heLLo"); - - assertDoesNotMatch(matcher, null); - } - - @Test(expected=IllegalArgumentException.class) public void - canOnlyBeConstructedAboutANonNullString() { - equalToIgnoringCase(null); - } - - - @Test public void - describesItself() { - final Matcher matcher = equalToIgnoringCase("heLLo"); - assertDescription("a string equal to \"heLLo\" ignoring case", matcher); - } - - @Test public void - describesAMismatch() { - final Matcher matcher = equalToIgnoringCase("heLLo"); - String expectedMismatchString = "was \"Cheese\""; - assertMismatchDescription(expectedMismatchString, matcher, "Cheese"); - } +public final class IsEqualIgnoringCaseTest +{ + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = equalToIgnoringCase("irrelevant"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + ignoresCaseOfCharsInString() + { + final Matcher matcher = equalToIgnoringCase("heLLo"); + + assertMatches(matcher, "HELLO"); + assertMatches(matcher, "hello"); + assertMatches(matcher, "HelLo"); + assertDoesNotMatch(matcher, "bye"); + } + + @Test public void + mismatchesIfAdditionalWhitespaceIsPresent() + { + final Matcher matcher = equalToIgnoringCase("heLLo"); + + assertDoesNotMatch(matcher, "hello "); + assertDoesNotMatch(matcher, " hello"); + } + + @Test public void + mismatchesNull() + { + final Matcher matcher = equalToIgnoringCase("heLLo"); + + assertDoesNotMatch(matcher, null); + } + + @Test(expected = IllegalArgumentException.class) public void + canOnlyBeConstructedAboutANonNullString() + { + equalToIgnoringCase(null); + } + + + @Test public void + describesItself() + { + final Matcher matcher = equalToIgnoringCase("heLLo"); + assertDescription("a string equal to \"heLLo\" ignoring case", matcher); + } + + @Test public void + describesAMismatch() + { + final Matcher matcher = equalToIgnoringCase("heLLo"); + String expectedMismatchString = "was \"Cheese\""; + assertMismatchDescription(expectedMismatchString, matcher, "Cheese"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java b/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java index 52390a82..1c431ab8 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java @@ -7,27 +7,31 @@ import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder; -public class StringContainsInOrderTest extends AbstractMatcherTest { - final StringContainsInOrder matcher = new StringContainsInOrder(asList("a", "b", "c", "c")); - - @Override - protected Matcher createMatcher() { - return matcher; - } - - public void testMatchesOnlyIfStringContainsGivenSubstringsInTheSameOrder() { - assertMatches("substrings in order", matcher, "abcc"); - assertMatches("substrings separated", matcher, "1a2b3c4c5"); - - assertDoesNotMatch("can detect repeated strings for matching", stringContainsInOrder("abc", "abc"), "---abc---"); - assertDoesNotMatch("substrings in order missing a repeated pattern", matcher, "abc"); - assertDoesNotMatch("substrings out of order", matcher, "cab"); - assertDoesNotMatch("no substrings in string", matcher, "xyz"); - assertDoesNotMatch("substring missing", matcher, "ac"); - assertDoesNotMatch("empty string", matcher, ""); - } - - public void testHasAReadableDescription() { - assertDescription("a string containing \"a\", \"b\", \"c\", \"c\" in order", matcher); - } +public class StringContainsInOrderTest extends AbstractMatcherTest +{ + final StringContainsInOrder matcher = new StringContainsInOrder(asList("a", "b", "c", "c")); + + @Override + protected Matcher createMatcher() + { + return matcher; + } + + public void testMatchesOnlyIfStringContainsGivenSubstringsInTheSameOrder() + { + assertMatches("substrings in order", matcher, "abcc"); + assertMatches("substrings separated", matcher, "1a2b3c4c5"); + + assertDoesNotMatch("can detect repeated strings for matching", stringContainsInOrder("abc", "abc"), "---abc---"); + assertDoesNotMatch("substrings in order missing a repeated pattern", matcher, "abc"); + assertDoesNotMatch("substrings out of order", matcher, "cab"); + assertDoesNotMatch("no substrings in string", matcher, "xyz"); + assertDoesNotMatch("substring missing", matcher, "ac"); + assertDoesNotMatch("empty string", matcher, ""); + } + + public void testHasAReadableDescription() + { + assertDescription("a string containing \"a\", \"b\", \"c\", \"c\" in order", matcher); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java b/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java index a66689dc..48484cef 100644 --- a/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java +++ b/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java @@ -23,125 +23,148 @@ * @author Joe Walnes * @author Tom Denley */ -public final class HasXPathTest { - - private final Document xml = parse("" - + "\n" - + " Edam\n" - + " Cheddar\n" - + " Caravane\n" - + " \n" - + " " - + "\n" - ); - - private final NamespaceContext ns = new NamespaceContext() { - @Override - public String getNamespaceURI(String prefix) { - return ("cheese".equals(prefix) ? "http://cheese.com" : null); - } - - @Override - public String getPrefix(String namespaceURI) { - return ("http://cheese.com".equals(namespaceURI) ? "cheese" : null); - } - - @Override - public Iterator getPrefixes(String namespaceURI) { - HashSet prefixes = new HashSet(); - String prefix = getPrefix(namespaceURI); - if (prefix != null) { - prefixes.add(prefix); - } - return prefixes.iterator(); - } - }; - - @Test public void - copesWithNullsAndUnknownTypes() { - Matcher matcher = hasXPath("//irrelevant"); - - assertNullSafe(matcher); - assertUnknownTypeSafe(matcher); +public final class HasXPathTest +{ + + private final Document xml = parse("" + + "\n" + + " Edam\n" + + " Cheddar\n" + + " Caravane\n" + + " \n" + + " " + + "\n" + ); + + private final NamespaceContext ns = new NamespaceContext() + { + @Override + public String getNamespaceURI(String prefix) + { + return ("cheese".equals(prefix) ? "http://cheese.com" : null); } - @Test public void - appliesMatcherToXPathInDocument() { - assertMatches(hasXPath("/root/something[2]/cheese", equalTo("Cheddar")), xml); - assertMatches(hasXPath("//something[1]/cheese", containsString("dam")), xml); - assertMatches(hasXPath("//something[2]/cheese", not(containsString("dam"))), xml); - assertMatches(hasXPath("/root/@type", equalTo("food")), xml); - assertMatches(hasXPath("//something[@id='b']/cheese", equalTo("Cheddar")), xml); - assertMatches(hasXPath("//something[@id='b']/cheese"), xml); + @Override + public String getPrefix(String namespaceURI) + { + return ("http://cheese.com".equals(namespaceURI) ? "cheese" : null); } - @Test public void - matchesEmptyElement() { - assertMatches(hasXPath("//emptySomething"), xml); + @Override + public Iterator getPrefixes(String namespaceURI) + { + HashSet prefixes = new HashSet(); + String prefix = getPrefix(namespaceURI); + if (prefix != null) + { + prefixes.add(prefix); + } + return prefixes.iterator(); } - - @Test public void - matchesEmptyElementInNamespace() { - assertMatches(hasXPath("//cheese:emptySomething", ns), xml); - } - - @Test public void - failsIfNodeIsMissing() { - assertDoesNotMatch(hasXPath("/root/something[3]/cheese", ns, equalTo("Cheddar")), xml); - assertDoesNotMatch(hasXPath("//something[@id='c']/cheese", ns), xml); - } - - @Test public void - failsIfNodeIsMissingInNamespace() { - assertDoesNotMatch(hasXPath("//cheese:foreignSomething", equalTo("Badger")), xml); - assertDoesNotMatch(hasXPath("//cheese:foreignSomething"), xml); - } - - @Test public void - matchesWithNamespace() { - assertMatches(hasXPath("//cheese:foreignSomething", ns), xml); - assertMatches(hasXPath("//cheese:foreignSomething/@milk", ns, equalTo("camel")), xml); - assertMatches(hasXPath("//cheese:foreignSomething/text()", ns, equalTo("Caravane")), xml); + }; + + @Test public void + copesWithNullsAndUnknownTypes() + { + Matcher matcher = hasXPath("//irrelevant"); + + assertNullSafe(matcher); + assertUnknownTypeSafe(matcher); + } + + @Test public void + appliesMatcherToXPathInDocument() + { + assertMatches(hasXPath("/root/something[2]/cheese", equalTo("Cheddar")), xml); + assertMatches(hasXPath("//something[1]/cheese", containsString("dam")), xml); + assertMatches(hasXPath("//something[2]/cheese", not(containsString("dam"))), xml); + assertMatches(hasXPath("/root/@type", equalTo("food")), xml); + assertMatches(hasXPath("//something[@id='b']/cheese", equalTo("Cheddar")), xml); + assertMatches(hasXPath("//something[@id='b']/cheese"), xml); + } + + @Test public void + matchesEmptyElement() + { + assertMatches(hasXPath("//emptySomething"), xml); + } + + @Test public void + matchesEmptyElementInNamespace() + { + assertMatches(hasXPath("//cheese:emptySomething", ns), xml); + } + + @Test public void + failsIfNodeIsMissing() + { + assertDoesNotMatch(hasXPath("/root/something[3]/cheese", ns, equalTo("Cheddar")), xml); + assertDoesNotMatch(hasXPath("//something[@id='c']/cheese", ns), xml); + } + + @Test public void + failsIfNodeIsMissingInNamespace() + { + assertDoesNotMatch(hasXPath("//cheese:foreignSomething", equalTo("Badger")), xml); + assertDoesNotMatch(hasXPath("//cheese:foreignSomething"), xml); + } + + @Test public void + matchesWithNamespace() + { + assertMatches(hasXPath("//cheese:foreignSomething", ns), xml); + assertMatches(hasXPath("//cheese:foreignSomething/@milk", ns, equalTo("camel")), xml); + assertMatches(hasXPath("//cheese:foreignSomething/text()", ns, equalTo("Caravane")), xml); + } + + @Test public void + throwsIllegalArgumentExceptionIfGivenIllegalExpression() + { + try + { + hasXPath("\\g:dfgd::DSgf/root/something[2]/cheese", equalTo("blah")); + fail("Expected exception"); } - - @Test public void - throwsIllegalArgumentExceptionIfGivenIllegalExpression() { - try { - hasXPath("\\g:dfgd::DSgf/root/something[2]/cheese", equalTo("blah")); - fail("Expected exception"); - } catch (IllegalArgumentException expectedException) { - // expected exception - } - } - - @Test public void - describesItself() { - assertDescription("an XML document with XPath /some/path \"Cheddar\"", - hasXPath("/some/path", equalTo("Cheddar"))); - - assertDescription("an XML document with XPath /some/path", - hasXPath("/some/path")); + catch (IllegalArgumentException expectedException) + { + // expected exception } - - @Test public void - describesMissingNodeMismatch() { - assertMismatchDescription("xpath returned no results.", hasXPath("//honky"), xml); + } + + @Test public void + describesItself() + { + assertDescription("an XML document with XPath /some/path \"Cheddar\"", + hasXPath("/some/path", equalTo("Cheddar"))); + + assertDescription("an XML document with XPath /some/path", + hasXPath("/some/path")); + } + + @Test public void + describesMissingNodeMismatch() + { + assertMismatchDescription("xpath returned no results.", hasXPath("//honky"), xml); + } + + @Test public void + describesIncorrectNodeValueMismatch() + { + assertMismatchDescription("was \"Edam\"", hasXPath("//something[1]/cheese", equalTo("parmesan")), xml); + } + + private static Document parse(String xml) + { + try + { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + return documentBuilder.parse(new ByteArrayInputStream(xml.getBytes())); } - - @Test public void - describesIncorrectNodeValueMismatch() { - assertMismatchDescription("was \"Edam\"", hasXPath("//something[1]/cheese", equalTo("parmesan")), xml); - } - - private static Document parse(String xml) { - try { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - return documentBuilder.parse(new ByteArrayInputStream(xml.getBytes())); - } - catch (Exception e) { - throw new IllegalStateException(e); - } + catch (Exception e) + { + throw new IllegalStateException(e); } + } }