From 2ab54c79ed227d5eaa0d66f5fb84cb0b29b07c97 Mon Sep 17 00:00:00 2001 From: JJ Brown Date: Sun, 19 Apr 2020 22:11:15 -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 + .../java/org/hamcrest/EasyMock2Matchers.java | 8 +- .../java/org/hamcrest/JMock1Matchers.java | 6 +- .../org/hamcrest/JavaLangMatcherAssert.java | 11 +- .../integration/EasyMock2Adapter.java | 46 +-- .../hamcrest/integration/JMock1Adapter.java | 42 +-- .../java/org/hamcrest/BaseDescription.java | 249 +++++++------- .../main/java/org/hamcrest/BaseMatcher.java | 56 ++-- .../src/main/java/org/hamcrest/Condition.java | 96 +++--- .../main/java/org/hamcrest/CoreMatchers.java | 48 +-- .../main/java/org/hamcrest/CustomMatcher.java | 22 +- .../org/hamcrest/CustomTypeSafeMatcher.java | 20 +- .../main/java/org/hamcrest/Description.java | 122 +++---- .../java/org/hamcrest/DiagnosingMatcher.java | 18 +- .../java/org/hamcrest/FeatureMatcher.java | 16 +- .../src/main/java/org/hamcrest/Matcher.java | 70 ++-- .../main/java/org/hamcrest/MatcherAssert.java | 44 +-- .../src/main/java/org/hamcrest/Matchers.java | 230 ++++++------- .../java/org/hamcrest/SelfDescribing.java | 14 +- .../java/org/hamcrest/StringDescription.java | 86 ++--- .../hamcrest/TypeSafeDiagnosingMatcher.java | 96 +++--- .../java/org/hamcrest/TypeSafeMatcher.java | 138 ++++---- .../java/org/hamcrest/beans/HasProperty.java | 68 ++-- .../hamcrest/beans/HasPropertyWithValue.java | 218 ++++++------- .../java/org/hamcrest/beans/PropertyUtil.java | 60 ++-- .../hamcrest/beans/SamePropertyValuesAs.java | 238 +++++++------- .../collection/ArrayAsIterableMatcher.java | 13 +- .../hamcrest/collection/ArrayMatching.java | 15 +- .../hamcrest/collection/HasItemInArray.java | 48 +-- .../java/org/hamcrest/collection/IsArray.java | 146 ++++----- .../IsArrayContainingInAnyOrder.java | 156 ++++----- .../collection/IsArrayContainingInOrder.java | 122 +++---- .../hamcrest/collection/IsArrayWithSize.java | 74 ++--- .../collection/IsCollectionWithSize.java | 62 ++-- .../collection/IsEmptyCollection.java | 74 ++--- .../hamcrest/collection/IsEmptyIterable.java | 63 ++-- .../java/org/hamcrest/collection/IsIn.java | 206 ++++++------ .../IsIterableContainingInAnyOrder.java | 234 +++++++------- .../IsIterableContainingInOrder.java | 234 +++++++------- .../IsIterableContainingInRelativeOrder.java | 180 +++++------ .../collection/IsIterableWithSize.java | 72 ++--- .../hamcrest/collection/IsMapContaining.java | 180 +++++------ .../hamcrest/collection/IsMapWithSize.java | 84 ++--- .../comparator/ComparatorMatcherBuilder.java | 306 +++++++++--------- .../main/java/org/hamcrest/core/AllOf.java | 90 +++--- .../main/java/org/hamcrest/core/AnyOf.java | 74 ++--- .../org/hamcrest/core/CombinableMatcher.java | 12 +- .../java/org/hamcrest/core/DescribedAs.java | 88 ++--- .../main/java/org/hamcrest/core/Every.java | 58 ++-- .../src/main/java/org/hamcrest/core/Is.java | 102 +++--- .../java/org/hamcrest/core/IsAnything.java | 68 ++-- .../hamcrest/core/IsCollectionContaining.java | 138 ++++---- .../main/java/org/hamcrest/core/IsEqual.java | 138 ++++---- .../java/org/hamcrest/core/IsInstanceOf.java | 138 ++++---- .../hamcrest/core/IsIterableContaining.java | 196 +++++------ .../main/java/org/hamcrest/core/IsNot.java | 80 ++--- .../main/java/org/hamcrest/core/IsNull.java | 102 +++--- .../main/java/org/hamcrest/core/IsSame.java | 70 ++-- .../hamcrest/core/ShortcutCombination.java | 44 +-- .../org/hamcrest/core/StringContains.java | 60 ++-- .../org/hamcrest/core/StringEndsWith.java | 56 ++-- .../org/hamcrest/core/StringStartsWith.java | 58 ++-- .../org/hamcrest/core/SubstringMatcher.java | 74 +++-- .../org/hamcrest/internal/ArrayIterator.java | 44 +-- .../org/hamcrest/internal/NullSafety.java | 14 +- .../internal/ReflectiveTypeFinder.java | 40 +-- .../internal/SelfDescribingValue.java | 18 +- .../internal/SelfDescribingValueIterator.java | 36 +-- .../java/org/hamcrest/io/FileMatchers.java | 187 ++++++----- .../hamcrest/number/BigDecimalCloseTo.java | 30 +- .../java/org/hamcrest/number/IsCloseTo.java | 88 ++--- .../main/java/org/hamcrest/number/IsNaN.java | 51 +-- .../hamcrest/number/OrderingComparison.java | 132 ++++---- .../org/hamcrest/object/HasEqualValues.java | 111 +++---- .../java/org/hamcrest/object/HasToString.java | 56 ++-- .../org/hamcrest/object/IsCompatibleType.java | 62 ++-- .../java/org/hamcrest/object/IsEventFrom.java | 96 +++--- .../org/hamcrest/text/CharSequenceLength.java | 82 ++--- .../java/org/hamcrest/text/IsBlankString.java | 77 ++--- .../java/org/hamcrest/text/IsEmptyString.java | 111 +++---- .../text/IsEqualCompressingWhiteSpace.java | 96 +++--- .../hamcrest/text/IsEqualIgnoringCase.java | 72 ++--- .../org/hamcrest/text/MatchesPattern.java | 62 ++-- .../hamcrest/text/StringContainsInOrder.java | 104 +++--- .../main/java/org/hamcrest/xml/HasXPath.java | 242 +++++++------- .../org/hamcrest/AbstractMatcherTest.java | 39 ++- .../org/hamcrest/BaseDescriptionTest.java | 221 +++++++------ .../java/org/hamcrest/BaseMatcherTest.java | 30 +- .../java/org/hamcrest/CustomMatcherTest.java | 21 +- .../hamcrest/CustomTypeSafeMatcherTest.java | 62 ++-- .../java/org/hamcrest/FeatureMatcherTest.java | 99 +++--- .../java/org/hamcrest/MatcherAssertTest.java | 151 ++++----- .../org/hamcrest/NullDescriptionTest.java | 13 +- .../TypeSafeDiagnosingMatcherTest.java | 121 ++++--- .../org/hamcrest/TypeSafeMatcherTest.java | 54 ++-- .../org/hamcrest/beans/HasPropertyTest.java | 65 ++-- .../beans/HasPropertyWithValueTest.java | 52 +-- .../beans/SamePropertyValuesAsTest.java | 47 +-- .../ArrayMatchingInAnyOrderTest.java | 64 ++-- .../collection/ArrayMatchingInOrderTest.java | 68 ++-- .../collection/HasItemInArrayTest.java | 56 ++-- .../IsArrayContainingInAnyOrderTest.java | 64 ++-- .../IsArrayContainingInOrderTest.java | 60 ++-- .../org/hamcrest/collection/IsArrayTest.java | 99 +++--- .../collection/IsArrayWithSizeTest.java | 48 +-- .../collection/IsCollectionWithSizeTest.java | 102 +++--- .../collection/IsEmptyCollectionTest.java | 61 ++-- .../collection/IsEmptyIterableTest.java | 47 +-- .../org/hamcrest/collection/IsInTest.java | 66 ++-- .../IsIterableContainingInAnyOrderTest.java | 76 ++--- .../IsIterableContainingInOrderTest.java | 103 +++--- ...IterableContainingInRelativeOrderTest.java | 129 ++++---- .../collection/IsIterableWithSizeTest.java | 48 +-- .../collection/IsMapContainingKeyTest.java | 104 +++--- .../collection/IsMapContainingTest.java | 66 ++-- .../collection/IsMapContainingValueTest.java | 62 ++-- .../collection/IsMapWithSizeTest.java | 114 +++---- .../ComparatorMatcherBuilderTest.java | 212 ++++++------ .../comparator/ComparatorMatcherTest.java | 138 ++++---- .../java/org/hamcrest/core/AllOfTest.java | 105 +++--- .../java/org/hamcrest/core/AnyOfTest.java | 100 +++--- .../org/hamcrest/core/CombinableTest.java | 104 +++--- .../org/hamcrest/core/DescribedAsTest.java | 77 ++--- .../java/org/hamcrest/core/EveryTest.java | 61 ++-- .../org/hamcrest/core/IsAnythingTest.java | 60 ++-- .../core/IsCollectionContainingTest.java | 166 +++++----- .../java/org/hamcrest/core/IsEqualTest.java | 300 ++++++++--------- .../org/hamcrest/core/IsInstanceOfTest.java | 99 +++--- .../core/IsIterableContainingTest.java | 182 ++++++----- .../java/org/hamcrest/core/IsNotTest.java | 62 ++-- .../java/org/hamcrest/core/IsNullTest.java | 63 ++-- .../java/org/hamcrest/core/IsSameTest.java | 75 +++-- .../test/java/org/hamcrest/core/IsTest.java | 81 ++--- .../org/hamcrest/core/SampleBaseClass.java | 32 +- .../org/hamcrest/core/SampleSubClass.java | 8 +- .../org/hamcrest/core/StringContainsTest.java | 64 ++-- .../org/hamcrest/core/StringEndsWithTest.java | 66 ++-- .../org/hamcrest/core/StringMatchingTest.java | 12 +- .../core/StringRegularExpressionTest.java | 4 +- .../hamcrest/core/StringStartsWithTest.java | 68 ++-- .../org/hamcrest/io/FileMatchersTest.java | 150 ++++----- .../number/BigDecimalCloseToTest.java | 6 +- .../org/hamcrest/number/IsCloseToTest.java | 38 +-- .../java/org/hamcrest/number/IsNanTest.java | 70 ++-- .../number/OrderingComparisonTest.java | 127 ++++---- .../hamcrest/object/HasEqualsValuesTest.java | 88 ++--- .../org/hamcrest/object/HasToStringTest.java | 91 +++--- .../hamcrest/object/IsCompatibleTypeTest.java | 64 ++-- .../org/hamcrest/object/IsEventFromTest.java | 64 ++-- .../hamcrest/object/MatchesPatternTest.java | 92 +++--- .../hamcrest/text/CharSequenceLengthTest.java | 34 +- .../org/hamcrest/text/IsBlankStringTest.java | 93 +++--- .../org/hamcrest/text/IsEmptyStringTest.java | 93 +++--- .../IsEqualCompressingWhiteSpaceTest.java | 68 ++-- .../text/IsEqualIgnoringCaseTest.java | 109 ++++--- .../text/StringContainsInOrderTest.java | 44 +-- .../java/org/hamcrest/xml/HasXPathTest.java | 234 +++++++------- 157 files changed, 7055 insertions(+), 6722 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-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java b/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java index 936aa7d5..58911c27 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/EasyMock2Matchers.java @@ -9,9 +9,9 @@ */ 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..520ff046 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/JMock1Matchers.java @@ -6,7 +6,7 @@ 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..06e23d2f 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/JavaLangMatcherAssert.java @@ -10,9 +10,12 @@ * @author Neil Dunn */ public class JavaLangMatcherAssert { - private 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..7a3ea891 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/integration/EasyMock2Adapter.java @@ -13,31 +13,31 @@ */ 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..4ee71ed6 100644 --- a/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java +++ b/hamcrest-integration/src/main/java/org/hamcrest/integration/JMock1Adapter.java @@ -14,29 +14,29 @@ */ 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/src/main/java/org/hamcrest/BaseDescription.java b/hamcrest/src/main/java/org/hamcrest/BaseDescription.java index d0c8fc41..bd58be38 100644 --- a/hamcrest/src/main/java/org/hamcrest/BaseDescription.java +++ b/hamcrest/src/main/java/org/hamcrest/BaseDescription.java @@ -13,140 +13,139 @@ */ public abstract class BaseDescription implements Description { - @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"); - } 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; - } + @Override + public Description appendText(String text) { + append(text); + return this; + } - private String descriptionOf(Object value) { - try { - return valueOf(value); - } - catch (Exception e) { - return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); - } - } + @Override + public Description appendDescriptionOf(SelfDescribing value) { + value.describeTo(this); + 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 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('>'); } - - @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()); + return this; + } + + private String descriptionOf(Object value) { + try { + return valueOf(value); + } catch (Exception e) { + return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); } + } + + @SafeVarargs + @Override + public final Description appendValueList(String start, String separator, String end, T... values) { + return appendValueList(start, separator, end, Arrays.asList(values)); + } - 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; + @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); - /** - * 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)); - } + 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 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..0e047d2a 100644 --- a/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/BaseMatcher.java @@ -7,36 +7,36 @@ */ 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..a7fe878b 100644 --- a/hamcrest/src/main/java/org/hamcrest/Condition.java +++ b/hamcrest/src/main/java/org/hamcrest/Condition.java @@ -7,63 +7,75 @@ * 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 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..20ce213d 100644 --- a/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java +++ b/hamcrest/src/main/java/org/hamcrest/CoreMatchers.java @@ -67,7 +67,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 @@ -85,7 +85,7 @@ 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} */ @@ -137,7 +137,7 @@ public static org.hamcrest.Matcher 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 */ @@ -152,7 +152,7 @@ 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} */ @@ -167,7 +167,7 @@ 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} */ @@ -182,7 +182,7 @@ 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} */ @@ -198,7 +198,7 @@ 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} */ @@ -211,17 +211,17 @@ 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"));
@@ -244,7 +244,7 @@ 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))

