Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge remote branch 'remotes/upstream/master'

Conflicts:
	src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java
  • Loading branch information...
commit 6caeeb1e1579cae1cd9ede58f38186e07da7f295 2 parents be8d4ee + 2e53904
Mark Michaelis mmichaelis authored
Showing with 1,029 additions and 575 deletions.
  1. +1 −1  .classpath
  2. +0 −1  README.html
  3. +3 −2 build.xml
  4. +1 −1  build/maven/junit-pom-template.xml
  5. +1 −1  build/maven/sample_project_template/pom.xml
  6. +1 −1  build/profile_junit.sh
  7. BIN  lib/hamcrest-core-1.1.jar
  8. BIN  lib/hamcrest-core-1.3-sources.jar
  9. BIN  lib/hamcrest-core-1.3.jar
  10. +4 −19 src/main/java/org/junit/Assert.java
  11. +2 −2 src/main/java/org/junit/Assume.java
  12. +1 −1  src/main/java/org/junit/experimental/results/ResultMatchers.java
  13. +8 −3 src/main/java/org/junit/experimental/theories/Theories.java
  14. +26 −12 src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java
  15. +0 −22 src/main/java/org/junit/internal/matchers/CauseMatcher.java
  16. +0 −34 src/main/java/org/junit/internal/matchers/CombinableMatcher.java
  17. +0 −24 src/main/java/org/junit/internal/matchers/Each.java
  18. +0 −67 src/main/java/org/junit/internal/matchers/IsCollectionContaining.java
  19. +56 −0 src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java
  20. +0 −31 src/main/java/org/junit/internal/matchers/StringContains.java
  21. +0 −28 src/main/java/org/junit/internal/matchers/SubstringMatcher.java
  22. +37 −0 src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java
  23. +37 −0 src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java
  24. +3 −0  src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java
  25. +60 −27 src/main/java/org/junit/matchers/JUnitMatchers.java
  26. +17 −48 src/main/java/org/junit/rules/ExpectedException.java
  27. +46 −0 src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java
  28. +1 −1  src/main/java/org/junit/rules/RuleChain.java
  29. +20 −13 src/main/java/org/junit/rules/TemporaryFolder.java
  30. +50 −7 src/main/java/org/junit/rules/TestWatcher.java
  31. +1 −1  src/main/java/org/junit/rules/Timeout.java
  32. +1 −1  src/main/java/org/junit/rules/Verifier.java
  33. +29 −4 src/main/java/org/junit/runner/Description.java
  34. +2 −2 src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java
  35. +121 −0 src/main/java/org/junit/runners/Parameterized.java
  36. +6 −6 src/test/java/org/junit/internal/MethodSorterTest.java
  37. +37 −0 src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java
  38. +4 −8 src/test/java/org/junit/tests/AllTests.java
  39. +6 −16 src/test/java/org/junit/tests/assertion/AssertionTest.java
  40. +0 −71 src/test/java/org/junit/tests/assertion/BothTest.java
  41. +0 −18 src/test/java/org/junit/tests/assertion/CauseMatcherTest.java
  42. +0 −13 src/test/java/org/junit/tests/assertion/EachTest.java
  43. +1 −1  src/test/java/org/junit/tests/experimental/AssumptionTest.java
  44. +1 −1  src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java
  45. +42 −0 src/test/java/org/junit/tests/experimental/max/DescriptionTest.java
  46. +1 −1  src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java
  47. +1 −1  src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java
  48. +1 −1  src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java
  49. +1 −2  src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java
  50. +1 −1  src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java
  51. +3 −3 src/test/java/org/junit/tests/experimental/rules/EventCollector.java
  52. +15 −28 src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionTest.java
  53. +2 −2 src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java
  54. +2 −2 src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java
  55. +56 −18 src/test/java/org/junit/tests/experimental/rules/TemporaryFolderUsageTest.java
  56. +9 −0 src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java
  57. +80 −0 src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java
  58. +1 −1  src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java
  59. +4 −4 src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java
  60. +4 −5 src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java
  61. +1 −1  src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java
  62. +57 −0 src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataPointsMethod.java
  63. +34 −4 src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java
  64. +1 −1  src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java
  65. +3 −4 src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java
  66. +1 −1  src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java
  67. +1 −1  src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java
  68. +119 −1 src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java
  69. +1 −1  src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java
  70. +3 −3 src/test/java/org/junit/tests/running/methods/AnnotationTest.java
  71. +1 −1  src/test/java/org/junit/tests/running/methods/TimeoutTest.java
2  .classpath
View
@@ -3,6 +3,6 @@
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
- <classpathentry exported="true" kind="lib" path="lib/hamcrest-core-1.1.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/hamcrest-core-1.3.jar" sourcepath="lib/hamcrest-core-1.3-sources.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
1  README.html
View
@@ -2,7 +2,6 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="Author" content="Erich Gamma, Kent Beck, and David Saff">
<title>JUnit 4.6</title>
</head>
5 build.xml
View
@@ -28,7 +28,8 @@
<property name="javadocdir" location="${dist}/javadoc" />
<property name="javadoczip" location="${dist}-javadoc.zip" />
- <property name="hamcrestlib" location="lib/hamcrest-core-1.1.jar" />
+ <property name="hamcrestlib" location="lib/hamcrest-core-1.3.jar" />
+ <property name="hamcrestlibsources" location="lib/hamcrest-core-1.3-sources.jar" />
<property name="hamcrestsrc" location="${dist}/temp.hamcrest.source" />
<property name="maven.deploy.goal" value="org.apache.maven.plugins:maven-gpg-plugin:1.1:sign-and-deploy-file" />
@@ -125,7 +126,7 @@
</target>
<target name="unjar.hamcrest">
- <unjar src="${hamcrestlib}" dest="${hamcrestsrc}" />
+ <unjar src="${hamcrestlibsources}" dest="${hamcrestsrc}" />
</target>
<target name="release-notes">
2  build/maven/junit-pom-template.xml
View
@@ -58,7 +58,7 @@
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
- <version>1.1</version>
+ <version>1.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
2  build/maven/sample_project_template/pom.xml
View
@@ -9,7 +9,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <version.hamcrest>1.2.1</version.hamcrest>
+ <version.hamcrest>1.3</version.hamcrest>
</properties>
<dependencies>
2  build/profile_junit.sh
View
@@ -1,2 +1,2 @@
-java -classpath ../bin:../lib/hamcrest-core-1.1.jar -agentlib:hprof=cpu=samples,depth=18 org.junit.runner.JUnitCore org.junit.tests.AllTests
+java -classpath ../bin:../lib/hamcrest-core-1.3.jar -agentlib:hprof=cpu=samples,depth=18 org.junit.runner.JUnitCore org.junit.tests.AllTests
cat java.hprof.txt
BIN  lib/hamcrest-core-1.1.jar
View
Binary file not shown
BIN  lib/hamcrest-core-1.3-sources.jar
View
Binary file not shown
BIN  lib/hamcrest-core-1.3.jar
View
Binary file not shown
23 src/main/java/org/junit/Assert.java
View
@@ -1,8 +1,7 @@
package org.junit;
-import org.hamcrest.Description;
import org.hamcrest.Matcher;
-import org.hamcrest.StringDescription;
+import org.hamcrest.MatcherAssert;
import org.junit.internal.ArrayComparisonFailure;
import org.junit.internal.ExactComparisonCriteria;
import org.junit.internal.InexactComparisonCriteria;
@@ -919,7 +918,7 @@ public static void assertEquals(Object[] expecteds, Object[] actuals) {
* values
*
* @see org.hamcrest.CoreMatchers
- * @see org.junit.matchers.JUnitMatchers
+ * @see org.hamcrest.MatcherAssert
*/
public static <T> void assertThat(T actual, Matcher<? super T> matcher) {
assertThat("", actual, matcher);
@@ -931,7 +930,6 @@ public static void assertEquals(Object[] expecteds, Object[] actuals) {
* the reason and information about the matcher and failing value. Example:
*
* <pre>
- * :
* assertThat(&quot;Help! Integers don't work&quot;, 0, is(1)); // fails:
* // failure message:
* // Help! Integers don't work
@@ -957,23 +955,10 @@ public static void assertEquals(Object[] expecteds, Object[] actuals) {
* values
*
* @see org.hamcrest.CoreMatchers
- * @see org.junit.matchers.JUnitMatchers
+ * @see org.hamcrest.MatcherAssert
*/
public static <T> void assertThat(String reason, T actual,
Matcher<? super T> matcher) {
- if (!matcher.matches(actual)) {
- Description description= new StringDescription();
- description.appendText(reason);
- description.appendText("\nExpected: ");
- description.appendDescriptionOf(matcher);
- description.appendText("\n got: ");
- description.appendValue(actual);
- description.appendText("\n");
- java.lang.AssertionError assertionError= new java.lang.AssertionError(
- description.toString());
- if (actual instanceof Throwable)
- assertionError.initCause((Throwable) actual);
- throw assertionError;
- }
+ MatcherAssert.assertThat(reason, actual, matcher);
}
}
4 src/main/java/org/junit/Assume.java
View
@@ -1,12 +1,12 @@
package org.junit;
import static java.util.Arrays.asList;
+import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import org.hamcrest.Matcher;
import org.junit.internal.AssumptionViolatedException;
-import org.junit.internal.matchers.Each;
/**
* A set of methods useful for stating assumptions about the conditions in which a test is meaningful.
@@ -45,7 +45,7 @@ public static void assumeTrue(boolean b) {
* @param objects
*/
public static void assumeNotNull(Object... objects) {
- assumeThat(asList(objects), Each.each(notNullValue()));
+ assumeThat(asList(objects), everyItem(notNullValue()));
}
/**
2  src/main/java/org/junit/experimental/results/ResultMatchers.java
View
@@ -3,7 +3,7 @@
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
+import org.hamcrest.TypeSafeMatcher;
/**
* Matchers on a PrintableResult, to enable JUnit self-tests.
11 src/main/java/org/junit/experimental/theories/Theories.java
View
@@ -34,9 +34,14 @@ protected void collectInitializationErrors(List<Throwable> errors) {
private void validateDataPointFields(List<Throwable> errors) {
Field[] fields= getTestClass().getJavaClass().getDeclaredFields();
- for (Field each : fields)
- if (each.getAnnotation(DataPoint.class) != null && !Modifier.isStatic(each.getModifiers()))
- errors.add(new Error("DataPoint field " + each.getName() + " must be static"));
+ for (Field field : fields) {
+ if (field.getAnnotation(DataPoint.class) == null)
+ continue;
+ if (!Modifier.isStatic(field.getModifiers()))
+ errors.add(new Error("DataPoint field " + field.getName() + " must be static"));
+ if (!Modifier.isPublic(field.getModifiers()))
+ errors.add(new Error("DataPoint field " + field.getName() + " must be public"));
+ }
}
@Override
38 src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java
View
@@ -1,6 +1,3 @@
-/**
- *
- */
package org.junit.experimental.theories.internal;
import java.lang.reflect.Array;
@@ -65,40 +62,42 @@ public AllMembersSupplier(TestClass type) {
addFields(sig, list);
addSinglePointMethods(sig, list);
- addMultiPointMethods(list);
+ addMultiPointMethods(sig, list);
return list;
}
- private void addMultiPointMethods(List<PotentialAssignment> list) {
+ private void addMultiPointMethods(ParameterSignature sig, List<PotentialAssignment> list) {
for (FrameworkMethod dataPointsMethod : fClass
.getAnnotatedMethods(DataPoints.class))
try {
- addArrayValues(dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null));
+ addMultiPointArrayValues(sig, dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null));
} catch (Throwable e) {
// ignore and move on
}
}
- @SuppressWarnings("deprecation")
private void addSinglePointMethods(ParameterSignature sig,
- List<PotentialAssignment> list) {
+ List<PotentialAssignment> list) {
for (FrameworkMethod dataPointMethod : fClass
.getAnnotatedMethods(DataPoint.class)) {
- Class<?> type= sig.getType();
- if ((dataPointMethod.producesType(type)))
+ if (isCorrectlyTyped(sig, dataPointMethod.getType()))
list.add(new MethodParameterValue(dataPointMethod));
}
}
private void addFields(ParameterSignature sig,
- List<PotentialAssignment> list) {
+ List<PotentialAssignment> list) {
for (final Field field : fClass.getJavaClass().getFields()) {
if (Modifier.isStatic(field.getModifiers())) {
Class<?> type= field.getType();
if (sig.canAcceptArrayType(type)
&& field.getAnnotation(DataPoints.class) != null) {
- addArrayValues(field.getName(), list, getStaticFieldValue(field));
+ try {
+ addArrayValues(field.getName(), list, getStaticFieldValue(field));
+ } catch (Throwable e) {
+ // ignore and move on
+ }
} else if (sig.canAcceptType(type)
&& field.getAnnotation(DataPoint.class) != null) {
list.add(PotentialAssignment
@@ -113,6 +112,21 @@ private void addArrayValues(String name, List<PotentialAssignment> list, Object
list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i)));
}
+ private void addMultiPointArrayValues(ParameterSignature sig, String name, List<PotentialAssignment> list,
+ Object array) throws Throwable {
+ for (int i= 0; i < Array.getLength(array); i++) {
+ if (!isCorrectlyTyped(sig, Array.get(array, i).getClass())) {
+ return;
+ }
+ list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i)));
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private boolean isCorrectlyTyped(ParameterSignature parameterSignature, Class<?> type) {
+ return parameterSignature.canAcceptType(type);
+ }
+
private Object getStaticFieldValue(final Field field) {
try {
return field.get(null);
22 src/main/java/org/junit/internal/matchers/CauseMatcher.java
View
@@ -1,22 +0,0 @@
-package org.junit.internal.matchers;
-
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-
-public class CauseMatcher extends TypeSafeMatcher<Throwable> {
- private final Matcher<? super Throwable> fCauseMatcher;
-
- public CauseMatcher(final Matcher<? super Throwable> causeMatcher) {
- fCauseMatcher= causeMatcher;
- }
-
- public void describeTo(Description description) {
- description.appendText("caused by ");
- fCauseMatcher.describeTo(description);
- }
-
- @Override
- public boolean matchesSafely(Throwable item) {
- return fCauseMatcher.matches(item.getCause());
- }
-}
34 src/main/java/org/junit/internal/matchers/CombinableMatcher.java
View
@@ -1,34 +0,0 @@
-package org.junit.internal.matchers;
-
-import static org.hamcrest.CoreMatchers.allOf;
-import static org.hamcrest.CoreMatchers.anyOf;
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-
-public class CombinableMatcher<T> extends BaseMatcher<T> {
-
- private final Matcher<? extends T> fMatcher;
-
- public CombinableMatcher(Matcher<? extends T> matcher) {
- fMatcher= matcher;
- }
-
- public boolean matches(Object item) {
- return fMatcher.matches(item);
- }
-
- public void describeTo(Description description) {
- description.appendDescriptionOf(fMatcher);
- }
-
- @SuppressWarnings("unchecked")
- public CombinableMatcher<T> and(Matcher<? extends T> matcher) {
- return new CombinableMatcher<T>(allOf(matcher, fMatcher));
- }
-
- @SuppressWarnings("unchecked")
- public CombinableMatcher<T> or(Matcher<? extends T> matcher) {
- return new CombinableMatcher<T>(anyOf(matcher, fMatcher));
- }
-}
24 src/main/java/org/junit/internal/matchers/Each.java
View
@@ -1,24 +0,0 @@
-package org.junit.internal.matchers;
-
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.internal.matchers.IsCollectionContaining.hasItem;
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-
-public class Each {
- public static <T> Matcher<Iterable<T>> each(final Matcher<T> individual) {
- final Matcher<Iterable<T>> allItemsAre = not(hasItem(not(individual)));
-
- return new BaseMatcher<Iterable<T>>() {
- public boolean matches(Object item) {
- return allItemsAre.matches(item);
- }
-
- public void describeTo(Description description) {
- description.appendText("each ");
- individual.describeTo(description);
- }
- };
- }
-}
67 src/main/java/org/junit/internal/matchers/IsCollectionContaining.java
View
@@ -1,67 +0,0 @@
-package org.junit.internal.matchers;
-
-import static org.hamcrest.core.AllOf.allOf;
-import static org.hamcrest.core.IsEqual.equalTo;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-
-// Copied (hopefully temporarily) from hamcrest-library
-public class IsCollectionContaining<T> extends TypeSafeMatcher<Iterable<T>> {
- private final Matcher<? extends T> elementMatcher;
-
- public IsCollectionContaining(Matcher<? extends T> elementMatcher) {
- this.elementMatcher = elementMatcher;
- }
-
- @Override
- public boolean matchesSafely(Iterable<T> collection) {
- for (T item : collection) {
- if (elementMatcher.matches(item)){
- return true;
- }
- }
- return false;
- }
-
- public void describeTo(Description description) {
- description
- .appendText("a collection containing ")
- .appendDescriptionOf(elementMatcher);
- }
-
- @Factory
- public static <T> Matcher<Iterable<T>> hasItem(Matcher<? extends T> elementMatcher) {
- return new IsCollectionContaining<T>(elementMatcher);
- }
-
- @Factory
- public static <T> Matcher<Iterable<T>> hasItem(T element) {
- return hasItem(equalTo(element));
- }
-
- @Factory
- public static <T> Matcher<Iterable<T>> hasItems(Matcher<? extends T>... elementMatchers) {
- Collection<Matcher<? extends Iterable<T>>> all
- = new ArrayList<Matcher<? extends Iterable<T>>>(elementMatchers.length);
- for (Matcher<? extends T> elementMatcher : elementMatchers) {
- all.add(hasItem(elementMatcher));
- }
- return allOf(all);
- }
-
- @Factory
- public static <T> Matcher<Iterable<T>> hasItems(T... elements) {
- Collection<Matcher<? extends Iterable<T>>> all
- = new ArrayList<Matcher<? extends Iterable<T>>>(elements.length);
- for (T element : elements) {
- all.add(hasItem(element));
- }
- return allOf(all);
- }
-
-}
56 src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java
View
@@ -0,0 +1,56 @@
+package org.junit.internal.matchers;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+/**
+ * A matcher that delegates to throwableMatcher and in addition appends the
+ * stacktrace of the actual Throwable in case of a mismatch.
+ */
+public class StacktracePrintingMatcher<T extends Throwable> extends
+ org.hamcrest.TypeSafeMatcher<T> {
+
+ private final Matcher<T> fThrowableMatcher;
+
+ public StacktracePrintingMatcher(Matcher<T> throwableMatcher) {
+ fThrowableMatcher= throwableMatcher;
+ }
+
+ public void describeTo(Description description) {
+ fThrowableMatcher.describeTo(description);
+ }
+
+ @Override
+ protected boolean matchesSafely(T item) {
+ return fThrowableMatcher.matches(item);
+ }
+
+ @Override
+ protected void describeMismatchSafely(T item, Description description) {
+ fThrowableMatcher.describeMismatch(item, description);
+ description.appendText("\nStacktrace was: ");
+ description.appendText(readStacktrace(item));
+ }
+
+ private String readStacktrace(Throwable throwable) {
+ StringWriter stringWriter= new StringWriter();
+ throwable.printStackTrace(new PrintWriter(stringWriter));
+ return stringWriter.toString();
+ }
+
+ @Factory
+ public static <T extends Throwable> Matcher<T> isThrowable(
+ Matcher<T> throwableMatcher) {
+ return new StacktracePrintingMatcher<T>(throwableMatcher);
+ }
+
+ @Factory
+ public static <T extends Exception> Matcher<T> isException(
+ Matcher<T> exceptionMatcher) {
+ return new StacktracePrintingMatcher<T>(exceptionMatcher);
+ }
+}
31 src/main/java/org/junit/internal/matchers/StringContains.java
View
@@ -1,31 +0,0 @@
-/* Copyright (c) 2000-2006 hamcrest.org
- */
-package org.junit.internal.matchers;
-
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-
-/**
- * Tests if the argument is a string that contains a substring.
- */
-public class StringContains extends SubstringMatcher {
- public StringContains(String substring) {
- super(substring);
- }
-
- @Override
- protected boolean evalSubstringOf(String s) {
- return s.indexOf(substring) >= 0;
- }
-
- @Override
- protected String relationship() {
- return "containing";
- }
-
- @Factory
- public static Matcher<String> containsString(String substring) {
- return new StringContains(substring);
- }
-
-}
28 src/main/java/org/junit/internal/matchers/SubstringMatcher.java
View
@@ -1,28 +0,0 @@
-package org.junit.internal.matchers;
-
-import org.hamcrest.Description;
-
-public abstract class SubstringMatcher extends TypeSafeMatcher<String> {
-
- protected final String substring;
-
- protected SubstringMatcher(final String substring) {
- this.substring = substring;
- }
-
- @Override
- public boolean matchesSafely(String item) {
- return evalSubstringOf(item);
- }
-
- public void describeTo(Description description) {
- description.appendText("a string ")
- .appendText(relationship())
- .appendText(" ")
- .appendValue(substring);
- }
-
- protected abstract boolean evalSubstringOf(String string);
-
- protected abstract String relationship();
-}
37 src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java
View
@@ -0,0 +1,37 @@
+package org.junit.internal.matchers;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
+
+public class ThrowableCauseMatcher<T extends Throwable> extends
+ TypeSafeMatcher<T> {
+
+ private final Matcher<T> fMatcher;
+
+ public ThrowableCauseMatcher(Matcher<T> matcher) {
+ fMatcher= matcher;
+ }
+
+ public void describeTo(Description description) {
+ description.appendText("exception with cause ");
+ description.appendDescriptionOf(fMatcher);
+ }
+
+ @Override
+ protected boolean matchesSafely(T item) {
+ return fMatcher.matches(item.getCause());
+ }
+
+ @Override
+ protected void describeMismatchSafely(T item, Description description) {
+ description.appendText("cause ");
+ fMatcher.describeMismatch(item.getCause(), description);
+ }
+
+ @Factory
+ public static <T extends Throwable> Matcher<T> hasCause(final Matcher<T> matcher) {
+ return new ThrowableCauseMatcher<T>(matcher);
+ }
+}
37 src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java
View
@@ -0,0 +1,37 @@
+package org.junit.internal.matchers;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
+
+public class ThrowableMessageMatcher<T extends Throwable> extends
+ TypeSafeMatcher<T> {
+
+ private final Matcher<String> fMatcher;
+
+ public ThrowableMessageMatcher(Matcher<String> matcher) {
+ fMatcher= matcher;
+ }
+
+ public void describeTo(Description description) {
+ description.appendText("exception with message ");
+ description.appendDescriptionOf(fMatcher);
+ }
+
+ @Override
+ protected boolean matchesSafely(T item) {
+ return fMatcher.matches(item.getMessage());
+ }
+
+ @Override
+ protected void describeMismatchSafely(T item, Description description) {
+ description.appendText("message ");
+ fMatcher.describeMismatch(item.getMessage(), description);
+ }
+
+ @Factory
+ public static <T extends Throwable> Matcher<T> hasMessage(final Matcher<String> matcher) {
+ return new ThrowableMessageMatcher<T>(matcher);
+ }
+}
3  src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java
View
@@ -10,7 +10,10 @@
* This simply implements the null check, checks the type and then casts.
*
* @author Joe Walnes
+ *
+ * @deprecated Please use {@link org.hamcrest.TypeSafeMatcher}.
*/
+@Deprecated
public abstract class TypeSafeMatcher<T> extends BaseMatcher<T> {
private Class<?> expectedType;
87 src/main/java/org/junit/matchers/JUnitMatchers.java
View
@@ -1,11 +1,10 @@
package org.junit.matchers;
+import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
-import org.junit.internal.matchers.CombinableMatcher;
-import org.junit.internal.matchers.Each;
-import org.junit.internal.matchers.IsCollectionContaining;
-import org.junit.internal.matchers.StringContains;
-import org.junit.internal.matchers.CauseMatcher;
+import org.hamcrest.core.CombinableMatcher.CombinableBothMatcher;
+import org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher;
+import org.junit.internal.matchers.StacktracePrintingMatcher;
/**
* Convenience import class: these are useful matchers for use with the assertThat method, but they are
@@ -16,25 +15,34 @@
/**
* @param element
* @return A matcher matching any collection containing element
+ *
+ * @deprecated Please use {@link CoreMatchers#hasItem(Object)} instead.
*/
- public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItem(T element) {
- return IsCollectionContaining.hasItem(element);
+ @Deprecated
+ public static <T> Matcher<Iterable<? super T>> hasItem(T element) {
+ return CoreMatchers.hasItem(element);
}
/**
* @param elementMatcher
* @return A matcher matching any collection containing an element matching elementMatcher
+ *
+ * @deprecated Please use {@link CoreMatchers#hasItem(Matcher)} instead.
*/
- public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItem(org.hamcrest.Matcher<? extends T> elementMatcher) {
- return IsCollectionContaining.hasItem(elementMatcher);
+ @Deprecated
+ public static <T> Matcher<Iterable<? super T>> hasItem(Matcher<? super T> elementMatcher) {
+ return CoreMatchers.hasItem(elementMatcher);
}
/**
* @param elements
* @return A matcher matching any collection containing every element in elements
+ *
+ * @deprecated Please use {@link CoreMatchers#hasItems(Object...)} instead.
*/
- public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(T... elements) {
- return IsCollectionContaining.hasItems(elements);
+ @Deprecated
+ public static <T> Matcher<Iterable<T>> hasItems(T... elements) {
+ return CoreMatchers.hasItems(elements);
}
/**
@@ -42,25 +50,34 @@
* @return A matcher matching any collection containing at least one element that matches
* each matcher in elementMatcher (this may be one element matching all matchers,
* or different elements matching each matcher)
+ *
+ * @deprecated Please use {@link CoreMatchers#hasItems(Matcher...)} instead.
*/
- public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(org.hamcrest.Matcher<? extends T>... elementMatchers) {
- return IsCollectionContaining.hasItems(elementMatchers);
+ @Deprecated
+ public static <T> Matcher<Iterable<T>> hasItems(Matcher<? super T>... elementMatchers) {
+ return CoreMatchers.hasItems(elementMatchers);
}
/**
* @param elementMatcher
* @return A matcher matching any collection in which every element matches elementMatcher
+ *
+ * @deprecated Please use {@link CoreMatchers#everyItem(Matcher)} instead.
*/
+ @Deprecated
public static <T> Matcher<Iterable<T>> everyItem(final Matcher<T> elementMatcher) {
- return Each.each(elementMatcher);
+ return CoreMatchers.everyItem(elementMatcher);
}
/**
* @param substring
* @return a matcher matching any string that contains substring
+ *
+ * @deprecated Please use {@link CoreMatchers#containsString(String)} instead.
*/
- public static org.hamcrest.Matcher<java.lang.String> containsString(java.lang.String substring) {
- return StringContains.containsString(substring);
+ @Deprecated
+ public static Matcher<java.lang.String> containsString(java.lang.String substring) {
+ return CoreMatchers.containsString(substring);
}
/**
@@ -68,9 +85,12 @@
* <pre>
* assertThat(string, both(containsString("a")).and(containsString("b")));
* </pre>
+ *
+ * @deprecated Please use {@link CoreMatchers#both(Matcher)} instead.
*/
- public static <T> CombinableMatcher<T> both(Matcher<T> matcher) {
- return new CombinableMatcher<T>(matcher);
+ @Deprecated
+ public static <T> CombinableBothMatcher<T> both(Matcher<? super T> matcher) {
+ return CoreMatchers.both(matcher);
}
/**
@@ -78,16 +98,29 @@
* <pre>
* assertThat(string, either(containsString("a")).or(containsString("b")));
* </pre>
+ *
+ * @deprecated Please use {@link CoreMatchers#either(Matcher)} instead.
*/
- public static <T> CombinableMatcher<T> either(Matcher<T> matcher) {
- return new CombinableMatcher<T>(matcher);
- }
-
+ @Deprecated
+ public static <T> CombinableEitherMatcher<T> either(Matcher<? super T> matcher) {
+ return CoreMatchers.either(matcher);
+ }
+
+ /**
+ * @param throwableMatcher
+ * @return A matcher that delegates to throwableMatcher and in addition
+ * appends the stacktrace of the actual Throwable in case of a mismatch.
+ */
+ public static <T extends Throwable> Matcher<T> isThrowable(Matcher<T> throwableMatcher) {
+ return StacktracePrintingMatcher.isThrowable(throwableMatcher);
+ }
+
/**
- * @param causeMatcher
- * @return a matcher matching the cause of the exception with the given {@code causeMatcher}
+ * @param exceptionMatcher
+ * @return A matcher that delegates to exceptionMatcher and in addition
+ * appends the stacktrace of the actual Exception in case of a mismatch.
*/
- public static Matcher<Throwable> causedBy(final Matcher<? super Throwable> causeMatcher) {
- return new CauseMatcher(causeMatcher);
- }
+ public static <T extends Exception> Matcher<T> isException(Matcher<T> exceptionMatcher) {
+ return StacktracePrintingMatcher.isException(exceptionMatcher);
+ }
}
65 src/main/java/org/junit/rules/ExpectedException.java
View
@@ -1,14 +1,15 @@
package org.junit.rules;
+import static junit.framework.Assert.fail;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.both;
-import static org.junit.matchers.JUnitMatchers.containsString;
-import org.hamcrest.Description;
+import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause;
+import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;
+import junit.framework.Assert;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.junit.internal.AssumptionViolatedException;
-import org.junit.internal.matchers.TypeSafeMatcher;
import org.junit.runners.model.Statement;
/**
@@ -89,7 +90,7 @@ public static ExpectedException none() {
return new ExpectedException();
}
- private Matcher<Object> fMatcher= null;
+ private final ExpectedExceptionMatcherBuilder fMatcherBuilder= new ExpectedExceptionMatcherBuilder();
private boolean handleAssumptionViolatedExceptions= false;
@@ -117,14 +118,8 @@ public Statement apply(Statement base,
* Adds {@code matcher} to the list of requirements for any thrown
* exception.
*/
- // Should be able to remove this suppression in some brave new hamcrest
- // world.
- @SuppressWarnings("unchecked")
public void expect(Matcher<?> matcher) {
- if (fMatcher == null)
- fMatcher= (Matcher<Object>) matcher;
- else
- fMatcher= both(fMatcher).and(matcher);
+ fMatcherBuilder.add(matcher);
}
/**
@@ -170,22 +165,23 @@ public ExpectedExceptionStatement(Statement base) {
public void evaluate() throws Throwable {
try {
fNext.evaluate();
+ if (fMatcherBuilder.expectsThrowable())
+ failDueToMissingException();
} catch (AssumptionViolatedException e) {
optionallyHandleException(e, handleAssumptionViolatedExceptions);
- return;
} catch (AssertionError e) {
optionallyHandleException(e, handleAssertionErrors);
- return;
} catch (Throwable e) {
handleException(e);
- return;
}
- if (fMatcher != null)
- throw new AssertionError("Expected test to throw "
- + StringDescription.toString(fMatcher));
}
}
+ private void failDueToMissingException() throws AssertionError {
+ String expectation= StringDescription.toString(fMatcherBuilder.build());
+ fail("Expected test to throw " + expectation);
+ }
+
private void optionallyHandleException(Throwable e, boolean handleException)
throws Throwable {
if (handleException)
@@ -195,36 +191,9 @@ private void optionallyHandleException(Throwable e, boolean handleException)
}
private void handleException(Throwable e) throws Throwable {
- if (fMatcher == null)
+ if (fMatcherBuilder.expectsThrowable())
+ assertThat(e, fMatcherBuilder.build());
+ else
throw e;
- assertThat(e, fMatcher);
- }
-
- private Matcher<Throwable> hasMessage(final Matcher<String> matcher) {
- return new TypeSafeMatcher<Throwable>() {
- public void describeTo(Description description) {
- description.appendText("exception with message ");
- description.appendDescriptionOf(matcher);
- }
-
- @Override
- public boolean matchesSafely(Throwable item) {
- return matcher.matches(item.getMessage());
- }
- };
- }
-
- private Matcher<Throwable> hasCause(final Matcher<? extends Throwable> causeMatcher) {
- return new TypeSafeMatcher<Throwable>() {
- public void describeTo(Description description) {
- description.appendText("exception with cause ");
- description.appendDescriptionOf(causeMatcher);
- }
-
- @Override
- public boolean matchesSafely(Throwable item) {
- return causeMatcher.matches(item.getCause());
- }
- };
}
}
46 src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java
View
@@ -0,0 +1,46 @@
+package org.junit.rules;
+
+import static org.hamcrest.CoreMatchers.allOf;
+import static org.junit.matchers.JUnitMatchers.isThrowable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hamcrest.Matcher;
+
+/**
+ * Builds special matcher used by {@link ExpectedException}.
+ */
+class ExpectedExceptionMatcherBuilder {
+
+ private final List<Matcher<?>> fMatchers= new ArrayList<Matcher<?>>();
+
+ void add(Matcher<?> matcher) {
+ fMatchers.add(matcher);
+ }
+
+ boolean expectsThrowable() {
+ return !fMatchers.isEmpty();
+ }
+
+ Matcher<Throwable> build() {
+ return isThrowable(allOfTheMatchers());
+ }
+
+ private Matcher<Throwable> allOfTheMatchers() {
+ if (fMatchers.size() == 1) {
+ return cast(fMatchers.get(0));
+ }
+ return allOf(castedMatchers());
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private List<Matcher<? super Throwable>> castedMatchers() {
+ return new ArrayList<Matcher<? super Throwable>>((List) fMatchers);
+ }
+
+ @SuppressWarnings("unchecked")
+ private Matcher<Throwable> cast(Matcher<?> singleMatcher) {
+ return (Matcher<Throwable>) singleMatcher;
+ }
+}
2  src/main/java/org/junit/rules/RuleChain.java
View
@@ -15,7 +15,7 @@
* <pre>
* public static class UseRuleChain {
* &#064;Rule
- * public TestRule chain= RuleChain
+ * public RuleChain chain= RuleChain
* .outerRule(new LoggingRule("outer rule")
* .around(new LoggingRule("middle rule")
* .around(new LoggingRule("inner rule");
33 src/main/java/org/junit/rules/TemporaryFolder.java
View
@@ -26,16 +26,16 @@
* @since 4.7
*/
public class TemporaryFolder extends ExternalResource {
- private final File parentFolder;
+ private final File parentFolder;
private File folder;
- public TemporaryFolder() {
- this(null);
- }
+ public TemporaryFolder() {
+ this(null);
+ }
- public TemporaryFolder(File parentFolder) {
- this.parentFolder = parentFolder;
- }
+ public TemporaryFolder(File parentFolder) {
+ this.parentFolder = parentFolder;
+ }
@Override
protected void before() throws Throwable {
@@ -61,7 +61,7 @@ public void create() throws IOException {
public File newFile(String fileName) throws IOException {
File file= new File(getRoot(), fileName);
if (!file.createNewFile())
- throw new IllegalStateException(
+ throw new IOException(
"a file with the name \'" + fileName + "\' already exists in the test folder");
return file;
}
@@ -77,7 +77,7 @@ public File newFile() throws IOException {
* Returns a new fresh folder with the given name under the temporary
* folder.
*/
- public File newFolder(String folder) {
+ public File newFolder(String folder) throws IOException {
return newFolder(new String[]{folder});
}
@@ -85,15 +85,22 @@ public File newFolder(String folder) {
* Returns a new fresh folder with the given name(s) under the temporary
* folder.
*/
- public File newFolder(String... folderNames) {
+ public File newFolder(String... folderNames) throws IOException {
File file= getRoot();
- for (String folderName : folderNames) {
- file= new File(file, folderName);
- file.mkdir();
+ for (int i = 0; i < folderNames.length; i++) {
+ String folderName = folderNames[i];
+ file = new File(file, folderName);
+ if (!file.mkdir() && isLastElementInArray(i, folderNames))
+ throw new IOException(
+ "a folder with the name \'" + folderName + "\' already exists");
}
return file;
}
+ private boolean isLastElementInArray(int index, String[] array) {
+ return index == array.length - 1;
+ }
+
/**
* Returns a new fresh folder with a random name under the temporary folder.
*/
57 src/main/java/org/junit/rules/TestWatcher.java
View
@@ -1,7 +1,11 @@
package org.junit.rules;
+import java.util.ArrayList;
+import java.util.List;
+
import org.junit.internal.AssumptionViolatedException;
import org.junit.runner.Description;
+import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
/**
@@ -14,7 +18,7 @@
* private static String watchedLog;
*
* &#064;Rule
- * public TestRule watchman= new TestWatcher() {
+ * public TestWatcher watchman= new TestWatcher() {
* &#064;Override
* protected void failed(Throwable e, Description description) {
* watchedLog+= description + &quot;\n&quot;;
@@ -43,23 +47,63 @@ public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
- starting(description);
+ List<Throwable> errors = new ArrayList<Throwable>();
+
+ startingQuietly(description, errors);
try {
base.evaluate();
- succeeded(description);
+ succeededQuietly(description, errors);
} catch (AssumptionViolatedException e) {
skipped(e, description);
throw e;
} catch (Throwable t) {
- failed(t, description);
- throw t;
+ errors.add(t);
+ failedQuietly(t, description, errors);
} finally {
- finished(description);
+ finishedQuietly(description, errors);
}
+
+ MultipleFailureException.assertEmpty(errors);
}
};
}
+ private void succeededQuietly(Description description,
+ List<Throwable> errors) {
+ try {
+ succeeded(description);
+ } catch (Throwable t) {
+ errors.add(t);
+ }
+ }
+
+ private void failedQuietly(Throwable t, Description description,
+ List<Throwable> errors) {
+ try {
+ failed(t, description);
+ } catch (Throwable t1) {
+ errors.add(t1);
+ }
+ }
+
+ private void startingQuietly(Description description,
+ List<Throwable> errors) {
+ try {
+ starting(description);
+ } catch (Throwable t) {
+ errors.add(t);
+ }
+ }
+
+ private void finishedQuietly(Description description,
+ List<Throwable> errors) {
+ try {
+ finished(description);
+ } catch (Throwable t) {
+ errors.add(t);
+ }
+ }
+
/**
* Invoked when a test succeeds
*
@@ -94,7 +138,6 @@ protected void skipped(AssumptionViolatedException e, Description description) {
protected void starting(Description description) {
}
-
/**
* Invoked when a test method finishes (whether passing or failing)
*
2  src/main/java/org/junit/rules/Timeout.java
View
@@ -12,7 +12,7 @@
* public static String log;
*
* &#064;Rule
- * public TestRule globalTimeout= new Timeout(20);
+ * public Timeout globalTimeout= new Timeout(20);
*
* &#064;Test
* public void testInfiniteLoop1() {
2  src/main/java/org/junit/rules/Verifier.java
View
@@ -13,7 +13,7 @@
* private ErrorLog errorLog = new ErrorLog();
*
* &#064;Rule
- * public TestRule verifier = new Verifier() {
+ * public Verifier verifier = new Verifier() {
* &#064;Override public void verify() {
* assertTrue(errorLog.isEmpty());
* }
33 src/main/java/org/junit/runner/Description.java
View
@@ -36,7 +36,7 @@
* Create a <code>Description</code> named <code>name</code>.
* Generally, you will add children to this <code>Description</code>.
* @param name the name of the <code>Description</code>
- * @param annotations
+ * @param annotations meta-data about the test, for downstream interpreters
* @return a <code>Description</code> named <code>name</code>
*/
public static Description createSuiteDescription(String name, Annotation... annotations) {
@@ -56,6 +56,20 @@ public static Description createSuiteDescription(String name, Serializable uniqu
}
/**
+ * Create a <code>Description</code> of a single test named <code>name</code> in the 'class' named
+ * <code>className</code>. Generally, this will be a leaf <code>Description</code>. This method is a better choice
+ * than {@link #createTestDescription(Class, String, Annotation...)} for test runners whose test cases are not
+ * defined in an actual Java <code>Class</code>.
+ * @param className the class name of the test
+ * @param name the name of the test (a method name for test annotated with {@link org.junit.Test})
+ * @param annotations meta-data about the test, for downstream interpreters
+ * @return a <code>Description</code> named <code>name</code>
+ */
+ public static Description createTestDescription(String className, String name, Annotation... annotations) {
+ return new Description(String.format("%s(%s)", name, className), annotations);
+ }
+
+ /**
* Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>.
* Generally, this will be a leaf <code>Description</code>.
* @param clazz the class of the test
@@ -64,19 +78,30 @@ public static Description createSuiteDescription(String name, Serializable uniqu
* @return a <code>Description</code> named <code>name</code>
*/
public static Description createTestDescription(Class<?> clazz, String name, Annotation... annotations) {
- return new Description(String.format("%s(%s)", name, clazz.getName()), annotations);
+ return createTestDescription(clazz.getName(), name, annotations);
}
/**
* Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>.
- * Generally, this will be a leaf <code>Description</code>.
+ * Generally, this will be a leaf <code>Description</code>.
* (This remains for binary compatibility with clients of JUnit 4.3)
* @param clazz the class of the test
* @param name the name of the test (a method name for test annotated with {@link org.junit.Test})
* @return a <code>Description</code> named <code>name</code>
*/
public static Description createTestDescription(Class<?> clazz, String name) {
- return createTestDescription(clazz, name, new Annotation[0]);
+ return createTestDescription(clazz.getName(), name);
+ }
+
+ /**
+ * Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>.
+ * Generally, this will be a leaf <code>Description</code>.
+ *
+ * @param name the name of the test (a method name for test annotated with {@link org.junit.Test})
+ * @return a <code>Description</code> named <code>name</code>
+ */
+ public static Description createTestDescription(String className, String name, Serializable uniqueId) {
+ return new Description(String.format("%s(%s)", name, className), uniqueId);
}
/**
4 src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java
View
@@ -169,7 +169,7 @@ protected void validateInstanceMethods(List<Throwable> errors) {
errors.add(new Exception("No runnable methods"));
}
- private void validateFields(List<Throwable> errors) {
+ protected void validateFields(List<Throwable> errors) {
RULE_VALIDATOR.validate(getTestClass(), errors);
}
@@ -417,4 +417,4 @@ private long getTimeout(Test annotation) {
return 0;
return annotation.timeout();
}
-}
+}
121 src/main/java/org/junit/runners/Parameterized.java
View
@@ -5,6 +5,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
@@ -12,6 +13,7 @@
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
@@ -73,6 +75,35 @@
* names like <code>[1: fib(3)=2]</code>. If you don't use the name parameter,
* then the current parameter index is used as name.
* </p>
+ *
+ * You can also write:
+ *
+ * <pre>
+ * &#064;RunWith(Parameterized.class)
+ * public class FibonacciTest {
+ * &#064;Parameters
+ * public static Iterable&lt;Object[]&gt; data() {
+ * return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
+ * { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
+ * }
+ * &#064;Parameter(0)
+ * public int fInput;
+ *
+ * &#064;Parameter(1)
+ * public int fExpected;
+ *
+ * &#064;Test
+ * public void test() {
+ * assertEquals(fExpected, Fibonacci.compute(fInput));
+ * }
+ * }
+ * </pre>
+ *
+ * <p>
+ * Each instance of <code>FibonacciTest</code> will be constructed with the default constructor
+ * and fields annotated by <code>&#064;Parameter</code> will be initialized
+ * with the data values in the <code>&#064;Parameters</code> method.
+ * </p>
* @since 4.0
*/
public class Parameterized extends Suite {
@@ -108,6 +139,26 @@
String name() default "{index}";
}
+ /**
+ * Annotation for fields of the test class which will be initialized by the
+ * method annotated by <code>Parameters</code><br/>
+ * By using directly this annotation, the test class constructor isn't needed.<br/>
+ * Index range must start at 0.
+ * Default value is 0.
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.FIELD)
+ public static @interface Parameter {
+ /**
+ * Method that returns the index of the parameter in the array
+ * returned by the method annotated by <code>Parameters</code>.<br/>
+ * Index range must start at 0.
+ * Default value is 0.
+ * @return the index of the parameter.
+ */
+ int value() default 0;
+ }
+
private class TestClassRunnerForParameters extends BlockJUnit4ClassRunner {
private final Object[] fParameters;
@@ -122,8 +173,38 @@
@Override
public Object createTest() throws Exception {
+ if (fieldsAreAnnotated()) {
+ return createTestUsingFieldInjection();
+ } else {
+ return createTestUsingConstructorInjection();
+ }
+ }
+
+ private Object createTestUsingConstructorInjection() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(fParameters);
}
+
+ private Object createTestUsingFieldInjection() throws Exception {
+ List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
+ if (annotatedFieldsByParameter.size() != fParameters.length)
+ throw new Exception("Wrong number of parameters and @Parameter fields."+
+ " @Parameter fields counted: "+annotatedFieldsByParameter.size()+", available parameters: "+fParameters.length+".");
+ Object testClassInstance = getTestClass().getJavaClass().newInstance();
+ for (FrameworkField each : annotatedFieldsByParameter) {
+ Field field = each.getField();
+ Parameter annotation = field.getAnnotation(Parameter.class);
+ int index = annotation.value();
+ try {
+ field.set(testClassInstance, fParameters[index]);
+ } catch(IllegalArgumentException iare) {
+ throw new Exception(getTestClass().getName() + ": Trying to set "+field.getName()+
+ " with the value "+fParameters[index]+
+ " that is not the right type ("+fParameters[index].getClass().getSimpleName()+" instead of "+
+ field.getType().getSimpleName()+").", iare);
+ }
+ }
+ return testClassInstance;
+ }
@Override
protected String getName() {
@@ -138,6 +219,38 @@ protected String testName(FrameworkMethod method) {
@Override
protected void validateConstructor(List<Throwable> errors) {
validateOnlyOneConstructor(errors);
+ if (fieldsAreAnnotated()) {
+ validateZeroArgConstructor(errors);
+ }
+ }
+
+ @Override
+ protected void validateFields(List<Throwable> errors) {
+ super.validateFields(errors);
+ if (fieldsAreAnnotated()) {
+ List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
+ int[] usedIndices = new int[annotatedFieldsByParameter.size()];
+ for (FrameworkField each : annotatedFieldsByParameter) {
+ int index = each.getField().getAnnotation(Parameter.class).value();
+ if (index < 0 || index > annotatedFieldsByParameter.size()-1) {
+ errors.add(
+ new Exception("Invalid @Parameter value: "+index+". @Parameter fields counted: "+
+ annotatedFieldsByParameter.size()+". Please use an index between 0 and "+
+ (annotatedFieldsByParameter.size()-1)+".")
+ );
+ } else {
+ usedIndices[index]++;
+ }
+ }
+ for (int index = 0 ; index < usedIndices.length ; index++) {
+ int numberOfUse = usedIndices[index];
+ if (numberOfUse == 0) {
+ errors.add(new Exception("@Parameter("+index+") is never used."));
+ } else if (numberOfUse > 1) {
+ errors.add(new Exception("@Parameter("+index+") is used more than once ("+numberOfUse+")."));
+ }
+ }
+ }
}
@Override
@@ -224,4 +337,12 @@ private Exception parametersMethodReturnedWrongType() throws Exception {
className, methodName);
return new Exception(message);
}
+
+ private List<FrameworkField> getAnnotatedFieldsByParameter() {
+ return getTestClass().getAnnotatedFields(Parameter.class);
+ }
+
+ private boolean fieldsAreAnnotated() {
+ return !getAnnotatedFieldsByParameter().isEmpty();
+ }
}
12 src/test/java/org/junit/internal/MethodSorterTest.java
View
@@ -17,7 +17,7 @@
private static final String DELTA= "void delta()";
private static final String EPSILON= "void epsilon()";
- private static class Dummy {
+ static class Dummy {
Object alpha(int i, double d, Thread t) {return null;}
void beta(int[][] x) {}
int gamma() {return 0;}
@@ -25,10 +25,10 @@ void gamma(boolean b) {}
void delta() {}
void epsilon() {}
}
- private static class Super {
+ static class Super {
void testOne() {}
}
- private static class Sub extends Super {
+ static class Sub extends Super {
void testTwo() {}
}
@@ -48,7 +48,7 @@ private String declaredMethods(Class<?> clazz) {
}
@FixMethodOrder(MethodSorters.DEFAULT)
- private static class DummySortWithDefault {
+ static class DummySortWithDefault {
Object alpha(int i, double d, Thread t) {return null;}
void beta(int[][] x) {}
int gamma() {return 0;}
@@ -63,7 +63,7 @@ void epsilon() {}
}
@FixMethodOrder(MethodSorters.JVM)
- private static class DummySortJvm {
+ static class DummySortJvm {
Object alpha(int i, double d, Thread t) {return null;}
void beta(int[][] x) {}
int gamma() {return 0;}
@@ -80,7 +80,7 @@ void epsilon() {}
}
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
- private static class DummySortWithNameAsc {
+ static class DummySortWithNameAsc {
Object alpha(int i, double d, Thread t) {return null;}
void beta(int[][] x) {}
int gamma() {return 0;}
37 src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java
View
@@ -0,0 +1,37 @@
+package org.junit.internal.matchers;
+
+import static org.hamcrest.CoreMatchers.any;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.internal.matchers.StacktracePrintingMatcher.isException;
+import static org.junit.internal.matchers.StacktracePrintingMatcher.isThrowable;
+import org.junit.Test;
+
+public class StacktracePrintingMatcherTest {
+
+ @Test
+ public void succeedsWhenInnerMatcherSucceeds() throws Exception {
+ assertTrue(isThrowable(any(Throwable.class)).matches(new Exception()));
+ }
+
+ @Test
+ public void failsWhenInnerMatcherFails() throws Exception {
+ assertFalse(isException(notNullValue(Exception.class)).matches(null));
+ }
+
+ @Test
+ public void assertThatIncludesStacktrace() {
+ Exception actual= new IllegalArgumentException("my message");
+ Exception expected= new NullPointerException();
+
+ try {
+ assertThat(actual, isThrowable(equalTo(expected)));
+ } catch (AssertionError e) {
+ assertThat(e.getMessage(), containsString("Stacktrace was: java.lang.IllegalArgumentException: my message"));
+ }
+ }
+}
12 src/test/java/org/junit/tests/AllTests.java
View
@@ -3,14 +3,12 @@
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import org.junit.internal.MethodSorterTest;
+import org.junit.internal.matchers.StacktracePrintingMatcherTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.junit.tests.assertion.AssertionTest;
-import org.junit.tests.assertion.BothTest;
-import org.junit.tests.assertion.EachTest;
import org.junit.tests.assertion.MultipleFailureExceptionTest;
-import org.junit.tests.assertion.CauseMatcherTest;
import org.junit.tests.deprecated.JUnit4ClassRunnerTest;
import org.junit.tests.description.AnnotatedDescriptionTest;
import org.junit.tests.description.SuiteDescriptionTest;
@@ -31,8 +29,8 @@
import org.junit.tests.experimental.rules.ExternalResourceRuleTest;
import org.junit.tests.experimental.rules.MethodRulesTest;
import org.junit.tests.experimental.rules.NameRulesTest;
-import org.junit.tests.experimental.rules.RuleFieldValidatorTest;
import org.junit.tests.experimental.rules.RuleChainTest;
+import org.junit.tests.experimental.rules.RuleFieldValidatorTest;
import org.junit.tests.experimental.rules.TempFolderRuleTest;
import org.junit.tests.experimental.rules.TemporaryFolderUsageTest;
import org.junit.tests.experimental.rules.TestRuleTest;
@@ -126,9 +124,7 @@
IgnoreClassTest.class,
OldTestClassAdaptingListenerTest.class,
AnnotatedDescriptionTest.class,
- BothTest.class,
AssumptionViolatedExceptionTest.class,
- EachTest.class,
ExperimentalTests.class,
InheritedTestTest.class,
TestClassTest.class,
@@ -162,9 +158,9 @@
RuleFieldValidatorTest.class,
RuleChainTest.class,
BlockJUnit4ClassRunnerTest.class,
- CauseMatcherTest.class,
MethodSorterTest.class,
- TestedOnSupplierTest.class
+ TestedOnSupplierTest.class,
+ StacktracePrintingMatcherTest.class
})
public class AllTests {
public static Test suite() {
22 src/test/java/org/junit/tests/assertion/AssertionTest.java
View
@@ -1,13 +1,14 @@
package org.junit.tests.assertion;
import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -462,7 +463,7 @@ public void arraysDeclaredAsObjectAreComparedAsObjects() {
String expected = "expected";
String actual = "actual";
- String expectedMessage = "identifier\nExpected: \"expected\"\n got: \"actual\"\n";
+ String expectedMessage = "identifier\nExpected: \"expected\"\n but: was \"actual\"";
try {
assertThat("identifier", actual, equalTo(expected));
@@ -472,10 +473,10 @@ public void arraysDeclaredAsObjectAreComparedAsObjects() {
}
@Test public void assertThatIncludesAdvancedMismatch() {
- String expectedMessage = "identifier\nExpected: is an instance of java.lang.Integer\n got: \"actual\"\n";
+ String expectedMessage = "identifier\nExpected: is an instance of java.lang.Integer\n but: \"actual\" is a java.lang.String";
try {
- assertThat("identifier", "actual", is(Integer.class));
+ assertThat("identifier", "actual", is(instanceOf(Integer.class)));
} catch (AssertionError e) {
assertEquals(expectedMessage, e.getMessage());
}
@@ -485,7 +486,7 @@ public void arraysDeclaredAsObjectAreComparedAsObjects() {
String expected = "expected";
String actual = "actual";
- String expectedMessage = "\nExpected: \"expected\"\n got: \"actual\"\n";
+ String expectedMessage = "\nExpected: \"expected\"\n but: was \"actual\"";
try {
assertThat(actual, equalTo(expected));
@@ -494,17 +495,6 @@ public void arraysDeclaredAsObjectAreComparedAsObjects() {
}
}
- @Test public void assertThatIncludesActualException() {
- Exception actual= new IllegalArgumentException();
- Exception expected= new NullPointerException();
-
- try {
- assertThat(actual, equalTo(expected));
- } catch (AssertionError e) {
- assertEquals(actual, e.getCause());
- }
- }
-
@Test public void nullAndStringNullPrintCorrectError() {
try {
assertEquals(null, "null");
71 src/test/java/org/junit/tests/assertion/BothTest.java
View
@@ -1,71 +0,0 @@
-package org.junit.tests.assertion;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assume.assumeTrue;
-import static org.junit.matchers.JUnitMatchers.both;
-import static org.junit.matchers.JUnitMatchers.containsString;
-import static org.junit.matchers.JUnitMatchers.either;
-import org.hamcrest.Matcher;
-import org.junit.Test;
-import org.junit.experimental.theories.DataPoint;
-import org.junit.experimental.theories.Theories;
-import org.junit.experimental.theories.Theory;
-import org.junit.runner.RunWith;
-
-@RunWith(Theories.class)
-public class BothTest {
- @DataPoint
- public static Matcher<Integer> IS_3= is(3);
-
- @DataPoint
- public static Matcher<Integer> IS_4= is(4);
-
- @DataPoint
- public static int THREE= 3;
-
- @Test
- public void bothPasses() {
- assertThat(3, both(is(Integer.class)).and(is(3)));
- }
-
- @Theory
- public void bothFails(int value, Matcher<Integer> first,
- Matcher<Integer> second) {
- assumeTrue(!(first.matches(value) && second.matches(value)));
- assertThat(value, not(both(first).and(second)));
- }
-
- @Theory
- public <T> void descriptionIsSensible(Matcher<T> first, Matcher<T> second) {
- Matcher<?> both= both(first).and(second);
- assertThat(both.toString(), containsString(first.toString()));
- assertThat(both.toString(), containsString(second.toString()));
- }
-
- @Test
- public void eitherPasses() {
- assertThat(3, either(is(3)).or(is(4)));
- }
-
- @Theory
- public <T> void threeAndsWork(Matcher<Integer> first,
- Matcher<Integer> second, Matcher<Integer> third, int value) {
- assumeTrue(first.matches(value) && second.matches(value)
- && third.matches(value));
- assertThat(value, both(first).and(second).and(third));
- }
-
- @Theory
- public <T> void threeOrsWork(Matcher<Integer> first,
- Matcher<Integer> second, Matcher<Integer> third, int value) {
- assumeTrue(first.matches(value) || second.matches(value)
- || third.matches(value));
- assertThat(value, either(first).or(second).or(third));
- }
-
- @Test public void subclassesAreOkInSecondPositionOnly() {
- assertThat(3, both(is(Integer.class)).and(is(3)));
- }
-}
18 src/test/java/org/junit/tests/assertion/CauseMatcherTest.java
View
@@ -1,18 +0,0 @@
-package org.junit.tests.assertion;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.causedBy;
-import org.junit.Test;
-
-public class CauseMatcherTest {
- @Test
- public void causedByCorrect() {
- assertThat(new IllegalStateException(new IllegalArgumentException()), causedBy(instanceOf(IllegalArgumentException.class)));
- }
-
- @Test(expected=AssertionError.class)
- public void causedByFailing() {
- assertThat(new IllegalStateException(new IllegalArgumentException()), causedBy(instanceOf(IllegalStateException.class)));
- }
-}
13 src/test/java/org/junit/tests/assertion/EachTest.java
View
@@ -1,13 +0,0 @@
-package org.junit.tests.assertion;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import org.junit.Test;
-import org.junit.internal.matchers.Each;
-
-public class EachTest {
- @Test
- public void eachDescription() {
- assertThat(Each.each(is("a")).toString(), is("each is \"a\""));
- }
-}
2  src/test/java/org/junit/tests/experimental/AssumptionTest.java
View
@@ -1,5 +1,6 @@
package org.junit.tests.experimental;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@@ -9,7 +10,6 @@
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
-import static org.junit.internal.matchers.StringContains.containsString;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
2  src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java
View
@@ -1,10 +1,10 @@
package org.junit.tests.experimental;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
-import static org.junit.internal.matchers.StringContains.containsString;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.junit.Test;
42 src/test/java/org/junit/tests/experimental/max/DescriptionTest.java
View
@@ -1,9 +1,15 @@
package org.junit.tests.experimental.max;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+
import org.junit.Test;
import org.junit.runner.Description;
+import java.lang.annotation.Annotation;
+
public class DescriptionTest {
@Test
@@ -25,4 +31,40 @@ public void createSuiteDescription_whenZeroLength() {
public void createSuiteDescription_whenNull() {
Description.createSuiteDescription((String) null);
}
+
+ @Test
+ public void parseClassAndMethodNoAnnotations() throws Exception {
+ Description description = Description.createTestDescription(Description.class, "aTestMethod");
+
+ assertThat(description.getClassName(), equalTo("org.junit.runner.Description"));
+ assertThat(description.getMethodName(), equalTo("aTestMethod"));
+ assertThat(description.getAnnotations().size(), equalTo(0));
+ }
+
+ @Test
+ public void parseClassAndMethodWithAnnotations() throws Exception {
+ Annotation[] annotations =
+ DescriptionTest.class.getMethod("parseClassAndMethodWithAnnotations").getDeclaredAnnotations();
+
+ Description description = Description.createTestDescription(Description.class, "aTestMethod", annotations);
+
+ assertThat(description.getClassName(), equalTo("org.junit.runner.Description"));
+ assertThat(description.getMethodName(), equalTo("aTestMethod"));
+ assertThat(description.getAnnotations().size(), equalTo(1));
+ }
+
+ @Test
+ public void parseClassNameAndMethodUniqueId() throws Exception {
+ Description description = Description.createTestDescription("not a class name", "aTestMethod", 123);
+
+ assertThat(description.getClassName(), equalTo("not a class name"));
+ assertThat(description.getMethodName(), equalTo("aTestMethod"));
+ assertThat(description.getAnnotations().size(), equalTo(0));
+ }
+
+ @Test
+ public void sameNamesButDifferentUniqueIdAreNotEqual() throws Exception {
+ assertThat(Description.createTestDescription("not a class name", "aTestMethod", 1),
+ not(equalTo(Description.createTestDescription("not a class name", "aTestMethod", 2))));
+ }
}
2  src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java
View
@@ -1,11 +1,11 @@
package org.junit.tests.experimental.max;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.containsString;
import java.io.File;
import java.util.ArrayList;
2  src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java
View
@@ -4,9 +4,9 @@
import static org.junit.Assert.assertTrue;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import org.junit.experimental.ParallelComputer;
-import org.junit.internal.matchers.TypeSafeMatcher;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
2  src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java
View
@@ -4,9 +4,9 @@
import static org.junit.Assert.assertTrue;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import org.junit.experimental.ParallelComputer;
-import org.junit.internal.matchers.TypeSafeMatcher;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
3  src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java
View
@@ -2,8 +2,8 @@
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.allOf;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
-import static org.junit.internal.matchers.StringContains.containsString;
import java.util.Arrays;
@@ -17,7 +17,6 @@
@RunWith(Theories.class)
public class PrintableResultTest {
- @SuppressWarnings("unchecked")
@Theory(nullsAccepted= false)
public void backTraceHasGoodToString(String descriptionName,
final String stackTraceClassName) {
2  src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java
View
@@ -1,8 +1,8 @@
package org.junit.tests.experimental.results;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
-import static org.junit.internal.matchers.StringContains.containsString;
import org.junit.Test;
import org.junit.experimental.results.ResultMatchers;
import org.junit.experimental.theories.Theory;
6 src/test/java/org/junit/tests/experimental/rules/EventCollector.java
View
@@ -1,13 +1,13 @@
package org.junit.tests.experimental.rules;
+import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.matchers.JUnitMatchers.both;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
+import org.hamcrest.TypeSafeMatcher;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
@@ -15,7 +15,7 @@
class EventCollector extends RunListener {
static Matcher<EventCollector> everyTestRunSuccessful() {
- return both(hasNoFailure()).and(hasNoAssumptionFailure());
+ return allOf(hasNoFailure(), hasNoAssumptionFailure());
}
private static Matcher<EventCollector> hasNumberOfFailures(
43 src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionTest.java
View
@@ -2,30 +2,27 @@
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.any;
-import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
-import static org.junit.matchers.JUnitMatchers.causedBy;
import static org.junit.rules.ExpectedException.none;
import static org.junit.tests.experimental.rules.EventCollector.everyTestRunSuccessful;
-import static org.junit.tests.experimental.rules.EventCollector.failureIs;
import static org.junit.tests.experimental.rules.EventCollector.hasSingleAssumptionFailure;
import static org.junit.tests.experimental.rules.EventCollector.hasSingleFailure;
import static org.junit.tests.experimental.rules.EventCollector.hasSingleFailureWithMessage;
-import java.io.IOException;
import java.util.Collection;
import org.hamcrest.CoreMatchers;
-import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.internal.AssumptionViolatedException;
-import org.junit.internal.matchers.TypeSafeMatcher;
import org.junit.rules.ExpectedException;
import org.junit.runner.JUnitCore;
import org.junit.runner.RunWith;
@@ -49,8 +46,8 @@
hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException")) },
{
HasWrongMessage.class,
- hasSingleFailureWithMessage("\nExpected: exception with message a string containing \"expectedMessage\"\n"
- + " got: <java.lang.IllegalArgumentException: actualMessage>\n") },
+ hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n"
+ + " but: message was \"actualMessage\"")) },
{
ThrowNoExceptionButExpectExceptionWithType.class,
hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException") },
@@ -70,7 +67,7 @@
hasSingleFailure() },
{
ThrowAssumptionViolatedExceptionButExpectOtherType.class,
- failureIs(causedBy(instanceOf(AssumptionViolatedException.class))) },
+ hasSingleFailureWithMessage(containsString("Stacktrace was: org.junit.internal.AssumptionViolatedException")) },
{ ViolateAssumptionAndExpectException.class,
hasSingleAssumptionFailure() },
{ ThrowExpectedAssertionError.class, everyTestRunSuccessful() },
@@ -81,12 +78,17 @@
hasSingleFailureWithMessage(ARBITRARY_MESSAGE) },
{
ExpectsMultipleMatchers.class,
- hasSingleFailureWithMessage(startsWith("\nExpected: (exception with message a string containing \"Ack!\" and an instance of java.lang.IllegalArgumentException)")) },
+ hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")")) },
{ ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful() },
{ ThrowExpectedNullCause.class, everyTestRunSuccessful() },
{
ThrowUnexpectedCause.class,
- hasSingleFailureWithMessage(startsWith("\nExpected: (exception with cause")) }
+ hasSingleFailureWithMessage(CoreMatchers.<String>allOf(
+ startsWith("\nExpected: ("),
+ containsString("exception with cause is <java.lang.NullPointerException: expected cause>"),
+ containsString("cause was <java.lang.NullPointerException: an unexpected cause>"),
+ containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"),
+ containsString("Caused by: java.lang.NullPointerException: an unexpected cause"))) }
});
}
@@ -234,7 +236,7 @@ public void throwsMore() {
@Test
public void throwsMore() {
- thrown.expect(any(IOException.class));
+ thrown.expect(any(Exception.class));
throw new NullPointerException("Ack!");
}
}
@@ -346,7 +348,7 @@ public void throwExceptionWithMatchingCause() {
public void throwExpectedNullCause() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Ack!");
- thrown.expectCause(CoreMatchers.<Throwable>nullValue());
+ thrown.expectCause(nullValue(Throwable.class));
throw new IllegalArgumentException("Ack!");
}
@@ -366,19 +368,4 @@ public void throwWithCause() {
throw new IllegalArgumentException("Ack!", new NullPointerException("an unexpected cause"));
}
}
-
-
- private static Matcher<String> startsWith(final String prefix) {
- return new TypeSafeMatcher<String>() {
- public void describeTo(Description description) {
- description.appendText("starts with ");
- description.appendText(prefix);
- }
-
- @Override
- public boolean matchesSafely(String item) {
- return item.startsWith(prefix);
- }
- };
- }
}
4 src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java
View
@@ -1,5 +1,6 @@
package org.junit.tests.experimental.rules;
+import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@@ -8,14 +9,13 @@
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
-import static org.junit.matchers.JUnitMatchers.containsString;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.TestRule;