@@ -259,7 +259,7 @@ 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));
@@ -273,7 +273,7 @@ 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 */ @@ -287,7 +287,7 @@ 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 */ @@ -313,7 +313,7 @@ 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 */ @@ -335,7 +335,7 @@ 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 */ @@ -346,7 +346,7 @@ public static org.hamcrest.Matcher nullValue(java.lang.Class 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 */ @@ -357,7 +357,7 @@ public static org.hamcrest.Matcher sameInstance(T 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 */ @@ -370,7 +370,7 @@ 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 */ @@ -383,7 +383,7 @@ 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 */ @@ -398,7 +398,7 @@ 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 */ @@ -413,7 +413,7 @@ 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 */ @@ -426,7 +426,7 @@ 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 */ @@ -439,7 +439,7 @@ 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 */ diff --git a/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java b/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java index 036a7640..a322b2b3 100644 --- a/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/CustomMatcher.java @@ -17,21 +17,21 @@ * * @author Neil Dunn * @see CustomTypeSafeMatcher for a type safe variant of this class that you probably - * want to use. + * want to use. * @param The type of object being matched. */ public abstract class CustomMatcher extends BaseMatcher { - private final String fixedDescription; + 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..31efec4e 100644 --- a/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/CustomTypeSafeMatcher.java @@ -23,17 +23,17 @@ * @param The type of object being matched */ public abstract class CustomTypeSafeMatcher extends TypeSafeMatcher { - private final String fixedDescription; + 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..ddbcc4b5 100644 --- a/hamcrest/src/main/java/org/hamcrest/Description.java +++ b/hamcrest/src/main/java/org/hamcrest/Description.java @@ -11,79 +11,79 @@ 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..929aa277 100644 --- a/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/DiagnosingMatcher.java @@ -7,15 +7,15 @@ */ 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..f0ab22fe 100644 --- a/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/FeatureMatcher.java @@ -4,22 +4,22 @@ /** * 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 */ public abstract class FeatureMatcher extends TypeSafeDiagnosingMatcher { - private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("featureValueOf", 1, 0); + 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 subMatcher The matcher to apply to the feature * @param featureDescription Descriptive text to use in describeTo - * @param featureName Identifying text for mismatch message + * @param featureName Identifying text for mismatch message */ public FeatureMatcher(Matcher subMatcher, String featureDescription, String featureName) { super(TYPE_FINDER); @@ -27,7 +27,7 @@ public FeatureMatcher(Matcher subMatcher, String featureDescription, this.featureDescription = featureDescription; this.featureName = featureName; } - + /** * Implement this to extract the interesting feature. * @param actual the target object @@ -45,10 +45,10 @@ protected boolean matchesSafely(T actual, Description mismatch) { } return true; } - + @Override 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..43366f69 100644 --- a/hamcrest/src/main/java/org/hamcrest/Matcher.java +++ b/hamcrest/src/main/java/org/hamcrest/Matcher.java @@ -25,43 +25,43 @@ */ public interface Matcher extends SelfDescribing { - /** - * Evaluates the matcher for argument item. + /** + * 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. * - * 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. + * @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); + */ + 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_(); + /** + * 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..c0614934 100644 --- a/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java +++ b/hamcrest/src/main/java/org/hamcrest/MatcherAssert.java @@ -2,28 +2,28 @@ 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(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..5d98de60 100644 --- a/hamcrest/src/main/java/org/hamcrest/Matchers.java +++ b/hamcrest/src/main/java/org/hamcrest/Matchers.java @@ -161,7 +161,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 @@ -179,7 +179,7 @@ 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} */ @@ -231,7 +231,7 @@ public static org.hamcrest.Matcher 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 */ @@ -246,7 +246,7 @@ 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} */ @@ -261,7 +261,7 @@ 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} */ @@ -276,7 +276,7 @@ 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} */ @@ -292,7 +292,7 @@ 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} */ @@ -305,17 +305,17 @@ 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"));
@@ -338,7 +338,7 @@ 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))

@@ -353,7 +353,7 @@ 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));
@@ -367,7 +367,7 @@ 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 */ @@ -381,7 +381,7 @@ 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 */ @@ -407,7 +407,7 @@ 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 */ @@ -429,7 +429,7 @@ 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 */ @@ -440,7 +440,7 @@ public static org.hamcrest.Matcher nullValue(java.lang.Class 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 */ @@ -451,20 +451,20 @@ public static org.hamcrest.Matcher sameInstance(T 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) { 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 */ @@ -477,7 +477,7 @@ 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 */ @@ -492,7 +492,7 @@ 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 */ @@ -507,7 +507,7 @@ 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 */ @@ -520,7 +520,7 @@ 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 */ @@ -533,7 +533,7 @@ 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 */ @@ -577,7 +577,7 @@ 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 */ @@ -592,7 +592,7 @@ 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 */ @@ -606,7 +606,7 @@ 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 */ @@ -620,7 +620,7 @@ 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 */ @@ -635,7 +635,7 @@ 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 */ @@ -650,7 +650,7 @@ 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 */ @@ -674,7 +674,7 @@ 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 */ @@ -699,7 +699,7 @@ 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 */ @@ -721,7 +721,7 @@ 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 */ @@ -735,7 +735,7 @@ 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 */ @@ -748,7 +748,7 @@ 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 */ @@ -771,11 +771,11 @@ 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 +784,11 @@ 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 +798,7 @@ 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,7 +807,7 @@ 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} */ @@ -820,7 +820,7 @@ 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} */ @@ -843,7 +843,7 @@ 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 */ @@ -864,7 +864,7 @@ 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 */ @@ -879,7 +879,7 @@ 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} */ @@ -894,10 +894,10 @@ 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} + * examined {@link Iterable} */ public static org.hamcrest.Matcher> contains(org.hamcrest.Matcher itemMatcher) { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatcher); @@ -910,7 +910,7 @@ 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} */ @@ -926,10 +926,10 @@ 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} + * an examined {@link Iterable} */ public static org.hamcrest.Matcher> contains(java.util.List> itemMatchers) { return org.hamcrest.collection.IsIterableContainingInOrder.contains(itemMatchers); @@ -951,7 +951,7 @@ 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} */ @@ -976,7 +976,7 @@ 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 */ @@ -999,7 +999,7 @@ 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} */ @@ -1013,7 +1013,7 @@ 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 */ @@ -1028,7 +1028,7 @@ 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 */ @@ -1043,10 +1043,10 @@ 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 + * an examined {@link Iterable} in the same relative order */ public static org.hamcrest.Matcher> containsInRelativeOrder(java.util.List> itemMatchers) { return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(itemMatchers); @@ -1058,7 +1058,7 @@ 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} */ @@ -1072,7 +1072,7 @@ 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} */ @@ -1086,13 +1086,13 @@ 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 +1102,13 @@ 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 +1117,11 @@ 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 +1130,11 @@ 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 +1143,11 @@ 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 +1156,11 @@ 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,7 +1169,7 @@ 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 */ @@ -1182,7 +1182,7 @@ 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 */ @@ -1195,7 +1195,7 @@ 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 @@ -1210,7 +1210,7 @@ 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 @@ -1225,7 +1225,7 @@ 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 @@ -1241,7 +1241,7 @@ 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 */ @@ -1255,7 +1255,7 @@ 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 @@ -1280,7 +1280,7 @@ 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 @@ -1296,7 +1296,7 @@ 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 */ public static > org.hamcrest.Matcher comparesEqualTo(T value) { @@ -1309,7 +1309,7 @@ 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 */ @@ -1323,7 +1323,7 @@ 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 */ @@ -1337,7 +1337,7 @@ 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 */ @@ -1351,7 +1351,7 @@ 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 */ @@ -1364,7 +1364,7 @@ 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 */ @@ -1423,7 +1423,7 @@ public static Matcher emptyString() { * has zero length. * For example: *
assertThat(((String)null), isEmptyOrNullString())
- * + * * @deprecated use is(emptyOrNullString()) instead */ @SuppressWarnings("deprecation") @@ -1435,7 +1435,7 @@ 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") @@ -1485,7 +1485,7 @@ 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 */ @@ -1499,7 +1499,7 @@ 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 */ @@ -1507,27 +1507,27 @@ public static Matcher stringContainsInOrder(java.lang.String.. 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 */ @@ -1540,7 +1540,7 @@ public static org.hamcrest.Matcher hasToString(org.hamcrest.MatcherassertThat(true, hasToString("TRUE"))
- * + * * @param expectedToString * the expected toString result */ @@ -1553,7 +1553,7 @@ 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 */ @@ -1566,7 +1566,7 @@ 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 @@ -1581,7 +1581,7 @@ 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 */ @@ -1594,7 +1594,7 @@ 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 */ @@ -1607,7 +1607,7 @@ 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 @@ -1641,7 +1641,7 @@ 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 @@ -1657,7 +1657,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 @@ -1674,7 +1674,7 @@ 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 */ @@ -1687,7 +1687,7 @@ 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 diff --git a/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java b/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java index 06b361d2..55c90e6f 100644 --- a/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java +++ b/hamcrest/src/main/java/org/hamcrest/SelfDescribing.java @@ -4,13 +4,13 @@ * 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. - * + /** + * 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); + */ + 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..7901ba87 100644 --- a/hamcrest/src/main/java/org/hamcrest/StringDescription.java +++ b/hamcrest/src/main/java/org/hamcrest/StringDescription.java @@ -6,58 +6,58 @@ * A {@link Description} that is stored as a string. */ public class StringDescription extends BaseDescription { - private final Appendable out; + 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. - * + 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 static String toString(SelfDescribing selfDescribing) { + return new StringDescription().appendDescriptionOf(selfDescribing).toString(); + } - /** - * Alias for {@link #toString(SelfDescribing)}. - */ - public static String asString(SelfDescribing selfDescribing) { - return toString(selfDescribing); - } + /** + * 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(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); - } - } - - /** - * Returns the description as a string. - */ - @Override - public String toString() { - return out.toString(); + @Override + protected void append(char c) { + try { + out.append(c); + } 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..22c9d066 100644 --- a/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/TypeSafeDiagnosingMatcher.java @@ -6,8 +6,8 @@ /** * 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 @@ -15,60 +15,60 @@ * @author Steve Freeman */ public abstract class TypeSafeDiagnosingMatcher extends BaseMatcher { - private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 2, 0); - private final Class expectedType; + 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 - && expectedType.isInstance(item) - && matchesSafely((T) item, new Description.NullDescription()); - } + @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"); + @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); + .appendText(item.getClass().getSimpleName()) + .appendText(" ") + .appendValue(item); } else { - matchesSafely((T) item, mismatchDescription); - } + 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..33ff84a8 100644 --- a/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/TypeSafeMatcher.java @@ -11,75 +11,75 @@ * @author Nat Pryce */ public abstract class TypeSafeMatcher extends BaseMatcher { - private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 1, 0); - - final private Class expectedType; + 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); - } - - /** - * 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); - } else if (! expectedType.isInstance(item)) { - description.appendText("was a ") - .appendText(item.getClass().getName()) - .appendText(" (") - .appendValue(item) - .appendText(")"); - } else { - describeMismatchSafely((T)item, description); - } + 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); + } else if (!expectedType.isInstance(item)) { + description.appendText("was a ") + .appendText(item.getClass().getName()) + .appendText(" (") + .appendValue(item) + .appendText(")"); + } 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..932410b0 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/HasProperty.java @@ -15,42 +15,42 @@ */ public class HasProperty extends TypeSafeMatcher { - private final String 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 void describeMismatchSafely(T item, Description mismatchDescription) { - mismatchDescription.appendText("no ").appendValue(propertyName).appendText(" in ").appendValue(item); + private final String 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 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"))
- * + } + + @Override + public void describeMismatchSafely(T item, Description mismatchDescription) { + mismatchDescription.appendText("no ").appendValue(propertyName).appendText(" in ").appendValue(item); + } + + @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); - } + */ + 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..58e12763 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 @@ -70,123 +70,123 @@ * @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; + 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); + } 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); } - - 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"))
- * + } + }; + } + + @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"))
- * + */ + 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; + */ + 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..801824e0 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java @@ -14,38 +14,38 @@ * @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; + /** + * 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..dafa0dc4 100644 --- a/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java +++ b/hamcrest/src/main/java/org/hamcrest/beans/SamePropertyValuesAs.java @@ -14,146 +14,146 @@ 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); + 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; } + mismatchDescription.appendText("is incompatible type: " + actual.getClass().getSimpleName()); + return false; + } - private boolean isCompatibleType(Object actual, Description mismatchDescription) { - if (expectedBean.getClass().isAssignableFrom(actual.getClass())) { - return true; - } - - 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 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 hasMatchingValues(Object actual, Description mismatchDescription) { - for (PropertyMatcher propertyMatcher : propertyMatchers) { - if (!propertyMatcher.matches(actual)) { - propertyMatcher.describeMismatch(actual, mismatchDescription); - 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 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; + 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 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); + } 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")
- * + } + + /** + * 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)); - } + */ + 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..a97ea379 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/ArrayAsIterableMatcher.java @@ -18,10 +18,9 @@ public class ArrayAsIterableMatcher extends TypeSafeMatcher { protected final Collection> matchers; public ArrayAsIterableMatcher( - TypeSafeDiagnosingMatcher> iterableMatcher, - Collection> matchers, - String message) - { + TypeSafeDiagnosingMatcher> iterableMatcher, + Collection> matchers, + String message) { this.matchers = matchers; this.iterableMatcher = iterableMatcher; this.message = message; @@ -29,7 +28,7 @@ public ArrayAsIterableMatcher( @Override public boolean matchesSafely(E[] item) { - return iterableMatcher.matches(asList(item)); + return iterableMatcher.matches(asList(item)); } @Override @@ -39,7 +38,7 @@ public void describeMismatchSafely(E[] item, Description mismatchDescription) { @Override public void describeTo(Description description) { - description.appendList("[", ", ", "]", matchers) - .appendText(" ").appendText(message); + 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..29e590c0 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/ArrayMatching.java @@ -28,7 +28,7 @@ public class ArrayMatching { * the matcher to apply to elements in examined arrays */ public static Matcher hasItemInArray(Matcher elementMatcher) { - return new HasItemInArray<>(elementMatcher); + return new HasItemInArray<>(elementMatcher); } /** @@ -67,7 +67,7 @@ public static Matcher hasItemInArray(T element) { */ @SafeVarargs public static Matcher arrayContainingInAnyOrder(Matcher... itemMatchers) { - return arrayContainingInAnyOrder(asList(itemMatchers)); + return arrayContainingInAnyOrder(asList(itemMatchers)); } /** @@ -131,6 +131,7 @@ public static Matcher arrayContainingInAnyOrder(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 @@ -143,11 +144,11 @@ public static Matcher arrayContaining(E... items) { */ @SafeVarargs public static Matcher arrayContaining(Matcher... itemMatchers) { - //required for JDK 1.6 - //noinspection RedundantTypeArguments - final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); + //required for JDK 1.6 + //noinspection RedundantTypeArguments + final List> nullSafeWithExplicitTypeMatchers = NullSafety.nullSafe(itemMatchers); - return arrayContaining(nullSafeWithExplicitTypeMatchers); + return arrayContaining(nullSafeWithExplicitTypeMatchers); } /** @@ -161,7 +162,7 @@ public static Matcher arrayContaining(Matcher... itemMatcher * 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, ""); + return new ArrayAsIterableMatcher<>(new IsIterableContainingInOrder<>(itemMatchers), itemMatchers, ""); } public static List> asEqualMatchers(E[] items) { diff --git a/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java b/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java index 5c0513c1..0315d695 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/HasItemInArray.java @@ -12,29 +12,29 @@ * 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 - .appendText("an array containing ") - .appendDescriptionOf(elementMatcher); - } + 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..9196e4f7 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArray.java @@ -11,87 +11,87 @@ * 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; - } + private final Matcher[] elementMatchers; + + public IsArray(Matcher[] elementMatchers) { + this.elementMatchers = elementMatchers.clone(); + } - @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; - } - } + @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; } - @Override - @SuppressWarnings("unchecked") - public void describeTo(Description description) { - description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(), - Arrays.asList(elementMatchers)); + return true; + } + + @Override + public void describeMismatchSafely(T[] actual, Description mismatchDescription) { + if (actual.length != elementMatchers.length) { + mismatchDescription.appendText("array length was ").appendValue(actual.length); + return; } - - /** - * Returns the string that starts the description. - * - * Can be overridden in subclasses to customise how the matcher is - * described. - */ - protected String descriptionStart() { - 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; + } } + } - /** - * 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 ", "; - } + @Override + @SuppressWarnings("unchecked") + public void describeTo(Description description) { + description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(), + Arrays.asList(elementMatchers)); + } - /** - * 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))))
- * + /** + * 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); - } + */ + 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..b5cf3665 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInAnyOrder.java @@ -16,97 +16,99 @@ */ @Deprecated public class IsArrayContainingInAnyOrder extends TypeSafeMatcher { - private final IsIterableContainingInAnyOrder iterableMatcher; - private final Collection> matchers; + 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[])}. + ; + + @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")))
+ * + * @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)); - } + */ + 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)}. + /** + * 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); - } + */ + 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[])}. + /** + * 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); + */ + 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..ae092747 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayContainingInOrder.java @@ -15,81 +15,81 @@ * @deprecated As of release 2.1, replaced by {@link ArrayMatching}. */ public class IsArrayContainingInOrder extends TypeSafeMatcher { - private final Collection> matchers; - private final IsIterableContainingInOrder iterableMatcher; + 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[])}. + @Override + public void describeTo(Description description) { + description.appendList("[", ", ", "]", matchers); + } + + /** + * 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); + */ + 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 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[])}. + /** + * 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)); - } + */ + 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"))))
- * - * @deprecated As of version 2.1, use {@link ArrayMatching#arrayContaining(List)}. + /** + * 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); - } + */ + 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..67d532f0 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsArrayWithSize.java @@ -10,49 +10,49 @@ * 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 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)))
- * + /** + * 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); - } + */ + 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))
- * + /** + * 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)); - } + */ + 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..7689addf 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsCollectionWithSize.java @@ -11,40 +11,40 @@ * 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)))
- * + 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))
- * + */ + 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)); - } + */ + @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..8aa92774 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyCollection.java @@ -11,43 +11,43 @@ */ 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)))
- * + @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(); - } + */ + @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..9890dc84 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsEmptyIterable.java @@ -9,40 +9,41 @@ */ 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)))
- * + /** + * 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(); - } + */ + @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..904f112e 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIn.java @@ -8,120 +8,120 @@ import java.util.Collection; public class IsIn extends BaseMatcher { - private final Collection collection; + 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 - * + public IsIn(T[] elements) { + collection = Arrays.asList(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")))
+ * + * @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"))))
- * + * + */ + @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 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"}))
- * - * @deprecated use is(in(...)) instead - * + /** + * 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"})))
- * + * + */ + @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 - * + * + */ + 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")))
- * + * 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); - } + * 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..b3d67ee1 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInAnyOrder.java @@ -12,145 +12,145 @@ import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContainingInAnyOrder extends TypeSafeDiagnosingMatcher> { - private final Collection> matchers; + 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"); + } + + private static class Matching { + private final Collection> matchers; + private final Description mismatchDescription; + + 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); + } - public boolean isFinished(Iterable items) { - if (matchers.isEmpty()) { - return true; - } - mismatchDescription + public boolean isFinished(Iterable items) { + if (matchers.isEmpty()) { + return true; + } + mismatchDescription .appendText("no item matches: ").appendList("", ", ", "", matchers) .appendText(" in ").appendValueList("[", ", ", "]", items); - return false; - } + return false; + } - private boolean isMatched(S item) { - for (Matcher matcher : matchers) { - if (matcher.matches(item)) { - matchers.remove(matcher); - return true; - } + private boolean isMatched(S item) { + for (Matcher matcher : matchers) { + if (matcher.matches(item)) { + matchers.remove(matcher); + return true; } - mismatchDescription.appendText("not matched: ").appendValue(item); - return false; } + 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 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")))
- * + /** + *

+ * 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)); - } + */ + @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"))
- * + /** + *

+ * 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); + */ + @SafeVarargs + public static Matcher> containsInAnyOrder(T... items) { + List> matchers = new ArrayList<>(); + for (T item : items) { + matchers.add(equalTo(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 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"))))
- * + 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); - } + */ + 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..9f1fcbcc 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInOrder.java @@ -12,139 +12,139 @@ import static org.hamcrest.collection.ArrayMatching.asEqualMatchers; public class IsIterableContainingInOrder extends TypeSafeDiagnosingMatcher> { - private final List> matchers; + 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; + } + } - public IsIterableContainingInOrder(List> matchers) { - this.matchers = matchers; + 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 - protected boolean matchesSafely(Iterable iterable, Description mismatchDescription) { - final MatchSeries matchSeries = new MatchSeries<>(matchers, mismatchDescription); - for (E item : iterable) { - if (!matchSeries.matches(item)) { - return false; - } - } + public boolean matches(F item) { + if (matchers.size() <= nextMatchIx) { + mismatchDescription.appendText("not matched: ").appendValue(item); + return false; + } - return matchSeries.isFinished(); + return isMatched(item); } - @Override - public void describeTo(Description description) { - description.appendText("iterable containing ").appendList("[", ", ", "]", matchers); + public boolean isFinished() { + if (nextMatchIx < matchers.size()) { + mismatchDescription.appendText("no item was ").appendDescriptionOf(matchers.get(nextMatchIx)); + return false; + } + return true; } - 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); - } + 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 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"))
- * + 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")))
- * + */ + @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")))
- * + * 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"))))
- * + */ + @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); - } + * 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..cebd4e0e 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java @@ -11,109 +11,109 @@ 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 void describeTo(Description description) { - description.appendText("iterable containing ").appendList("[", ", ", "]", matchers).appendText(" in relative order"); + 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; } - 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 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 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; } - /** - * 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"))
- * + } + + /** + * 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)); - } - - return containsInRelativeOrder(matchers); + */ + @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 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")))
- * + 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"))))
- * + */ + @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); - } + * 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..12d445bc 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsIterableWithSize.java @@ -9,45 +9,45 @@ 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; - } + public IsIterableWithSize(Matcher sizeMatcher) { + super(sizeMatcher, "an iterable with size", "iterable 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)))
- * + + @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))
- * + */ + 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 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..8ea4bc18 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsMapContaining.java @@ -10,120 +10,120 @@ 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")))
- * + /** + * 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); - } + */ + 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"))
- * + /** + * 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")))
- * + */ + 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()); - } + */ + 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 key that is equal to the specified key. - * For example: - *
assertThat(myMap, hasKey("bar"))
- * + /** + * 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()); - } + */ + 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 satisfies the specified valueMatcher. - * For example: - *
assertThat(myMap, hasValue(equalTo("foo")))
- * + /** + * 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); - } + */ + 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"))
- * + /** + * 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)); - } + */ + 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..7365794f 100644 --- a/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java +++ b/hamcrest/src/main/java/org/hamcrest/collection/IsMapWithSize.java @@ -11,50 +11,50 @@ * 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))))
- * + @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)))
- * + */ + 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 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..0864403a 100644 --- a/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java +++ b/hamcrest/src/main/java/org/hamcrest/comparator/ComparatorMatcherBuilder.java @@ -10,169 +10,169 @@ 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); - } - - /** - * 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; - - 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]; - } - } - - /** - * 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); + 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 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); + @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 :( + } } - /** - * 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); + @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); + } } - /** - * 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); + @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 - * 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..8b5fff2a 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/AllOf.java +++ b/hamcrest/src/main/java/org/hamcrest/core/AllOf.java @@ -12,50 +12,50 @@ */ public class AllOf extends DiagnosingMatcher { - private final Iterable> matchers; - - @SafeVarargs - public AllOf(Matcher ... matchers) { - this(Arrays.asList(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 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")))
- */ - @SafeVarargs - public static Matcher allOf(Matcher... matchers) { - return allOf(Arrays.asList(matchers)); + private final Iterable> matchers; + + @SafeVarargs + public AllOf(Matcher... matchers) { + this(Arrays.asList(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 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")))
+ */ + @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..95cf71a4 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java +++ b/hamcrest/src/main/java/org/hamcrest/core/AnyOf.java @@ -11,41 +11,41 @@ */ 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)); - } + @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..59054dad 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/core/CombinableMatcher.java @@ -50,12 +50,14 @@ private ArrayList> templatedListWith(Matcher other public static CombinableBothMatcher both(Matcher matcher) { return new CombinableBothMatcher<>(matcher); } - + public static final class CombinableBothMatcher { private final Matcher first; + public CombinableBothMatcher(Matcher matcher) { - this.first = matcher; + this.first = matcher; } + public CombinableMatcher and(Matcher other) { return new CombinableMatcher<>(first).and(other); } @@ -69,12 +71,14 @@ public CombinableMatcher and(Matcher other) { public static CombinableEitherMatcher either(Matcher matcher) { return new CombinableEitherMatcher<>(matcher); } - + public static final class CombinableEitherMatcher { private final Matcher first; + public CombinableEitherMatcher(Matcher matcher) { - this.first = matcher; + this.first = matcher; } + 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..69578b11 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java +++ b/hamcrest/src/main/java/org/hamcrest/core/DescribedAs.java @@ -12,58 +12,58 @@ * 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); - } + 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); + } - @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 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(); } - - @Override - public void describeMismatch(Object item, Description description) { - matcher.describeMismatch(item, description); + + if (textStart < descriptionTemplate.length()) { + description.appendText(descriptionTemplate.substring(textStart)); } + } - /** - * 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())
- * + @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); - } + */ + 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..9908460f 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/Every.java +++ b/hamcrest/src/main/java/org/hamcrest/core/Every.java @@ -5,40 +5,40 @@ import org.hamcrest.TypeSafeDiagnosingMatcher; public class Every extends TypeSafeDiagnosingMatcher> { - private final Matcher matcher; + 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")))
- * + /** + * 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); - } + */ + 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..efb9cc37 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/Is.java +++ b/hamcrest/src/main/java/org/hamcrest/core/Is.java @@ -11,64 +11,64 @@ * 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; + 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..201e77af 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsAnything.java @@ -10,39 +10,41 @@ */ 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}. - * + 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 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..26d550c8 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsCollectionContaining.java @@ -9,92 +9,92 @@ */ @Deprecated public class IsCollectionContaining extends TypeSafeDiagnosingMatcher> { - private final IsIterableContaining delegate; + 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")))
+ + /** + * 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)}. * - * @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); - } + */ + 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)}. + /** + * 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); - } + */ + 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")))
- * - * @deprecated As of version 2.1, use {@link IsIterableContaining#hasItems(Matcher[])}}. + /** + * 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[])}}. + */ + @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); - } + */ + @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..63aa825f 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsEqual.java @@ -12,86 +12,86 @@ * {@link java.lang.Object#equals} invokedMethod? */ public class IsEqual extends BaseMatcher { - private final Object expectedValue; + 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..89f5ad52 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsInstanceOf.java @@ -10,82 +10,82 @@ * 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; + 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; + 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; + } - @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; + @Override + protected boolean matches(Object item, Description mismatch) { + if (null == item) { + mismatch.appendText("null"); + return false; } - @Override - public void describeTo(Description description) { - description.appendText("an instance of ").appendText(expectedClass.getName()); + if (!matchableClass.isInstance(item)) { + mismatch.appendValue(item).appendText(" is a " + item.getClass().getName()); + 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 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));
+ 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 any(Class type) { - return (Matcher) new IsInstanceOf(type); - } + */ + @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..eb77f85c 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsIterableContaining.java @@ -11,123 +11,123 @@ import static org.hamcrest.core.IsEqual.equalTo; public class IsIterableContaining extends TypeSafeDiagnosingMatcher> { - private final Matcher elementMatcher; + 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; + } + + private boolean isEmpty(Iterable iterable) { + return !iterable.iterator().hasNext(); + } + + @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")))
- * + + /** + * 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); - } + */ + public static Matcher> hasItem(Matcher itemMatcher) { + return new IsIterableContaining<>(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"))
- * + /** + * 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)); - } + */ + 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")))
- * + /** + * 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); + */ + @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"))
- * + + 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); + */ + @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..9aa69648 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsNot.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsNot.java @@ -10,48 +10,48 @@ /** * 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))))
- * +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))))
- * + */ + 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 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..ce2fcf2b 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsNull.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsNull.java @@ -10,65 +10,65 @@ * Is the value null? */ public class IsNull extends BaseMatcher { - @Override - public boolean matches(Object o) { - return o == null; - } + @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))
- * + /** + * 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(); - } + */ + 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))))
- * + /** + * 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)); - } + * + */ + 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..b1ffb9d1 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/IsSame.java +++ b/hamcrest/src/main/java/org/hamcrest/core/IsSame.java @@ -9,43 +9,43 @@ * 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. - * + 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. - * + */ + 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 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..da650408 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java +++ b/hamcrest/src/main/java/org/hamcrest/core/ShortcutCombination.java @@ -6,28 +6,28 @@ 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..2e2c2777 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringContains.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringContains.java @@ -6,43 +6,45 @@ * 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 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"))
- * + /** + * 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"))
* + */ + 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); - } + */ + 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..6aa2ffb9 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringEndsWith.java @@ -6,39 +6,43 @@ * 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 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"))
- * + /** + * 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); - } + */ + 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"))
- * + /** + * 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); - } + */ + public static Matcher endsWithIgnoringCase(String suffix) { + return new StringEndsWith(true, suffix); + } } diff --git a/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java b/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java index fa49b793..6424b37c 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java +++ b/hamcrest/src/main/java/org/hamcrest/core/StringStartsWith.java @@ -6,37 +6,47 @@ * 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 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"))
- * + /** + *

+ * 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); } + */ + 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"))
- * + /** + *

+ * 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); } + */ + 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..3f27acbb 100644 --- a/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java +++ b/hamcrest/src/main/java/org/hamcrest/core/SubstringMatcher.java @@ -5,43 +5,47 @@ 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"); - } + // 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..63c491d8 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/ArrayIterator.java @@ -4,28 +4,28 @@ 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); - } + 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..8367b251 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/NullSafety.java @@ -7,12 +7,12 @@ 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; + @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..e6a8f304 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 */ @@ -37,14 +37,14 @@ public ReflectiveTypeFinder(String methodName, int expectedNumberOfParameters, i 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); - } + for (Method method : c.getDeclaredMethods()) { + if (canObtainExpectedTypeFrom(method)) { + return expectedTypeFrom(method); } + } } throw new Error("Cannot determine correct type for " + methodName + "() method."); } @@ -54,9 +54,9 @@ public Class findExpectedType(Class fromClass) { * @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(); + return method.getName().equals(methodName) + && method.getParameterTypes().length == expectedNumberOfParameters + && !method.isSynthetic(); } @@ -65,6 +65,6 @@ private boolean canObtainExpectedTypeFrom(Method method) { * @return The type we're looking for */ private Class expectedTypeFrom(Method method) { - return method.getParameterTypes()[typedParameter]; + 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..e0d075e1 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValue.java @@ -4,14 +4,14 @@ import org.hamcrest.SelfDescribing; public class SelfDescribingValue implements SelfDescribing { - private T value; - - public SelfDescribingValue(T value) { - this.value = value; - } + 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..3a68448c 100644 --- a/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java +++ b/hamcrest/src/main/java/org/hamcrest/internal/SelfDescribingValueIterator.java @@ -5,24 +5,24 @@ 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(); - } + 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..a75812d8 100644 --- a/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java +++ b/hamcrest/src/main/java/org/hamcrest/io/FileMatchers.java @@ -12,96 +12,121 @@ 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 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 Matcher aWritableFile() { - return fileChecker(CAN_WRITE, "a writable File", "cannot be written to"); - } + public static interface FileStatus { + boolean check(File actual); + } - public static Matcher aFileWithSize(long size) { - return aFileWithSize(equalTo(size)); + public static final FileStatus CAN_WRITE = new FileStatus() { + @Override + public boolean check(File actual) { + return actual.canWrite(); } - - 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 final FileStatus CAN_READ = new FileStatus() { + @Override + public boolean check(File actual) { + return actual.canRead(); } + }; - 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 IS_FILE = new FileStatus() { + @Override + public boolean check(File actual) { + return actual.isFile(); } + }; - 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_DIRECTORY = new FileStatus() { + @Override + public boolean check(File actual) { + return actual.isDirectory(); } + }; - 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 EXISTS = new FileStatus() { + @Override + public boolean check(File actual) { + return actual.exists(); } - - 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 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(); } + }; + + 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 IS_DIRECTORY = new FileStatus() { - @Override public boolean check(File actual) { return actual.isDirectory(); } - }; - - 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..3dde9a7d 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java +++ b/hamcrest/src/main/java/org/hamcrest/number/BigDecimalCloseTo.java @@ -13,34 +13,34 @@ public class BigDecimalCloseTo extends TypeSafeMatcher { private final BigDecimal value; public BigDecimalCloseTo(BigDecimal value, BigDecimal error) { - this.delta = error; - this.value = value; + this.delta = error; + this.value = value; } @Override public boolean matchesSafely(BigDecimal item) { - return actualDelta(item).compareTo(BigDecimal.ZERO) <= 0; + 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); + 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); + 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(); + return item.subtract(value, MathContext.DECIMAL128).abs().subtract(delta, MathContext.DECIMAL128).stripTrailingZeros(); } /** @@ -49,14 +49,14 @@ 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); + 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..b8a71077 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java +++ b/hamcrest/src/main/java/org/hamcrest/number/IsCloseTo.java @@ -12,52 +12,52 @@ * 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)))
- * + 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 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..53f67f93 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java +++ b/hamcrest/src/main/java/org/hamcrest/number/IsNaN.java @@ -10,29 +10,30 @@ */ 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(); - } + 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..a254073a 100644 --- a/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java +++ b/hamcrest/src/main/java/org/hamcrest/number/OrderingComparison.java @@ -5,75 +5,75 @@ 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..c73f3acd 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java +++ b/hamcrest/src/main/java/org/hamcrest/object/HasEqualValues.java @@ -13,74 +13,75 @@ import static java.lang.String.format; public class HasEqualValues extends TypeSafeDiagnosingMatcher { - private final T expectedObject; - private final List fieldMatchers; + 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..72aeccb0 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/HasToString.java +++ b/hamcrest/src/main/java/org/hamcrest/object/HasToString.java @@ -6,38 +6,38 @@ 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 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")))
- * + @Override + protected String featureValueOf(T actual) { + return String.valueOf(actual); + } + + /** + * 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); - } + */ + 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"))
- * + /** + * 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)); - } + */ + 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..aca5a2f3 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java +++ b/hamcrest/src/main/java/org/hamcrest/object/IsCompatibleType.java @@ -5,37 +5,37 @@ 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))
- * + 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 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..a7a74a83 100644 --- a/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java +++ b/hamcrest/src/main/java/org/hamcrest/object/IsEventFrom.java @@ -11,66 +11,66 @@ * 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; + 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)))
- * + private boolean eventHasSameSource(EventObject ev) { + return ev.getSource() == 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); - } + */ + 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)))
- * + /** + * 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); - } + */ + 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..0829d736 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java +++ b/hamcrest/src/main/java/org/hamcrest/text/CharSequenceLength.java @@ -11,47 +11,47 @@ */ 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); - } + /** + * @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..edf6171d 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java @@ -14,42 +14,43 @@ * 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; - } + 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..a515ee48 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsEmptyString.java @@ -12,66 +12,67 @@ * 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); + 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..d1859961 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java @@ -11,64 +11,64 @@ */ 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)} + @Override + public void describeTo(Description description) { + description.appendText("a string equal to ") + .appendValue(string) + .appendText(" compressing white space"); + } + + public String stripSpaces(String toBeStripped) { + return toBeStripped.replaceAll("\\s+", " ").trim(); + } + + /** + * @deprecated {@link #equalToCompressingWhiteSpace(String)} * @param expectedString * the expected value of matched strings - */ - public static Matcher equalToIgnoringWhiteSpace(String expectedString) { - return new IsEqualCompressingWhiteSpace(expectedString); - } + */ + 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"))
- * + /** + * 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 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..9923b565 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java +++ b/hamcrest/src/main/java/org/hamcrest/text/IsEqualIgnoringCase.java @@ -9,46 +9,46 @@ */ 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; + public IsEqualIgnoringCase(String string) { + if (string == null) { + throw new IllegalArgumentException("Non-null value required"); } - - @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"))
- * + 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 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..3ccc35ec 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java +++ b/hamcrest/src/main/java/org/hamcrest/text/MatchesPattern.java @@ -7,35 +7,35 @@ 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)); - } + 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..ba1f6513 100644 --- a/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java +++ b/hamcrest/src/main/java/org/hamcrest/text/StringContainsInOrder.java @@ -7,64 +7,64 @@ import java.util.Arrays; public class StringContainsInOrder extends TypeSafeMatcher { - private final Iterable substrings; + 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"); + @Override + public boolean matchesSafely(String s) { + int fromIndex = 0; + + for (String substring : substrings) { + fromIndex = s.indexOf(substring, fromIndex); + if (fromIndex == -1) { + return false; + } + fromIndex++; } - - /** - * 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" - * + + 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); - } + */ + 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" - * + /** + * 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)); - } + */ + 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..ec5670e3 100644 --- a/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java +++ b/hamcrest/src/main/java/org/hamcrest/xml/HasXPath.java @@ -22,148 +22,148 @@ * @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 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); + } catch (XPathExpressionException e) { + mismatch.appendText(e.getMessage()); } - - 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); - } - }; - } - - 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); + } 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")))
- * + /** + * 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")))
- * + */ + 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"))
- * + */ + 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))
- * + */ + 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); - } + */ + 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..1f8627c5 100644 --- a/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/AbstractMatcherTest.java @@ -9,9 +9,9 @@ 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); + assertMatches("Expected match, but mismatched", matcher, arg); } public static void assertMatches(String message, Matcher matcher, Object arg) { @@ -21,7 +21,7 @@ public static void assertMatches(String message, Matcher matcher, Object } public static void assertDoesNotMatch(Matcher c, T arg) { - assertDoesNotMatch("Unexpected match", c, arg); + assertDoesNotMatch("Unexpected match", c, arg); } public static void assertDoesNotMatch(String message, Matcher c, T arg) { @@ -38,22 +38,21 @@ public static void assertMismatchDescription(String expected, Matcher matcher) { - try { - matcher.matches(null); - } - catch (Exception e) { - Assert.fail("Matcher was not null safe"); - } + 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); - } + try { + matcher.matches(new UnknownType()); + } catch (Exception e) { + Assert.fail("Matcher was not unknown type safe, because: " + e); + } } public void testIsNullSafe() { @@ -64,11 +63,11 @@ 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 { diff --git a/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java b/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java index afbdd65f..66f48ea7 100644 --- a/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/BaseDescriptionTest.java @@ -6,109 +6,126 @@ 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..ca55ac7c 100644 --- a/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/BaseMatcherTest.java @@ -6,21 +6,21 @@ 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..d2e08534 100644 --- a/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/CustomMatcherTest.java @@ -6,15 +6,16 @@ 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..93dfdd58 100644 --- a/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/CustomTypeSafeMatcherTest.java @@ -5,37 +5,41 @@ 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); - } + private static final String STATIC_DESCRIPTION = "I match non empty strings"; - @Test public void - reportsMismatch() { - assertMismatchDescription("an item", customMatcher, "item"); + private final Matcher customMatcher = new CustomTypeSafeMatcher(STATIC_DESCRIPTION) { + @Override + public boolean matchesSafely(String item) { + return false; } - @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..29ab1722 100644 --- a/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/FeatureMatcherTest.java @@ -7,62 +7,73 @@ import static org.junit.Assert.assertEquals; public final class FeatureMatcherTest { - private final FeatureMatcher resultMatcher = resultMatcher(); + 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..05221bbf 100644 --- a/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java +++ b/hamcrest/src/test/java/org/hamcrest/MatcherAssertTest.java @@ -8,92 +8,93 @@ public final class MatcherAssertTest { - @Test public void - includesDescriptionOfTestedValueInErrorMessage() { - String expected = "expected"; - String actual = "actual"; - String endLine = System.lineSeparator(); - - String expectedMessage = "identifier" + endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; - - try { - assertThat("identifier", actual, equalTo(expected)); - } - catch (AssertionError e) { - assertTrue(e.getMessage().startsWith(expectedMessage)); - return; - } - - fail("should have failed"); + @Test + public void + includesDescriptionOfTestedValueInErrorMessage() { + String expected = "expected"; + String actual = "actual"; + String endLine = System.lineSeparator(); + + String expectedMessage = "identifier" + endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; + + try { + assertThat("identifier", actual, equalTo(expected)); + } catch (AssertionError e) { + assertTrue(e.getMessage().startsWith(expectedMessage)); + return; } - @Test public void - descriptionCanBeElided() { - String expected = "expected"; - String actual = "actual"; - String endLine = System.lineSeparator(); + fail("should have failed"); + } - String expectedMessage = endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; + @Test + public void + descriptionCanBeElided() { + String expected = "expected"; + String actual = "actual"; + String endLine = System.lineSeparator(); - try { - assertThat(actual, equalTo(expected)); - } - catch (AssertionError e) { - assertTrue(e.getMessage().startsWith(expectedMessage)); - return; - } + String expectedMessage = endLine + "Expected: \"expected\"" + endLine + " but: was \"actual\""; - fail("should have failed"); + try { + assertThat(actual, equalTo(expected)); + } catch (AssertionError e) { + assertTrue(e.getMessage().startsWith(expectedMessage)); + return; } - @Test public void - canTestBooleanDirectly() { - assertThat("success reason message", true); + fail("should have failed"); + } - try { - assertThat("failing reason message", false); - } - catch (AssertionError e) { - assertEquals("failing reason message", e.getMessage()); - return; - } + @Test + public void + canTestBooleanDirectly() { + assertThat("success reason message", true); - fail("should have failed"); + try { + assertThat("failing reason message", false); + } catch (AssertionError e) { + assertEquals("failing reason message", e.getMessage()); + return; } - @Test public void - includesMismatchDescription() { - Matcher matcherWithCustomMismatchDescription = new BaseMatcher() { - @Override - public boolean matches(Object item) { - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText("Something cool"); - } - - @Override - public void describeMismatch(Object item, Description mismatchDescription) { - mismatchDescription.appendText("Not cool"); - } - }; - - String endLine = System.lineSeparator(); - String expectedMessage = endLine + "Expected: Something cool" + endLine + " but: Not cool"; - - try { - assertThat("Value", matcherWithCustomMismatchDescription); - fail("should have failed"); - } - catch (AssertionError e) { - assertEquals(expectedMessage, e.getMessage()); - } + fail("should have failed"); + } + + @Test + public void + includesMismatchDescription() { + Matcher matcherWithCustomMismatchDescription = new BaseMatcher() { + @Override + public boolean matches(Object item) { + return false; + } + + @Override + public void describeTo(Description description) { + description.appendText("Something cool"); + } + + @Override + public void describeMismatch(Object item, Description mismatchDescription) { + mismatchDescription.appendText("Not cool"); + } + }; + + String endLine = System.lineSeparator(); + String expectedMessage = endLine + "Expected: Something cool" + endLine + " but: Not cool"; + + try { + assertThat("Value", matcherWithCustomMismatchDescription); + fail("should have failed"); + } catch (AssertionError e) { + assertEquals(expectedMessage, e.getMessage()); } + } - @Test public void - canAssertSubtypes() { - assertThat(1, equalTo((Number) 1)); - } + @Test + public void + 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..539d1f89 100644 --- a/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/NullDescriptionTest.java @@ -7,12 +7,13 @@ 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..26b14af8 100644 --- a/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/TypeSafeDiagnosingMatcherTest.java @@ -10,72 +10,93 @@ @SuppressWarnings("WeakerAccess") 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; - } + @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"); } - }; + @Override + public void describeTo(Description description) { + description.appendText("a not builtin"); + } + }; - 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 + 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 - but_cannot_detect_generic_type_in_subclassed_matcher_using_reflection() { - final Matcher matcher = new SubMatcher<>(); + @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()); + assertMatches("other not built in", (Matcher) matcher, new OtherNotBuiltIn()); + } - assertMatches("not built in", matcher, new NotBuiltIn()); - assertMatches("other not built in", (Matcher)matcher, new OtherNotBuiltIn()); + private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher() { + @Override + protected boolean matchesSafely(String item, Description mismatchDescription) { + mismatchDescription.appendText("mismatching"); + return false; } - private static final TypeSafeDiagnosingMatcher STRING_MATCHER = new TypeSafeDiagnosingMatcher() { - @Override - protected boolean matchesSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("mismatching"); - return false; - } + @Override + public void describeTo(Description description) { + } + }; - @Override - public void describeTo(Description description) { } - }; + public static class SubMatcher extends TypeSafeDiagnosingMatcher { + public SubMatcher() { + super(); + } - 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"); } + public SubMatcher(T expectedObject) { + super(expectedObject.getClass()); + } + + @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..9afa439a 100644 --- a/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/TypeSafeMatcherTest.java @@ -7,35 +7,37 @@ @SuppressWarnings("WeakerAccess") public final class TypeSafeMatcherTest { - private final Matcher matcher = new TypeSafeMatcherSubclass(); - - public static class TypeSafeMatcherSubclass extends TypeSafeMatcher { - @Override - public boolean matchesSafely(String item) { - return false; - } - - @Override - public void describeMismatchSafely(String item, Description mismatchDescription) { - mismatchDescription.appendText("The mismatch"); - } - - @Override - public void describeTo(Description description) { - } + private final Matcher matcher = new TypeSafeMatcherSubclass(); + + public static class TypeSafeMatcherSubclass extends TypeSafeMatcher { + @Override + public boolean matchesSafely(String item) { + return false; } - @Test public void - canDetermineMatcherTypeFromProtectedMatchesSafelyMethod() { - assertFalse(matcher.matches(null)); - assertFalse(matcher.matches(10)); + @Override + public void describeMismatchSafely(String item, Description mismatchDescription) { + mismatchDescription.appendText("The mismatch"); } - @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"); + @Override + public void describeTo(Description description) { } + } + + @Test + public void + 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"); + } } diff --git a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java index 11813106..5991dab4 100644 --- a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java +++ b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyTest.java @@ -15,34 +15,39 @@ */ 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); - } + 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..ffd4698c 100644 --- a/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java +++ b/hamcrest/src/test/java/org/hamcrest/beans/HasPropertyWithValueTest.java @@ -48,18 +48,18 @@ public void testMatchesBeanWithoutInfoWithMatchedNamedBooleanProperty() { 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); - } + assertMismatchDescription("No property \"nonExistentProperty\"", + hasProperty("nonExistentProperty", anything()), shouldNotMatch); + } public void testDoesNotMatchWriteOnlyProperty() { assertMismatchDescription("property \"writeOnlyProperty\" is not readable", - hasProperty("writeOnlyProperty", anything()), shouldNotMatch); + hasProperty("writeOnlyProperty", anything()), shouldNotMatch); } public void testMatchesPath() { @@ -78,10 +78,10 @@ public void testDescribeTo() { public void testMatchesPropertyAndValue() { assertMatches("property with value", hasProperty("property", anything()), beanWithInfo); } - + 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()); } @@ -91,9 +91,9 @@ public void testDescribesMissingPropertyMismatch() { 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()); } @@ -130,7 +130,9 @@ 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) { } @@ -145,25 +147,35 @@ public String toString() { 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 { 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 { @Override public PropertyDescriptor[] getPropertyDescriptors() { try { - return new PropertyDescriptor[] { - new PropertyDescriptor("property", BeanWithInfo.class, "property", null) - }; + return new PropertyDescriptor[]{ + new PropertyDescriptor("property", BeanWithInfo.class, "property", null) + }; } catch (IntrospectionException e) { throw new AssertionError("Introspection exception", e); } @@ -179,6 +191,8 @@ public String getBroken() { @SuppressWarnings("WeakerAccess") public static class BeanFailed extends RuntimeException { - public BeanFailed() { super("bean failed"); } + 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..2a9750fa 100644 --- a/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/beans/SamePropertyValuesAsTest.java @@ -10,8 +10,8 @@ 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() { return samePropertyValuesAs(expectedBean); @@ -20,10 +20,10 @@ protected Matcher createMatcher() { 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); + assertMismatchDescription("is incompatible type: ExampleBean", + samePropertyValuesAs((Object) aValue), actualBean); } public void test_reports_mismatch_on_first_property_difference() { @@ -36,7 +36,7 @@ public void test_reports_mismatch_on_first_property_difference() { } public void test_matches_beans_with_inheritance_but_no_extra_properties() { - assertMatches("sub type with same properties", + assertMatches("sub type with same properties", samePropertyValuesAs(expectedBean), new SubBeanWithNoExtraProperties("same", 1, aValue)); } @@ -62,20 +62,20 @@ public void test_accepts_missing_properties_to_ignore() { public void test_can_ignore_all_properties() { final ExampleBean differentBean = new ExampleBean("different", 2, new Value("not expected")); assertMatches( - "different property", - samePropertyValuesAs(expectedBean, "stringProperty", "intProperty", "valueProperty"), - differentBean); + "different property", + samePropertyValuesAs(expectedBean, "stringProperty", "intProperty", "valueProperty"), + differentBean); } public void testDescribesItself() { assertDescription( - "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ]", - samePropertyValuesAs(expectedBean)); + "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ]", + samePropertyValuesAs(expectedBean)); assertDescription( - "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ] ignoring [\"ignored1\", \"ignored2\"]", - samePropertyValuesAs(expectedBean, "ignored1", "ignored2")); + "same property values as ExampleBean [intProperty: <1>, stringProperty: \"same\", valueProperty: ] ignoring [\"ignored1\", \"ignored2\"]", + samePropertyValuesAs(expectedBean, "ignored1", "ignored2")); } public static class Value { @@ -84,12 +84,13 @@ public Value(Object value) { } public final Object value; + @Override public String toString() { return "Value " + value; } } - + @SuppressWarnings("unused") public static class ExampleBean { private String stringProperty; @@ -101,31 +102,39 @@ public ExampleBean(String stringProperty, int intProperty, Value valueProperty) this.intProperty = intProperty; this.valueProperty = valueProperty; } - + public String getStringProperty() { return stringProperty; } + public int getIntProperty() { return intProperty; } + 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) { super(stringProperty, intProperty, 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..94a1dc95 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInAnyOrderTest.java @@ -8,36 +8,36 @@ 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}); - } + @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..c11c7ff0 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/ArrayMatchingInOrderTest.java @@ -8,38 +8,38 @@ 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}); - } + @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..d7acee1c 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/HasItemInArrayTest.java @@ -8,39 +8,39 @@ 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", diff --git a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java index 01d9e3de..b0e5495d 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInAnyOrderTest.java @@ -8,36 +8,36 @@ 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}); - } + @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..b6fe0d58 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayContainingInOrderTest.java @@ -8,34 +8,34 @@ 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}); - } + @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..965ef162 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayTest.java @@ -11,49 +11,58 @@ @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"}); - } + @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..c9d06942 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsArrayWithSizeTest.java @@ -9,28 +9,28 @@ 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()); - } + @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..5945f482 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsCollectionWithSizeTest.java @@ -14,64 +14,64 @@ 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..d6ea082a 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyCollectionTest.java @@ -12,34 +12,35 @@ 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(); - } + @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..91ee789c 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsEmptyIterableTest.java @@ -11,34 +11,35 @@ public class IsEmptyIterableTest extends AbstractMatcherTest { - @Override - protected Matcher> createMatcher() { - return emptyIterable(); - } + @Override + protected Matcher> createMatcher() { + return emptyIterable(); + } - public void testMatchesAnEmptyIterable() { - assertMatches("empty iterable", createMatcher(), emptyCollection()); - } + public void testMatchesAnEmptyIterable() { + assertMatches("empty iterable", createMatcher(), emptyCollection()); + } - public void testDoesNotMatchAnIterableWithItems() { - assertDoesNotMatch("iterable with an item", createMatcher(), collectionOfValues()); - } + public void testDoesNotMatchAnIterableWithItems() { + assertDoesNotMatch("iterable with an item", createMatcher(), collectionOfValues()); + } - public void testHasAReadableDescription() { - assertDescription("an empty iterable", createMatcher()); - } + public void testHasAReadableDescription() { + assertDescription("an empty iterable", createMatcher()); + } - public void testCompiles() { - needs(IsEmptyIterable.emptyIterableOf(String.class)); - } + public void testCompiles() { + needs(IsEmptyIterable.emptyIterableOf(String.class)); + } - private void needs(@SuppressWarnings("unused") Matcher> bar) { } + private void needs(@SuppressWarnings("unused") Matcher> bar) { + } - private static Collection collectionOfValues() { - return new ArrayList(asList("one", "three")); - } + private static Collection collectionOfValues() { + return new ArrayList(asList("one", "three")); + } - private static Collection emptyCollection() { - return new ArrayList(); - } + 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..6be9a0bb 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsInTest.java @@ -8,37 +8,37 @@ 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)); - } + 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..2e751ab4 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInAnyOrderTest.java @@ -13,42 +13,42 @@ public class IsIterableContainingInAnyOrderTest extends AbstractMatcherTest { - @Override - protected Matcher createMatcher() { - return containsInAnyOrder(1, 2); - } - - public void testMatchesSingleItemIterable() { - assertMatches("single item", containsInAnyOrder(1), asList(1)); - } - - public void testDoesNotMatchEmpty() { - assertMismatchDescription("no item matches: <1>, <2> in []", containsInAnyOrder(1, 2), Collections.emptyList()); - } - - public void testMatchesIterableOutOfOrder() { - assertMatches("Out of order", containsInAnyOrder(1, 2), asList(2, 1)); - } - - public void testMatchesIterableInOrder() { - assertMatches("In order", containsInAnyOrder(1, 2), asList(1, 2)); - } - - public void testDoesNotMatchIfOneOfMultipleElementsMismatches() { - assertMismatchDescription("not matched: <4>", containsInAnyOrder(1, 2, 3), asList(1, 2, 4)); - } - - @SuppressWarnings("unchecked") - 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() { - assertMismatchDescription("no item matches: <4> in [<1>, <2>, <3>]", containsInAnyOrder(1, 2, 3, 4), asList(1, 2, 3)); - } - - public void testHasAReadableDescription() { - assertDescription("iterable with items [<1>, <2>] in any order", containsInAnyOrder(1, 2)); - } + @Override + protected Matcher createMatcher() { + return containsInAnyOrder(1, 2); + } + + public void testMatchesSingleItemIterable() { + assertMatches("single item", containsInAnyOrder(1), asList(1)); + } + + public void testDoesNotMatchEmpty() { + assertMismatchDescription("no item matches: <1>, <2> in []", containsInAnyOrder(1, 2), Collections.emptyList()); + } + + public void testMatchesIterableOutOfOrder() { + assertMatches("Out of order", containsInAnyOrder(1, 2), asList(2, 1)); + } + + public void testMatchesIterableInOrder() { + assertMatches("In order", containsInAnyOrder(1, 2), asList(1, 2)); + } + + public void testDoesNotMatchIfOneOfMultipleElementsMismatches() { + assertMismatchDescription("not matched: <4>", containsInAnyOrder(1, 2, 3), asList(1, 2, 4)); + } + + @SuppressWarnings("unchecked") + 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() { + assertMismatchDescription("no item matches: <4> in [<1>, <2>, <3>]", containsInAnyOrder(1, 2, 3, 4), asList(1, 2, 3)); + } + + 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..0ce00e60 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInOrderTest.java @@ -14,64 +14,77 @@ @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)); + // 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); - } + @Override + protected Matcher createMatcher() { + return contains(1, 2); + } - public void testMatchingSingleItemIterable() throws Exception { - assertMatches("Single item iterable", contains(1), singletonList(1)); - } + 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 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 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 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 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 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 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 void testHasAReadableDescription() { + assertDescription("iterable containing [<1>, <2>]", contains(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 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..2c2a4eea 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInRelativeOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableContainingInRelativeOrderTest.java @@ -13,81 +13,94 @@ @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)); + // 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); - } + @Override + protected Matcher createMatcher() { + return containsInRelativeOrder(1, 2); + } - public void testMatchingSingleItemIterable() throws Exception { - assertMatches("Single item iterable", containsInRelativeOrder(1), asList(1)); - } + 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 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 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 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 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 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 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 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 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 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 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 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 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 class WithValue { + private final int value; - public static WithValue make(int value) { - return new WithValue(value); + public WithValue(int value) { + this.value = 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 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..7bd4c8dc 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsIterableWithSizeTest.java @@ -10,28 +10,28 @@ public class IsIterableWithSizeTest extends AbstractMatcherTest { - @Override - protected Matcher createMatcher() { - return iterableWithSize(7); - } - - public void testMatchesEmptyIterable() throws Exception { - assertMatches("Empty iterable", iterableWithSize(0), Collections.emptyList()); - } - - public void testMatchingSingleItemIterable() throws Exception { - assertMatches("Single item iterable", iterableWithSize(1), Arrays.asList(1)); - } - - public void testMatchingMultipleItemIterable() throws Exception { - assertMatches("Multiple item iterable", iterableWithSize(3), Arrays.asList(1, 2, 3)); - } - - public void testDoesNotMatchIncorrectSize() throws Exception { - assertDoesNotMatch("Incorrect size", iterableWithSize(3), Arrays.asList(1)); - } - - public void testHasAReadableDescription() { - assertDescription("an iterable with size <4>", iterableWithSize(4)); - } + @Override + protected Matcher createMatcher() { + return iterableWithSize(7); + } + + public void testMatchesEmptyIterable() throws Exception { + assertMatches("Empty iterable", iterableWithSize(0), Collections.emptyList()); + } + + public void testMatchingSingleItemIterable() throws Exception { + assertMatches("Single item iterable", iterableWithSize(1), Arrays.asList(1)); + } + + public void testMatchingMultipleItemIterable() throws Exception { + assertMatches("Multiple item iterable", iterableWithSize(3), Arrays.asList(1, 2, 3)); + } + + public void testDoesNotMatchIncorrectSize() throws Exception { + assertDoesNotMatch("Incorrect size", iterableWithSize(3), Arrays.asList(1)); + } + + 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..0e15e995 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingKeyTest.java @@ -12,28 +12,28 @@ public class IsMapContainingKeyTest extends AbstractMatcherTest { - @Override - protected Matcher createMatcher() { - return hasKey("foo"); - } - - 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(); - map.put("a", 1); - map.put("b", 2); - map.put("c", 3); - - assertMatches("Matches a", hasKey("a"), map); - assertMatches("Matches c", hasKey("c"), map); - } - + @Override + protected Matcher createMatcher() { + return hasKey("foo"); + } + + 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(); + 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() { @@ -46,39 +46,39 @@ public void testMatchesMapContainingKey() { // assertMatches("Matches c", hasKey("c"), map); // } - public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception { - Map map = new HashMap(); - map.put(1, "A"); - map.put(2, "B"); + public void testMatchesMapContainingKeyWithIntegerKeys() throws Exception { + Map map = new HashMap(); + map.put(1, "A"); + map.put(2, "B"); - assertThat(map, hasKey(1)); - } + assertThat(map, hasKey(1)); + } - public void testMatchesMapContainingKeyWithNumberKeys() throws Exception { - Map map = new HashMap(); - map.put(1, "A"); - map.put(2, "B"); + 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! + // TODO: work out the correct sprinkling of wildcards to get this to work! // assertThat(map, hasKey(1)); - } - - public void testHasReadableDescription() { - assertDescription("map containing [\"a\"->ANYTHING]", hasKey("a")); - } - - public void testDoesNotMatchEmptyMap() { - assertMismatchDescription("map was []", hasKey("Foo"), new HashMap()); - } - - 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); - } + } + + public void testHasReadableDescription() { + assertDescription("map containing [\"a\"->ANYTHING]", hasKey("a")); + } + + public void testDoesNotMatchEmptyMap() { + assertMismatchDescription("map was []", hasKey("Foo"), new HashMap()); + } + + 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..08f42d81 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingTest.java @@ -13,37 +13,37 @@ 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)))); - } + @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..66a187de 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapContainingValueTest.java @@ -12,35 +12,35 @@ 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); - } + @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..fb8ddd62 100644 --- a/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/collection/IsMapWithSizeTest.java @@ -12,71 +12,71 @@ 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..c9377ea3 100644 --- a/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherBuilderTest.java @@ -12,117 +12,117 @@ 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"; - } - }; - + 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..45a89867 100644 --- a/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java +++ b/hamcrest/src/test/java/org/hamcrest/comparator/ComparatorMatcherTest.java @@ -12,76 +12,76 @@ 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); + @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..c4b883ed 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/AllOfTest.java @@ -15,56 +15,63 @@ 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..800a81e5 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/AnyOfTest.java @@ -12,51 +12,57 @@ 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("."))); - } + @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..7490b398 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/CombinableTest.java @@ -9,60 +9,68 @@ 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))); + 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..28a8db3d 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/DescribedAsTest.java @@ -10,40 +10,45 @@ 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); - } + @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..d6d06c53 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/EveryTest.java @@ -12,33 +12,38 @@ 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")); - } + 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..b75f7901 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsAnythingTest.java @@ -11,34 +11,36 @@ 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)); - } + 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..fdbf1b25 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsCollectionContainingTest.java @@ -16,88 +16,88 @@ 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 - { - 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 - public void describeTo(Description description) { - description.appendText("mismatchable: " + string); - } - }; - } + @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() { + @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/IsEqualTest.java b/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java index d3ff21c5..d2d577d7 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsEqualTest.java @@ -9,149 +9,161 @@ 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)); - } + @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..8c5d976f 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsInstanceOfTest.java @@ -9,61 +9,68 @@ 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..292bcb9c 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsIterableContainingTest.java @@ -16,92 +16,100 @@ 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); - } - }; - } + + @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..0df7e55b 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsNotTest.java @@ -10,33 +10,37 @@ 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")); - } + @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..d3b0284e 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsNullTest.java @@ -10,34 +10,37 @@ 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 - } + 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..cd515d48 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsSameTest.java @@ -10,39 +10,44 @@ 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)); - } + @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..3099e616 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/IsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/IsTest.java @@ -10,42 +10,47 @@ 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); - } + @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..c648c7aa 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java +++ b/hamcrest/src/test/java/org/hamcrest/core/SampleBaseClass.java @@ -1,24 +1,24 @@ package org.hamcrest.core; public class SampleBaseClass { - String value; + 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..89a28dcf 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java +++ b/hamcrest/src/test/java/org/hamcrest/core/SampleSubClass.java @@ -1,9 +1,9 @@ package org.hamcrest.core; public class SampleSubClass extends SampleBaseClass { - - public SampleSubClass(String value) { - super(value); - } + + 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..908e4e1a 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringContainsTest.java @@ -8,38 +8,38 @@ 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); - } + 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..7d4db781 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringEndsWithTest.java @@ -8,38 +8,38 @@ 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); - } + 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..05139214 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringMatchingTest.java @@ -12,21 +12,25 @@ * @author Steve Freeman 2016 http://www.hamcrest.com */ public class StringMatchingTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); + @Rule + public final ExpectedException thrown = ExpectedException.none(); - @Test public void + @Test + public void startsWithFailsWithNullSubstring() { thrown.expect(IllegalArgumentException.class); startsWith(null); } - @Test public void + @Test + public void endWithFailsWithNullSubstring() { thrown.expect(IllegalArgumentException.class); endsWith(null); } - @Test public void + @Test + public void 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..2326ae1f 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringRegularExpressionTest.java @@ -12,7 +12,9 @@ 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() { diff --git a/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java b/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java index f093acb4..6413b588 100644 --- a/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java +++ b/hamcrest/src/test/java/org/hamcrest/core/StringStartsWithTest.java @@ -8,39 +8,39 @@ 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"); - } + 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..11029fc5 100644 --- a/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java +++ b/hamcrest/src/test/java/org/hamcrest/io/FileMatchersTest.java @@ -11,81 +11,81 @@ @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); + 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..fc02a2fc 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/BigDecimalCloseToTest.java @@ -7,7 +7,7 @@ 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 @@ -15,7 +15,7 @@ protected Matcher createMatcher() { BigDecimal irrelevant = new BigDecimal("0.01"); return closeTo(irrelevant, irrelevant); } - + public void testEvaluatesToTrueIfArgumentIsEqualToABigDecimalWithinSomeError() { assertTrue(matcher.matches(new BigDecimal("1.0"))); assertTrue(matcher.matches(new BigDecimal("0.5"))); @@ -26,7 +26,7 @@ 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() { assertTrue(matcher.matches(new BigDecimal("1.000000"))); assertTrue(matcher.matches(new BigDecimal("0.500000"))); diff --git a/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java b/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java index 8b0e244b..e451609e 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/IsCloseToTest.java @@ -9,24 +9,24 @@ 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..d9da0296 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/IsNanTest.java @@ -8,36 +8,42 @@ 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); - } + @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..b1325a15 100644 --- a/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java +++ b/hamcrest/src/test/java/org/hamcrest/number/OrderingComparisonTest.java @@ -11,70 +11,71 @@ public class OrderingComparisonTest extends AbstractMatcherTest { - @Override - protected Matcher createMatcher() { - return greaterThan(1); + @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 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/object/HasEqualsValuesTest.java b/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java index 44aa7619..7d1feb88 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/HasEqualsValuesTest.java @@ -5,52 +5,52 @@ @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); - - @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_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_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 WithPublicFields(char c, int i, String s) { - super(c); - this.i = i; - this.s = s; - } + 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; + } + + 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_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 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 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..37fd9474 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/HasToStringTest.java @@ -8,48 +8,53 @@ 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"); + 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..cb3bf31e 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/IsCompatibleTypeTest.java @@ -7,47 +7,47 @@ import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; public class IsCompatibleTypeTest extends AbstractMatcherTest { - static class BaseClass { - } + 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..eda60b38 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/IsEventFromTest.java @@ -11,42 +11,42 @@ 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); + @Override + protected Matcher createMatcher() { + return eventFrom(null); + } - assertThat(ev, isEventMatcher); - assertMismatchDescription("source was \"source 2\"", isEventMatcher, ev2); - } - - private static class DerivedEvent extends EventObject { - private static final long serialVersionUID = 1L; + public void testEvaluatesToTrueIfArgumentIsAnEventObjectFiredByASpecifiedSource() { + Object o = "Source"; + EventObject ev = new EventObject(o); + EventObject ev2 = new EventObject("source 2"); - public DerivedEvent(Object source) { - super(source); - } - } + Matcher isEventMatcher = eventFrom(o); - 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()); + assertThat(ev, isEventMatcher); + assertMismatchDescription("source was \"source 2\"", isEventMatcher, ev2); + } - Matcher isEventMatcher = IsEventFrom.eventFrom(DerivedEvent.class, o); + private static class DerivedEvent extends EventObject { + private static final long serialVersionUID = 1L; - 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 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..96a804fd 100644 --- a/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java +++ b/hamcrest/src/test/java/org/hamcrest/object/MatchesPatternTest.java @@ -10,50 +10,50 @@ 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 ); - } + @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..9d586351 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/CharSequenceLengthTest.java @@ -12,27 +12,27 @@ */ public class CharSequenceLengthTest extends AbstractMatcherTest { - @Override - protected Matcher createMatcher() { - return hasLength(4); - } + @Override + protected Matcher createMatcher() { + return hasLength(4); + } - public void test_matchesExactLengthOf_CharSequence() { - final Matcher matcher = hasLength(4); - assertMatches(matcher, "aaaa"); - assertMatches(matcher, "a b "); + public void test_matchesExactLengthOf_CharSequence() { + final Matcher matcher = hasLength(4); + assertMatches(matcher, "aaaa"); + assertMatches(matcher, "a b "); - assertMismatchDescription("length was <6>", matcher, "aaaaaa"); - } + assertMismatchDescription("length was <6>", matcher, "aaaaaa"); + } - public void test_matchesRelativeLengthOf_CharSequence() { - final Matcher matcher = hasLength(lessThan(4)); - assertMatches(matcher, "aaa"); - assertMatches(matcher, "a b"); + 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"); - } + 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..ef23f3e8 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java @@ -9,47 +9,54 @@ 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"); - } + @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..107ecc04 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsEmptyStringTest.java @@ -9,47 +9,54 @@ 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"); - } + @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..2b27fe6d 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java @@ -7,38 +7,38 @@ 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); - } + 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..40971f27 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/IsEqualIgnoringCaseTest.java @@ -8,55 +8,62 @@ 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"); - } + @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..c779a198 100644 --- a/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java +++ b/hamcrest/src/test/java/org/hamcrest/text/StringContainsInOrderTest.java @@ -8,26 +8,26 @@ 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); - } + 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..6ffd52ee 100644 --- a/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java +++ b/hamcrest/src/test/java/org/hamcrest/xml/HasXPathTest.java @@ -25,123 +25,133 @@ */ 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); + 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 - 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")); - } - - @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); + }; + + @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"); + } catch (IllegalArgumentException expectedException) { + // expected exception } - - 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); - } + } + + @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())); + } catch (Exception e) { + throw new IllegalStateException(e); } + } }