summaryrefslogtreecommitdiffstats
path: root/junit4/src/test/java/org/junit/tests
diff options
context:
space:
mode:
Diffstat (limited to 'junit4/src/test/java/org/junit/tests')
-rw-r--r--junit4/src/test/java/org/junit/tests/AllTests.java163
-rw-r--r--junit4/src/test/java/org/junit/tests/ObjectContractTest.java46
-rw-r--r--junit4/src/test/java/org/junit/tests/TestSystem.java31
-rw-r--r--junit4/src/test/java/org/junit/tests/assertion/AssertionTest.java486
-rw-r--r--junit4/src/test/java/org/junit/tests/assertion/BothTest.java71
-rw-r--r--junit4/src/test/java/org/junit/tests/assertion/EachTest.java13
-rw-r--r--junit4/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java60
-rw-r--r--junit4/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java54
-rw-r--r--junit4/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java96
-rw-r--r--junit4/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java35
-rw-r--r--junit4/src/test/java/org/junit/tests/description/TestDescriptionTest.java11
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/AssumptionTest.java177
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java52
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/ExperimentalTests.java28
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/MatcherTest.java43
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.java123
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/categories/CategoryTest.java254
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java24
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java53
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java293
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java54
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java44
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java51
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java21
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/BlockJUnit4ClassRunnerOverrideTest.java93
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/ClassRulesTest.java101
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionRuleTest.java232
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/ExternalResourceRuleTest.java37
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/LoggingTestWatcher.java32
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java275
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/NameRulesTest.java50
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java60
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/RuleFieldValidatorTest.java96
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java200
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java289
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java52
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/TestWatchmanTest.java72
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java39
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java133
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/AllMembersSupplierTest.java34
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java57
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java75
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java7
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java122
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java57
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java54
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java16
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java27
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java8
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java65
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java1
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java204
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java37
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java126
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java50
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java152
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java146
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java80
-rw-r--r--junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java177
-rw-r--r--junit4/src/test/java/org/junit/tests/internal/runners/statements/FailOnTimeoutTest.java110
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java81
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java19
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java89
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java222
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java100
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java79
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java27
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/OldTests.java11
-rw-r--r--junit4/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java123
-rw-r--r--junit4/src/test/java/org/junit/tests/listening/ListenerTest.java33
-rw-r--r--junit4/src/test/java/org/junit/tests/listening/RunnerTest.java69
-rw-r--r--junit4/src/test/java/org/junit/tests/listening/TestListenerTest.java63
-rw-r--r--junit4/src/test/java/org/junit/tests/listening/TextListenerTest.java65
-rw-r--r--junit4/src/test/java/org/junit/tests/listening/UserStopTest.java28
-rw-r--r--junit4/src/test/java/org/junit/tests/manipulation/FilterTest.java49
-rw-r--r--junit4/src/test/java/org/junit/tests/manipulation/FilterableTest.java62
-rw-r--r--junit4/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java168
-rw-r--r--junit4/src/test/java/org/junit/tests/manipulation/SortableTest.java149
-rw-r--r--junit4/src/test/java/org/junit/tests/package-info.java8
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java33
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/EnclosedTest.java40
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java26
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java216
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java171
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java139
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/RunWithTest.java85
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/SuiteTest.java167
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/TestClassTest.java121
-rw-r--r--junit4/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java44
-rw-r--r--junit4/src/test/java/org/junit/tests/running/core/CommandLineTest.java67
-rw-r--r--junit4/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java39
-rw-r--r--junit4/src/test/java/org/junit/tests/running/core/SystemExitTest.java30
-rw-r--r--junit4/src/test/java/org/junit/tests/running/methods/AnnotationTest.java520
-rw-r--r--junit4/src/test/java/org/junit/tests/running/methods/ExpectedTest.java58
-rw-r--r--junit4/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java31
-rw-r--r--junit4/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java102
-rw-r--r--junit4/src/test/java/org/junit/tests/running/methods/TestMethodTest.java147
-rw-r--r--junit4/src/test/java/org/junit/tests/running/methods/TimeoutTest.java170
-rw-r--r--junit4/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java68
-rw-r--r--junit4/src/test/java/org/junit/tests/validation/FailedConstructionTest.java28
-rw-r--r--junit4/src/test/java/org/junit/tests/validation/InaccessibleBaseClassTest.java13
-rw-r--r--junit4/src/test/java/org/junit/tests/validation/ValidationTest.java34
-rw-r--r--junit4/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java5
-rw-r--r--junit4/src/test/java/org/junit/tests/validation/anotherpackage/Super.java7
104 files changed, 9455 insertions, 0 deletions
diff --git a/junit4/src/test/java/org/junit/tests/AllTests.java b/junit4/src/test/java/org/junit/tests/AllTests.java
new file mode 100644
index 0000000..2d459f1
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/AllTests.java
@@ -0,0 +1,163 @@
+package org.junit.tests;
+
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.Test;
+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.deprecated.JUnit4ClassRunnerTest;
+import org.junit.tests.description.AnnotatedDescriptionTest;
+import org.junit.tests.description.SuiteDescriptionTest;
+import org.junit.tests.description.TestDescriptionTest;
+import org.junit.tests.experimental.AssumptionTest;
+import org.junit.tests.experimental.AssumptionViolatedExceptionTest;
+import org.junit.tests.experimental.ExperimentalTests;
+import org.junit.tests.experimental.MatcherTest;
+import org.junit.tests.experimental.categories.CategoriesAndParameterizedTest;
+import org.junit.tests.experimental.categories.CategoryTest;
+import org.junit.tests.experimental.max.JUnit38SortingTest;
+import org.junit.tests.experimental.max.MaxStarterTest;
+import org.junit.tests.experimental.parallel.ParallelClassTest;
+import org.junit.tests.experimental.parallel.ParallelMethodTest;
+import org.junit.tests.experimental.rules.BlockJUnit4ClassRunnerOverrideTest;
+import org.junit.tests.experimental.rules.ClassRulesTest;
+import org.junit.tests.experimental.rules.ExpectedExceptionRuleTest;
+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.RuleChainTest;
+import org.junit.tests.experimental.rules.TempFolderRuleTest;
+import org.junit.tests.experimental.rules.TestRuleTest;
+import org.junit.tests.experimental.rules.TimeoutRuleTest;
+import org.junit.tests.experimental.rules.VerifierRuleTest;
+import org.junit.tests.experimental.theories.AllMembersSupplierTest;
+import org.junit.tests.experimental.theories.runner.TheoriesPerformanceTest;
+import org.junit.tests.junit3compatibility.AllTestsTest;
+import org.junit.tests.junit3compatibility.ClassRequestTest;
+import org.junit.tests.junit3compatibility.ForwardCompatibilityTest;
+import org.junit.tests.junit3compatibility.InitializationErrorForwardCompatibilityTest;
+import org.junit.tests.junit3compatibility.JUnit38ClassRunnerTest;
+import org.junit.tests.junit3compatibility.OldTestClassAdaptingListenerTest;
+import org.junit.tests.junit3compatibility.OldTests;
+import org.junit.tests.junit3compatibility.SuiteMethodTest;
+import org.junit.tests.listening.ListenerTest;
+import org.junit.tests.listening.RunnerTest;
+import org.junit.tests.listening.TestListenerTest;
+import org.junit.tests.listening.TextListenerTest;
+import org.junit.tests.listening.UserStopTest;
+import org.junit.tests.manipulation.FilterTest;
+import org.junit.tests.manipulation.FilterableTest;
+import org.junit.tests.manipulation.SingleMethodTest;
+import org.junit.tests.manipulation.SortableTest;
+import org.junit.tests.running.classes.BlockJUnit4ClassRunnerTest;
+import org.junit.tests.running.classes.EnclosedTest;
+import org.junit.tests.running.classes.IgnoreClassTest;
+import org.junit.tests.running.classes.ParameterizedTestTest;
+import org.junit.tests.running.classes.ParentRunnerFilteringTest;
+import org.junit.tests.running.classes.ParentRunnerTest;
+import org.junit.tests.running.classes.RunWithTest;
+import org.junit.tests.running.classes.SuiteTest;
+import org.junit.tests.running.classes.TestClassTest;
+import org.junit.tests.running.classes.UseSuiteAsASuperclassTest;
+import org.junit.tests.running.core.CommandLineTest;
+import org.junit.tests.running.core.JUnitCoreReturnsCorrectExitCodeTest;
+import org.junit.tests.running.core.SystemExitTest;
+import org.junit.tests.running.methods.AnnotationTest;
+import org.junit.tests.running.methods.ExpectedTest;
+import org.junit.tests.running.methods.InheritedTestTest;
+import org.junit.tests.running.methods.ParameterizedTestMethodTest;
+import org.junit.tests.running.methods.TestMethodTest;
+import org.junit.tests.running.methods.TimeoutTest;
+import org.junit.tests.validation.BadlyFormedClassesTest;
+import org.junit.tests.validation.FailedConstructionTest;
+import org.junit.tests.validation.InaccessibleBaseClassTest;
+import org.junit.tests.validation.ValidationTest;
+
+// These test files need to be cleaned. See
+// https://sourceforge.net/pm/task.php?func=detailtask&project_task_id=136507&group_id=15278&group_project_id=51407
+
+@SuppressWarnings("deprecation")
+@RunWith(Suite.class)
+@SuiteClasses({
+ AssumptionTest.class,
+ ClassRequestTest.class,
+ ListenerTest.class,
+ FailedConstructionTest.class,
+ TestDescriptionTest.class,
+ SuiteDescriptionTest.class,
+ AllTestsTest.class,
+ AnnotationTest.class,
+ AssertionTest.class,
+ CommandLineTest.class,
+ ExpectedTest.class,
+ MultipleFailureExceptionTest.class,
+ ForwardCompatibilityTest.class,
+ OldTests.class,
+ ParameterizedTestTest.class,
+ RunWithTest.class,
+ RunnerTest.class,
+ SuiteTest.class,
+ TestListenerTest.class,
+ TestMethodTest.class,
+ TextListenerTest.class,
+ TimeoutTest.class,
+ EnclosedTest.class,
+ ParameterizedTestMethodTest.class,
+ InitializationErrorForwardCompatibilityTest.class,
+ SingleMethodTest.class,
+ ValidationTest.class,
+ UserStopTest.class,
+ SortableTest.class,
+ JUnit38ClassRunnerTest.class,
+ SystemExitTest.class,
+ JUnitCoreReturnsCorrectExitCodeTest.class,
+ InaccessibleBaseClassTest.class,
+ SuiteMethodTest.class,
+ BadlyFormedClassesTest.class,
+ IgnoreClassTest.class,
+ OldTestClassAdaptingListenerTest.class,
+ AnnotatedDescriptionTest.class,
+ BothTest.class,
+ AssumptionViolatedExceptionTest.class,
+ EachTest.class,
+ ExperimentalTests.class,
+ InheritedTestTest.class,
+ TestClassTest.class,
+ AllMembersSupplierTest.class,
+ MatcherTest.class,
+ ObjectContractTest.class,
+ TheoriesPerformanceTest.class,
+ JUnit4ClassRunnerTest.class,
+ UseSuiteAsASuperclassTest.class,
+ FilterableTest.class,
+ FilterTest.class,
+ MaxStarterTest.class,
+ JUnit38SortingTest.class,
+ MethodRulesTest.class,
+ TestRuleTest.class,
+ TimeoutRuleTest.class,
+ ParallelClassTest.class,
+ ParallelMethodTest.class,
+ ParentRunnerTest.class,
+ NameRulesTest.class,
+ ClassRulesTest.class,
+ ExpectedExceptionRuleTest.class,
+ TempFolderRuleTest.class,
+ ExternalResourceRuleTest.class,
+ VerifierRuleTest.class,
+ CategoryTest.class,
+ CategoriesAndParameterizedTest.class,
+ ParentRunnerFilteringTest.class,
+ RuleChainTest.class,
+ BlockJUnit4ClassRunnerTest.class,
+ BlockJUnit4ClassRunnerOverrideTest.class
+})
+public class AllTests {
+ public static Test suite() {
+ return new JUnit4TestAdapter(AllTests.class);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/ObjectContractTest.java b/junit4/src/test/java/org/junit/tests/ObjectContractTest.java
new file mode 100644
index 0000000..1239527
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/ObjectContractTest.java
@@ -0,0 +1,46 @@
+package org.junit.tests;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeNotNull;
+import static org.junit.Assume.assumeThat;
+
+import java.lang.reflect.Method;
+
+import org.junit.Test;
+import org.junit.Test.None;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+import org.junit.runners.model.FrameworkMethod;
+
+@RunWith(Theories.class)
+public class ObjectContractTest {
+ @DataPoints
+ public static Object[] objects= { new FrameworkMethod(toStringMethod()),
+ new FrameworkMethod(toStringMethod()), 3, null };
+
+ @Theory
+ @Test(expected= None.class)
+ public void equalsThrowsNoException(Object a, Object b) {
+ assumeNotNull(a);
+ a.equals(b);
+ }
+
+ @Theory
+ public void equalsMeansEqualHashCodes(Object a, Object b) {
+ assumeNotNull(a, b);
+ assumeThat(a, is(b));
+ assertThat(a.hashCode(), is(b.hashCode()));
+ }
+
+ private static Method toStringMethod() {
+ try {
+ return Object.class.getMethod("toString");
+ } catch (SecurityException e) {
+ } catch (NoSuchMethodException e) {
+ }
+ return null;
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/TestSystem.java b/junit4/src/test/java/org/junit/tests/TestSystem.java
new file mode 100644
index 0000000..9271d3b
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/TestSystem.java
@@ -0,0 +1,31 @@
+package org.junit.tests;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+import org.junit.internal.JUnitSystem;
+
+public class TestSystem implements JUnitSystem {
+ private PrintStream out;
+ public int fCode;
+ private ByteArrayOutputStream fOutContents;
+
+ public TestSystem() {
+ fOutContents= new ByteArrayOutputStream();
+ out= new PrintStream(fOutContents);
+ }
+
+ public void exit(int code) {
+ fCode= code;
+ }
+
+ public PrintStream out() {
+ return out;
+ }
+
+ public OutputStream outContents() {
+ return fOutContents;
+ }
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/assertion/AssertionTest.java b/junit4/src/test/java/org/junit/tests/assertion/AssertionTest.java
new file mode 100644
index 0000000..dabf065
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/assertion/AssertionTest.java
@@ -0,0 +1,486 @@
+package org.junit.tests.assertion;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+
+import java.math.BigDecimal;
+
+import org.junit.Assert;
+import org.junit.ComparisonFailure;
+import org.junit.Test;
+import org.junit.internal.ArrayComparisonFailure;
+
+/**
+ * Tests for {@link org.junit.Assert}
+ */
+public class AssertionTest {
+// If you want to use 1.4 assertions, they will be reported correctly.
+// However, you need to add the -ea VM argument when running.
+
+// @Test (expected=AssertionError.class) public void error() {
+// assert false;
+// }
+
+ @Test(expected=AssertionError.class) public void fails() {
+ Assert.fail();
+ }
+
+ @Test public void failWithNoMessageToString() {
+ try {
+ Assert.fail();
+ } catch (AssertionError exception) {
+ assertEquals("java.lang.AssertionError", exception.toString());
+ }
+ }
+
+ @Test public void failWithMessageToString() {
+ try {
+ Assert.fail("woops!");
+ } catch (AssertionError exception) {
+ assertEquals("java.lang.AssertionError: woops!", exception.toString());
+ }
+ }
+
+ @Test(expected= AssertionError.class) public void arraysNotEqual() {
+ assertArrayEquals((new Object[] {new Object()}), (new Object[] {new Object()}));
+ }
+
+ @Test(expected= AssertionError.class) public void arraysNotEqualWithMessage() {
+ assertArrayEquals("not equal", (new Object[] {new Object()}), (new Object[] {new Object()}));
+ }
+
+ @Test public void arraysExpectedNullMessage() {
+ try {
+ assertArrayEquals("not equal", null, (new Object[] {new Object()}));
+ } catch (AssertionError exception) {
+ assertEquals("not equal: expected array was null", exception.getMessage());
+ }
+ }
+
+ @Test public void arraysActualNullMessage() {
+ try {
+ assertArrayEquals("not equal", (new Object[] {new Object()}), null);
+ } catch (AssertionError exception) {
+ assertEquals("not equal: actual array was null", exception.getMessage());
+ }
+ }
+
+ @Test public void arraysDifferentLengthMessage() {
+ try {
+ assertArrayEquals("not equal", (new Object[0]), (new Object[1]));
+ } catch (AssertionError exception) {
+ assertEquals("not equal: array lengths differed, expected.length=0 actual.length=1", exception.getMessage());
+ }
+ }
+
+ @Test(expected=ArrayComparisonFailure.class) public void arraysElementsDiffer() {
+ assertArrayEquals("not equal", (new Object[] {"this is a very long string in the middle of an array"}), (new Object[] {"this is another very long string in the middle of an array"}));
+ }
+
+ @Test public void arraysDifferAtElement0nullMessage() {
+ try {
+ assertArrayEquals((new Object[] { true }), (new Object[] { false }));
+ } catch (AssertionError exception) {
+ assertEquals("arrays first differed at element [0]; expected:<true> but was:<false>", exception
+ .getMessage());
+ }
+ }
+
+ @Test public void arraysDifferAtElement1nullMessage() {
+ try {
+ assertArrayEquals((new Object[] { true, true }), (new Object[] { true,
+ false }));
+ } catch (AssertionError exception) {
+ assertEquals("arrays first differed at element [1]; expected:<true> but was:<false>", exception
+ .getMessage());
+ }
+ }
+
+ @Test public void arraysDifferAtElement0withMessage() {
+ try {
+ assertArrayEquals("message", (new Object[] { true }), (new Object[] { false }));
+ } catch (AssertionError exception) {
+ assertEquals("message: arrays first differed at element [0]; expected:<true> but was:<false>", exception
+ .getMessage());
+ }
+ }
+
+ @Test public void arraysDifferAtElement1withMessage() {
+ try {
+ assertArrayEquals("message", (new Object[] {true, true}), (new Object[] {true, false}));
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("message: arrays first differed at element [1]; expected:<true> but was:<false>", exception.getMessage());
+ }
+ }
+
+ @Test public void multiDimensionalArraysAreEqual() {
+ assertArrayEquals((new Object[][]{{true, true}, {false, false}}), (new Object[][]{{true, true}, {false, false}}));
+ }
+
+ @Test
+ public void multiDimensionalIntArraysAreEqual() {
+ int[][] int1= { { 1, 2, 3 }, { 4, 5, 6 } };
+ int[][] int2= { { 1, 2, 3 }, { 4, 5, 6 } };
+ assertArrayEquals(int1, int2);
+ }
+
+ @Test
+ public void oneDimensionalPrimitiveArraysAreEqual() {
+ assertArrayEquals(new byte[] {1}, new byte[] {1});
+ assertArrayEquals(new char[] {1}, new char[] {1});
+ assertArrayEquals(new short[] {1}, new short[] {1});
+ assertArrayEquals(new int[] {1}, new int[] {1});
+ assertArrayEquals(new long[] {1}, new long[] {1});
+ assertArrayEquals(new double[] {1.0}, new double[] {1.0}, 1.0);
+ assertArrayEquals(new float[] {1.0f}, new float[] {1.0f}, 1.0f);
+ }
+
+ @Test(expected=AssertionError.class)
+ public void oneDimensionalDoubleArraysAreNotEqual() {
+ assertArrayEquals(new double[] {1.0}, new double[] {2.5}, 1.0);
+ }
+
+ @Test(expected=AssertionError.class)
+ public void oneDimensionalFloatArraysAreNotEqual() {
+ assertArrayEquals(new float[] {1.0f}, new float[] {2.5f}, 1.0f);
+ }
+
+ @Test(expected=AssertionError.class)
+ public void IntegerDoesNotEqualLong() {
+ assertEquals(new Integer(1), new Long(1));
+ }
+
+ @Test public void intsEqualLongs() {
+ assertEquals(1, 1L);
+ }
+
+ @Test public void multiDimensionalArraysDeclaredAsOneDimensionalAreEqual() {
+ assertArrayEquals((new Object[]{new Object[] {true, true}, new Object[] {false, false}}), (new Object[]{new Object[] {true, true}, new Object[] {false, false}}));
+ }
+
+ @Test public void multiDimensionalArraysAreNotEqual() {
+ try {
+ assertArrayEquals("message", (new Object[][]{{true, true}, {false, false}}), (new Object[][]{{true, true}, {true, false}}));
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("message: arrays first differed at element [1][0]; expected:<false> but was:<true>", exception.getMessage());
+ }
+ }
+
+ @Test public void multiDimensionalArraysAreNotEqualNoMessage() {
+ try {
+ assertArrayEquals((new Object[][]{{true, true}, {false, false}}), (new Object[][]{{true, true}, {true, false}}));
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("arrays first differed at element [1][0]; expected:<false> but was:<true>", exception.getMessage());
+ }
+ }
+
+ @Test public void arraysWithNullElementEqual() {
+ Object[] objects1 = new Object[] {null};
+ Object[] objects2 = new Object[] {null};
+ assertArrayEquals(objects1, objects2);
+ }
+
+ @Test public void stringsDifferWithUserMessage() {
+ try {
+ assertEquals("not equal", "one", "two");
+ } catch (Throwable exception) {
+ assertEquals("not equal expected:<[one]> but was:<[two]>", exception.getMessage());
+ }
+ }
+
+ @Test public void arraysEqual() {
+ Object element= new Object();
+ Object[] objects1= new Object[] {element};
+ Object[] objects2= new Object[] {element};
+ assertArrayEquals(objects1, objects2);
+ }
+
+ @Test public void arraysEqualWithMessage() {
+ Object element= new Object();
+ Object[] objects1= new Object[] {element};
+ Object[] objects2= new Object[] {element};
+ assertArrayEquals("equal", objects1, objects2);
+ }
+
+ @Test public void equals() {
+ Object o= new Object();
+ assertEquals(o, o);
+ assertEquals("abc", "abc");
+ assertEquals(true, true);
+ assertEquals((byte) 1, (byte) 1);
+ assertEquals('a', 'a');
+ assertEquals((short) 1, (short) 1);
+ assertEquals(1, 1); // int by default, cast is unnecessary
+ assertEquals(1l, 1l);
+ assertEquals(1.0, 1.0, 0.0);
+ assertEquals(1.0d, 1.0d, 0.0d);
+ }
+
+ @Test(expected= AssertionError.class) public void notEqualsObjectWithNull() {
+ assertEquals(new Object(), null);
+ }
+
+ @Test(expected= AssertionError.class) public void notEqualsNullWithObject() {
+ assertEquals(null, new Object());
+ }
+
+ @Test public void notEqualsObjectWithNullWithMessage() {
+ Object o = new Object();
+ try {
+ assertEquals("message", null, o);
+ fail();
+ }
+ catch(AssertionError e) {
+ assertEquals("message expected:<null> but was:<" + o.toString() + ">", e.getMessage());
+ }
+ }
+
+ @Test public void notEqualsNullWithObjectWithMessage() {
+ Object o = new Object();
+ try {
+ assertEquals("message", o, null);
+ fail();
+ }
+ catch(AssertionError e) {
+ assertEquals("message expected:<"+ o.toString() + "> but was:<null>", e.getMessage());
+ }
+ }
+
+ @Test(expected= AssertionError.class) public void objectsNotEquals() {
+ assertEquals(new Object(), new Object());
+ }
+
+ @Test(expected= ComparisonFailure.class) public void stringsNotEqual() {
+ assertEquals("abc", "def");
+ }
+
+ @Test(expected= AssertionError.class) public void booleansNotEqual() {
+ assertEquals(true, false);
+ }
+
+ @Test(expected= AssertionError.class) public void bytesNotEqual() {
+ assertEquals((byte) 1, (byte) 2);
+ }
+
+ @Test(expected= AssertionError.class) public void charsNotEqual() {
+ assertEquals('a', 'b');
+ }
+
+ @Test(expected= AssertionError.class) public void shortsNotEqual() {
+ assertEquals((short) 1, (short) 2);
+ }
+
+ @Test(expected= AssertionError.class) public void intsNotEqual() {
+ assertEquals(1, 2);
+ }
+
+ @Test(expected= AssertionError.class) public void longsNotEqual() {
+ assertEquals(1l, 2l);
+ }
+
+ @Test(expected= AssertionError.class) public void floatsNotEqual() {
+ assertEquals(1.0, 2.0, 0.9);
+ }
+
+ @SuppressWarnings("deprecation")
+ @Test(expected= AssertionError.class) public void floatsNotEqualWithoutDelta() {
+ assertEquals(1.0, 1.1);
+ }
+
+ @Test(expected= AssertionError.class) public void bigDecimalsNotEqual() {
+ assertEquals(new BigDecimal("123.4"), new BigDecimal("123.0"));
+ }
+
+
+ @Test(expected= AssertionError.class) public void doublesNotEqual() {
+ assertEquals(1.0d, 2.0d, 0.9d);
+ }
+
+ @Test public void naNsAreEqual() {
+ assertEquals(Float.NaN, Float.NaN, Float.POSITIVE_INFINITY);
+ assertEquals(Double.NaN, Double.NaN, Double.POSITIVE_INFINITY);
+ }
+
+ @Test public void same() {
+ Object o1= new Object();
+ assertSame(o1, o1);
+ }
+
+ @Test public void notSame() {
+ Object o1= new Object();
+ Object o2= new Object();
+ assertNotSame(o1, o2);
+ }
+
+ @Test(expected= AssertionError.class) public void objectsNotSame() {
+ assertSame(new Object(), new Object());
+ }
+
+ @Test(expected= AssertionError.class) public void objectsAreSame() {
+ Object o= new Object();
+ assertNotSame(o, o);
+ }
+
+ @Test public void sameWithMessage() {
+ try {
+ assertSame("not same", "hello", "good-bye");
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("not same expected same:<hello> was not:<good-bye>",
+ exception.getMessage());
+ }
+ }
+
+ @Test public void sameNullMessage() {
+ try {
+ assertSame("hello", "good-bye");
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("expected same:<hello> was not:<good-bye>", exception.getMessage());
+ }
+ }
+
+ @Test public void notSameWithMessage() {
+ Object o= new Object();
+ try {
+ assertNotSame("message", o, o);
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("message expected not same", exception.getMessage());
+ }
+ }
+
+ @Test public void notSameNullMessage() {
+ Object o= new Object();
+ try {
+ assertNotSame(o, o);
+ fail();
+ } catch (AssertionError exception) {
+ assertEquals("expected not same", exception.getMessage());
+ }
+ }
+
+ @Test public void nullMessage() {
+ try {
+ fail(null);
+ } catch (AssertionError exception) {
+ // we used to expect getMessage() to return ""; see failWithNoMessageToString()
+ assertNull(exception.getMessage());
+ }
+ }
+
+ @Test public void nullMessageDisappearsWithStringAssertEquals() {
+ try {
+ assertEquals(null, "a", "b");
+ fail();
+ } catch (ComparisonFailure e) {
+ assertEquals("expected:<[a]> but was:<[b]>", e.getMessage());
+ }
+ }
+
+ @Test public void nullMessageDisappearsWithAssertEquals() {
+ try {
+ assertEquals(null, 1, 2);
+ fail();
+ } catch (AssertionError e) {
+ assertEquals("expected:<1> but was:<2>", e.getMessage());
+ }
+ }
+
+ @Test(expected=AssertionError.class)
+ public void arraysDeclaredAsObjectAreComparedAsObjects() {
+ Object a1= new Object[] {"abc"};
+ Object a2= new Object[] {"abc"};
+ assertEquals(a1, a2);
+ }
+
+ @Test public void implicitTypecastEquality() {
+ byte b = 1;
+ short s = 1;
+ int i = 1;
+ long l = 1L;
+ float f = 1.0f;
+ double d = 1.0;
+
+ assertEquals(b, s);
+ assertEquals(b, i);
+ assertEquals(b, l);
+ assertEquals(s, i);
+ assertEquals(s, l);
+ assertEquals(i, l);
+ assertEquals(f, d, 0);
+ }
+
+ @Test public void errorMessageDistinguishesDifferentValuesWithSameToString() {
+ try {
+ assertEquals("4", new Integer(4));
+ } catch (AssertionError e) {
+ assertEquals("expected: java.lang.String<4> but was: java.lang.Integer<4>", e.getMessage());
+ }
+ }
+
+ @Test public void assertThatIncludesDescriptionOfTestedValueInErrorMessage() {
+ String expected = "expected";
+ String actual = "actual";
+
+ String expectedMessage = "identifier\nExpected: \"expected\"\n got: \"actual\"\n";
+
+ try {
+ assertThat("identifier", actual, equalTo(expected));
+ } catch (AssertionError e) {
+ assertEquals(expectedMessage, e.getMessage());
+ }
+ }
+
+ @Test public void assertThatIncludesAdvancedMismatch() {
+ String expectedMessage = "identifier\nExpected: is an instance of java.lang.Integer\n got: \"actual\"\n";
+
+ try {
+ assertThat("identifier", "actual", is(Integer.class));
+ } catch (AssertionError e) {
+ assertEquals(expectedMessage, e.getMessage());
+ }
+ }
+
+ @Test public void assertThatDescriptionCanBeElided() {
+ String expected = "expected";
+ String actual = "actual";
+
+ String expectedMessage = "\nExpected: \"expected\"\n got: \"actual\"\n";
+
+ try {
+ assertThat(actual, equalTo(expected));
+ } catch (AssertionError e) {
+ assertEquals(expectedMessage, e.getMessage());
+ }
+ }
+
+ @Test public void nullAndStringNullPrintCorrectError() {
+ try {
+ assertEquals(null, "null");
+ } catch (AssertionError e) {
+ assertEquals("expected: null<null> but was: java.lang.String<null>", e.getMessage());
+ }
+ }
+
+ @Test(expected=AssertionError.class) public void stringNullAndNullWorksToo() {
+ assertEquals("null", null);
+ }
+
+ @Test(expected=AssertionError.class)
+ public void compareBigDecimalAndInteger() {
+ final BigDecimal bigDecimal = new BigDecimal("1.2");
+ final Integer integer = Integer.valueOf("1");
+ assertEquals(bigDecimal, integer);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/assertion/BothTest.java b/junit4/src/test/java/org/junit/tests/assertion/BothTest.java
new file mode 100644
index 0000000..fd51a09
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/assertion/BothTest.java
@@ -0,0 +1,71 @@
+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)));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/assertion/EachTest.java b/junit4/src/test/java/org/junit/tests/assertion/EachTest.java
new file mode 100644
index 0000000..16327e2
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/assertion/EachTest.java
@@ -0,0 +1,13 @@
+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\""));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java b/junit4/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java
new file mode 100644
index 0000000..1ddbcea
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java
@@ -0,0 +1,60 @@
+// Copyright 2010 Google Inc. All Rights Reserved.
+
+package org.junit.tests.assertion;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runners.model.MultipleFailureException;
+
+/**
+ * Tests for {@link org.junit.runners.model.MultipleFailureException}
+ *
+ * @author kcooney@google.com (Kevin Cooney)
+ */
+public class MultipleFailureExceptionTest {
+
+ @Test
+ public void assertEmptyDoesNotThrowForEmptyList() throws Throwable {
+ MultipleFailureException.assertEmpty(Collections.<Throwable>emptyList());
+ }
+
+ @Test(expected=ExpectedException.class)
+ public void assertEmptyRethrowsSingleThrowable() throws Throwable {
+ MultipleFailureException.assertEmpty(
+ Collections.<Throwable>singletonList(new ExpectedException("pesto")));
+ }
+
+ @Test
+ public void assertEmptyThrowsMutipleFailureExceptionForManyThrowables() throws Throwable {
+ List<Throwable> errors = new ArrayList<Throwable>();
+ errors.add(new ExpectedException("basil"));
+ errors.add(new RuntimeException("garlic"));
+
+ try {
+ MultipleFailureException.assertEmpty(errors);
+ fail();
+ } catch (MultipleFailureException expected) {
+ assertThat(expected.getFailures(), equalTo(errors));
+ assertTrue(expected.getMessage().startsWith("There were 2 errors:\n"));
+ assertTrue(expected.getMessage().contains("ExpectedException(basil)\n"));
+ assertTrue(expected.getMessage().contains("RuntimeException(garlic)"));
+ }
+ }
+
+
+ private static class ExpectedException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
+
+ public ExpectedException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java b/junit4/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java
new file mode 100644
index 0000000..7cdfbb7
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java
@@ -0,0 +1,54 @@
+package org.junit.tests.deprecated;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+import org.junit.internal.runners.JUnit4ClassRunner;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+
+/*
+ * @deprecated This is a simple smoke test to make sure the old JUnit4ClassRunner basically works.
+ * Delete this test when JUnit4ClassRunner goes to the Great Heap In The Sky.
+ */
+@Deprecated
+public class JUnit4ClassRunnerTest {
+
+ @SuppressWarnings("deprecation")
+ @RunWith(JUnit4ClassRunner.class)
+ public static class Example {
+ @Test public void success() {}
+ @Test public void failure() {
+ fail();
+ }
+ }
+
+ @Test
+ public void runWithOldJUnit4ClassRunner() {
+ Result result= JUnitCore.runClasses(Example.class);
+ assertThat(result.getRunCount(), is(2));
+ assertThat(result.getFailureCount(), is(1));
+ }
+
+ @SuppressWarnings("deprecation")
+ @RunWith(JUnit4ClassRunner.class)
+ public static class UnconstructableExample {
+ public UnconstructableExample() {
+ throw new UnsupportedOperationException();
+ }
+ @Test public void success() {}
+ @Test public void failure() {
+ fail();
+ }
+ }
+
+
+ @Test
+ public void runWithOldJUnit4ClassRunnerAndBadConstructor() {
+ Result result= JUnitCore.runClasses(UnconstructableExample.class);
+ assertThat(result.getRunCount(), is(2));
+ assertThat(result.getFailureCount(), is(2));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java b/junit4/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java
new file mode 100644
index 0000000..370293b
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java
@@ -0,0 +1,96 @@
+package org.junit.tests.description;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.Request;
+
+public class AnnotatedDescriptionTest {
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface MyOwnAnnotation {
+
+ }
+
+ @MyOwnAnnotation
+ public static class AnnotatedClass {
+ @Test
+ public void a() {
+ }
+ }
+
+ @Test
+ public void annotationsExistOnDescriptionsOfClasses() {
+ assertTrue((describe(AnnotatedClass.class).getAnnotation(
+ MyOwnAnnotation.class) != null));
+ }
+
+ @Test
+ public void getAnnotationsReturnsAllAnnotations() {
+ assertEquals(1, describe(ValueAnnotatedClass.class).getAnnotations()
+ .size());
+ }
+
+ @Ignore
+ public static class IgnoredClass {
+ @Test
+ public void a() {
+ }
+ }
+
+ @Test
+ public void annotationsExistOnDescriptionsOfIgnoredClass() {
+ assertTrue((describe(IgnoredClass.class).getAnnotation(Ignore.class) != null));
+ }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface ValuedAnnotation {
+ String value();
+ }
+
+ @ValuedAnnotation("hello")
+ public static class ValueAnnotatedClass {
+ @Test
+ public void a() {
+ }
+ }
+
+ @Test
+ public void descriptionOfTestClassHasValuedAnnotation() {
+ Description description= describe(ValueAnnotatedClass.class);
+ assertEquals("hello", description.getAnnotation(ValuedAnnotation.class)
+ .value());
+ }
+
+ @Test
+ public void childlessCopyOfDescriptionStillHasAnnotations() {
+ Description description= describe(ValueAnnotatedClass.class);
+ assertEquals("hello", description.childlessCopy().getAnnotation(ValuedAnnotation.class)
+ .value());
+ }
+
+ @Test
+ public void characterizeCreatingMyOwnAnnotation() {
+ Annotation annotation= new Ignore() {
+ public String value() {
+ return "message";
+ }
+
+ public Class<? extends Annotation> annotationType() {
+ return Ignore.class;
+ }
+ };
+
+ assertEquals(Ignore.class, annotation.annotationType());
+ }
+
+ private Description describe(Class<?> testClass) {
+ return Request.aClass(testClass).getRunner().getDescription();
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java b/junit4/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java
new file mode 100644
index 0000000..8124b01
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java
@@ -0,0 +1,35 @@
+package org.junit.tests.description;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import org.junit.Test;
+import org.junit.runner.Description;
+
+public class SuiteDescriptionTest {
+ Description childless = Description.createSuiteDescription("a");
+ Description anotherChildless = Description.createSuiteDescription("a");
+ Description namedB = Description.createSuiteDescription("b");
+
+ Description twoKids = descriptionWithTwoKids("foo", "bar");
+ Description anotherTwoKids = descriptionWithTwoKids("foo", "baz");
+
+ @Test public void equalsIsCorrect() {
+ assertEquals(childless, anotherChildless);
+ assertFalse(childless.equals(namedB));
+ assertEquals(childless, twoKids);
+ assertEquals(twoKids, anotherTwoKids);
+ assertFalse(twoKids.equals(new Integer(5)));
+ }
+
+ @Test public void hashCodeIsReasonable() {
+ assertEquals(childless.hashCode(), anotherChildless.hashCode());
+ assertFalse(childless.hashCode() == namedB.hashCode());
+ }
+
+ private Description descriptionWithTwoKids(String first, String second) {
+ Description twoKids = Description.createSuiteDescription("a");
+ twoKids.addChild(Description.createTestDescription(getClass(), first));
+ twoKids.addChild(Description.createTestDescription(getClass(), second));
+ return twoKids;
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/description/TestDescriptionTest.java b/junit4/src/test/java/org/junit/tests/description/TestDescriptionTest.java
new file mode 100644
index 0000000..7d6c8a5
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/description/TestDescriptionTest.java
@@ -0,0 +1,11 @@
+package org.junit.tests.description;
+
+import static org.junit.Assert.assertFalse;
+import org.junit.Test;
+import org.junit.runner.Description;
+
+public class TestDescriptionTest {
+ @Test public void equalsIsFalseForNonTestDescription() {
+ assertFalse(Description.createTestDescription(getClass(), "a").equals(new Integer(5)));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/AssumptionTest.java b/junit4/src/test/java/org/junit/tests/experimental/AssumptionTest.java
new file mode 100644
index 0000000..3c0fd9c
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/AssumptionTest.java
@@ -0,0 +1,177 @@
+package org.junit.tests.experimental;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeNoException;
+import static org.junit.Assume.assumeNotNull;
+import static org.junit.Assume.assumeThat;
+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;
+import org.junit.Test;
+import org.junit.internal.AssumptionViolatedException;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+
+public class AssumptionTest {
+ public static class HasFailingAssumption {
+ @Test
+ public void assumptionsFail() {
+ assumeThat(3, is(4));
+ fail();
+ }
+ }
+
+ @Test
+ public void failedAssumptionsMeanPassing() {
+ Result result= JUnitCore.runClasses(HasFailingAssumption.class);
+ assertThat(result.getRunCount(), is(1));
+ assertThat(result.getIgnoreCount(), is(0));
+ assertThat(result.getFailureCount(), is(0));
+ }
+
+ private static int assumptionFailures= 0;
+ @Test
+ public void failedAssumptionsCanBeDetectedByListeners() {
+ assumptionFailures= 0;
+ JUnitCore core= new JUnitCore();
+ core.addListener(new RunListener() {
+ @Override
+ public void testAssumptionFailure(Failure failure) {
+ assumptionFailures++;
+ }
+ });
+ core.run(HasFailingAssumption.class);
+
+ assertThat(assumptionFailures, is(1));
+ }
+
+ public static class HasPassingAssumption {
+ @Test
+ public void assumptionsFail() {
+ assumeThat(3, is(3));
+ fail();
+ }
+ }
+
+ @Test
+ public void passingAssumptionsScootThrough() {
+ Result result= JUnitCore.runClasses(HasPassingAssumption.class);
+ assertThat(result.getRunCount(), is(1));
+ assertThat(result.getIgnoreCount(), is(0));
+ assertThat(result.getFailureCount(), is(1));
+ }
+
+ @Test(expected= AssumptionViolatedException.class)
+ public void assumeThatWorks() {
+ assumeThat(1, is(2));
+ }
+
+ @Test
+ public void assumeThatPasses() {
+ assumeThat(1, is(1));
+ assertCompletesNormally();
+ }
+
+ @Test
+ public void assumeThatPassesOnStrings() {
+ assumeThat("x", is("x"));
+ assertCompletesNormally();
+ }
+
+ @Test(expected= AssumptionViolatedException.class)
+ public void assumeNotNullThrowsException() {
+ Object[] objects= { 1, 2, null };
+ assumeNotNull(objects);
+ }
+
+ @Test
+ public void assumeNotNullPasses() {
+ Object[] objects= { 1, 2 };
+ assumeNotNull(objects);
+ assertCompletesNormally();
+ }
+
+ @Test
+ public void assumeNotNullIncludesParameterList() {
+ try {
+ Object[] objects= { 1, 2, null };
+ assumeNotNull(objects);
+ } catch (AssumptionViolatedException e) {
+ assertThat(e.getMessage(), containsString("1, 2, null"));
+ } catch (Exception e) {
+ fail("Should have thrown AssumptionViolatedException");
+ }
+ }
+ @Test
+ public void assumeNoExceptionThrows() {
+ final Throwable exception= new NullPointerException();
+ try {
+ assumeNoException(exception);
+ fail("Should have thrown exception");
+ } catch (AssumptionViolatedException e) {
+ assertThat(e.getCause(), is(exception));
+ }
+ }
+
+ private void assertCompletesNormally() {
+ }
+
+ @Test(expected=AssumptionViolatedException.class) public void assumeTrueWorks() {
+ Assume.assumeTrue(false);
+ }
+
+ public static class HasFailingAssumeInBefore {
+ @Before public void checkForSomethingThatIsntThere() {
+ assumeTrue(false);
+ }
+
+ @Test public void failing() {
+ fail();
+ }
+ }
+
+ @Test public void failingAssumptionInBeforePreventsTestRun() {
+ assertThat(testResult(HasFailingAssumeInBefore.class), isSuccessful());
+ }
+
+ public static class HasFailingAssumeInBeforeClass {
+ @BeforeClass public static void checkForSomethingThatIsntThere() {
+ assumeTrue(false);
+ }
+
+ @Test public void failing() {
+ fail();
+ }
+ }
+
+ @Test public void failingAssumptionInBeforeClassIgnoresClass() {
+ assertThat(testResult(HasFailingAssumeInBeforeClass.class), isSuccessful());
+ }
+
+ public static class AssumptionFailureInConstructor {
+ public AssumptionFailureInConstructor() {
+ assumeTrue(false);
+ }
+
+ @Test public void shouldFail() {
+ fail();
+ }
+ }
+
+ @Test public void failingAssumptionInConstructorIgnoresClass() {
+ assertThat(testResult(AssumptionFailureInConstructor.class), isSuccessful());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void assumeWithExpectedException() {
+ assumeTrue(false);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java b/junit4/src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java
new file mode 100644
index 0000000..f1cb955
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java
@@ -0,0 +1,52 @@
+package org.junit.tests.experimental;
+
+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;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.internal.AssumptionViolatedException;
+import org.junit.runner.RunWith;
+
+@RunWith(Theories.class)
+public class AssumptionViolatedExceptionTest {
+ @DataPoint
+ public static Object TWO= 2;
+
+ @DataPoint
+ public static Matcher<?> IS_THREE= is(3);
+
+ @DataPoint
+ public static Matcher<?> NULL= null;
+
+ @Theory
+ public void toStringReportsMatcher(Object actual, Matcher<?> matcher) {
+ assumeThat(matcher, notNullValue());
+ assertThat(new AssumptionViolatedException(actual, matcher).toString(),
+ containsString(matcher.toString()));
+ }
+
+ @Theory
+ public void toStringReportsValue(Object actual, Matcher<?> matcher) {
+ assertThat(new AssumptionViolatedException(actual, matcher).toString(),
+ containsString(String.valueOf(actual)));
+ }
+
+ @Test
+ public void AssumptionViolatedExceptionDescribesItself() {
+ AssumptionViolatedException e= new AssumptionViolatedException(3, is(2));
+ assertThat(StringDescription.asString(e), is("got: <3>, expected: is <2>"));
+ }
+
+ @Test
+ public void simpleAssumptionViolatedExceptionDescribesItself() {
+ AssumptionViolatedException e= new AssumptionViolatedException("not enough money");
+ assertThat(StringDescription.asString(e), is("failed assumption: not enough money"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/ExperimentalTests.java b/junit4/src/test/java/org/junit/tests/experimental/ExperimentalTests.java
new file mode 100644
index 0000000..7ac7714
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/ExperimentalTests.java
@@ -0,0 +1,28 @@
+package org.junit.tests.experimental;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+import org.junit.tests.experimental.results.PrintableResultTest;
+import org.junit.tests.experimental.results.ResultMatchersTest;
+import org.junit.tests.experimental.theories.ParameterSignatureTest;
+import org.junit.tests.experimental.theories.ParameterizedAssertionErrorTest;
+import org.junit.tests.experimental.theories.extendingwithstubs.StubbedTheoriesTest;
+import org.junit.tests.experimental.theories.runner.SuccessfulWithDataPointFields;
+import org.junit.tests.experimental.theories.runner.UnsuccessfulWithDataPointFields;
+import org.junit.tests.experimental.theories.runner.WhenNoParametersMatch;
+import org.junit.tests.experimental.theories.runner.WithDataPointMethod;
+import org.junit.tests.experimental.theories.runner.WithExtendedParameterSources;
+import org.junit.tests.experimental.theories.runner.WithOnlyTestAnnotations;
+
+@RunWith(Suite.class)
+@SuiteClasses( { ParameterizedAssertionErrorTest.class,
+ UnsuccessfulWithDataPointFields.class,
+ SuccessfulWithDataPointFields.class, PrintableResultTest.class,
+ ResultMatchersTest.class, WithDataPointMethod.class,
+ ParameterSignatureTest.class, WhenNoParametersMatch.class,
+ WithExtendedParameterSources.class, StubbedTheoriesTest.class,
+ WithOnlyTestAnnotations.class })
+public class ExperimentalTests {
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/MatcherTest.java b/junit4/src/test/java/org/junit/tests/experimental/MatcherTest.java
new file mode 100644
index 0000000..6b01179
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/MatcherTest.java
@@ -0,0 +1,43 @@
+package org.junit.tests.experimental;
+
+import static org.hamcrest.CoreMatchers.not;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeThat;
+import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;
+import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;
+
+import java.util.Arrays;
+
+import org.hamcrest.Matcher;
+import org.junit.experimental.results.PrintableResult;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.Description;
+import org.junit.runner.RunWith;
+import org.junit.runner.notification.Failure;
+
+@RunWith(Theories.class)
+public class MatcherTest {
+ @DataPoint
+ public static Matcher<?> SINGLE_FAILURE= hasSingleFailureContaining("cheese");
+
+ @DataPoint
+ public static Matcher<?> ANY_FAILURE= hasFailureContaining("cheese");
+
+ @DataPoint
+ public static PrintableResult TWO_FAILURES_ONE_CHEESE= new PrintableResult(
+ Arrays.asList(failure("cheese"), failure("mustard")));
+
+ @Theory
+ public <T> void differentMatchersHaveDifferentDescriptions(
+ Matcher<T> matcher1, Matcher<T> matcher2, T value) {
+ assumeThat(value, matcher1);
+ assumeThat(value, not(matcher2));
+ assertThat(matcher1.toString(), not(matcher2.toString()));
+ }
+
+ private static Failure failure(String string) {
+ return new Failure(Description.EMPTY, new Error(string));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.java b/junit4/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.java
new file mode 100644
index 0000000..f589aea
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.java
@@ -0,0 +1,123 @@
+package org.junit.tests.experimental.categories;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+
+import java.util.Collection;
+import java.util.Collections;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.experimental.categories.Categories;
+import org.junit.experimental.categories.Categories.IncludeCategory;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+import org.junit.runners.Suite.SuiteClasses;
+
+public class CategoriesAndParameterizedTest {
+ public static class Token {
+
+ }
+
+ @RunWith(Parameterized.class)
+ public static class WellBehavedParameterizedTest {
+ public WellBehavedParameterizedTest(String a) {
+ }
+
+ @Parameters
+ public static Collection<Object[]> getParameters() {
+ return Collections.singletonList(new Object[] { "a" });
+ }
+
+ @Test
+ public void testSomething() {
+ Assert.assertTrue(true);
+ }
+ }
+
+ @RunWith(Parameterized.class)
+ public static class ParameterizedTestWithAttemptedMethodCategory {
+ public ParameterizedTestWithAttemptedMethodCategory(String a) {
+ }
+
+ @Parameters
+ public static Collection<Object[]> getParameters() {
+ return Collections.singletonList(new Object[] { "a" });
+ }
+
+ @Test
+ @Category(Token.class)
+ public void testSomething() {
+ Assert.assertTrue(true);
+ }
+ }
+
+ @RunWith(Parameterized.class)
+ @Category(Token.class)
+ public static class ParameterizedTestWithClassCategory {
+ public ParameterizedTestWithClassCategory(String a) {
+ }
+
+ @Parameters
+ public static Collection<Object[]> getParameters() {
+ return Collections.singletonList(new Object[] { "a" });
+ }
+
+ @Test
+ public void testSomething() {
+ Assert.assertTrue(true);
+ }
+ }
+
+ @Category(Token.class)
+ public static class VanillaCategorizedJUnitTest {
+ @Test
+ public void testSomething() {
+ Assert.assertTrue(true);
+ }
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(Token.class)
+ @SuiteClasses({ VanillaCategorizedJUnitTest.class,
+ WellBehavedParameterizedTest.class,
+ ParameterizedTestWithClassCategory.class })
+ public static class ParameterTokenSuiteWellFormed {
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(Token.class)
+ @SuiteClasses({ ParameterizedTestWithAttemptedMethodCategory.class, VanillaCategorizedJUnitTest.class })
+ public static class ParameterTokenSuiteMalformed {
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(Token.class)
+ @SuiteClasses({ VanillaCategorizedJUnitTest.class, ParameterizedTestWithAttemptedMethodCategory.class })
+ public static class ParameterTokenSuiteMalformedAndSwapped {
+ }
+
+ @Test
+ public void shouldSucceedWithAParameterizedClassSomewhere() {
+ assertThat(testResult(ParameterTokenSuiteWellFormed.class),
+ isSuccessful());
+ }
+
+ @Test
+ public void shouldFailWithMethodLevelCategoryAnnotation() {
+ assertThat(
+ testResult(ParameterTokenSuiteMalformed.class),
+ hasFailureContaining("Category annotations on Parameterized classes are not supported on individual methods."));
+ }
+
+ @Test
+ public void shouldFailWithMethodLevelCategoryAnnotationSwapped() {
+ assertThat(
+ testResult(ParameterTokenSuiteMalformedAndSwapped.class),
+ hasFailureContaining("Category annotations on Parameterized classes are not supported on individual methods."));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/categories/CategoryTest.java b/junit4/src/test/java/org/junit/tests/experimental/categories/CategoryTest.java
new file mode 100644
index 0000000..b316731
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/categories/CategoryTest.java
@@ -0,0 +1,254 @@
+package org.junit.tests.experimental.categories;
+
+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.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import org.junit.Test;
+import org.junit.experimental.categories.Categories;
+import org.junit.experimental.categories.Category;
+import org.junit.experimental.categories.Categories.CategoryFilter;
+import org.junit.experimental.categories.Categories.ExcludeCategory;
+import org.junit.experimental.categories.Categories.IncludeCategory;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+import org.junit.runners.model.InitializationError;
+
+public class CategoryTest {
+ public interface FastTests {
+ // category marker
+ }
+
+ public interface SlowTests {
+ // category marker
+ }
+
+ public static class A {
+ @Test
+ public void a() {
+ fail();
+ }
+
+ @Category(SlowTests.class)
+ @Test
+ public void b() {
+ }
+ }
+
+ @Category(SlowTests.class)
+ public static class B {
+ @Test
+ public void c() {
+
+ }
+ }
+
+ public static class C {
+ @Test
+ public void d() {
+ fail();
+ }
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(SlowTests.class)
+ @SuiteClasses( { A.class, B.class, C.class })
+ public static class SlowTestSuite {
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(SlowTests.class)
+ @SuiteClasses( { A.class })
+ public static class JustA {
+ }
+
+ @Test
+ public void testCountOnJustA() {
+ assertThat(testResult(JustA.class), isSuccessful());
+ }
+
+ @Test
+ public void testCount() {
+ assertThat(testResult(SlowTestSuite.class), isSuccessful());
+ }
+
+ public static class Category1 {}
+ public static class Category2 {}
+
+ public static class SomeAreSlow {
+ @Test public void noCategory() {}
+ @Category(Category1.class) @Test public void justCategory1() {}
+ @Category(Category2.class) @Test public void justCategory2() {}
+ @Category({Category1.class, Category2.class}) @Test public void both() {}
+ @Category({Category2.class, Category1.class}) @Test public void bothReversed() {}
+ }
+
+ @RunWith(Categories.class)
+ @ExcludeCategory(Category1.class)
+ @SuiteClasses( { SomeAreSlow.class })
+ public static class SomeAreSlowSuite {
+ }
+
+ @Test
+ public void testCountOnAWithoutSlowTests() {
+ Result result= JUnitCore.runClasses(SomeAreSlowSuite.class);
+ assertThat(testResult(SomeAreSlowSuite.class), isSuccessful());
+ assertEquals(2, result.getRunCount());
+ assertTrue(result.wasSuccessful());
+ }
+
+ @RunWith(Categories.class)
+ @ExcludeCategory(Category1.class)
+ @IncludeCategory(Category2.class)
+ @SuiteClasses( { SomeAreSlow.class })
+ public static class IncludeAndExcludeSuite {
+ }
+
+ @Test
+ public void testsThatAreBothIncludedAndExcludedAreExcluded() {
+ Result result= JUnitCore.runClasses(IncludeAndExcludeSuite.class);
+ assertThat(testResult(SomeAreSlowSuite.class), isSuccessful());
+ assertEquals(1, result.getRunCount());
+ assertTrue(result.wasSuccessful());
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses( { A.class, B.class, C.class })
+ public static class TestSuiteWithNoCategories {
+ }
+
+ @Test
+ public void testCountWithExplicitFilter() throws Throwable {
+ CategoryFilter include= CategoryFilter.include(SlowTests.class);
+ Request baseRequest= Request.aClass(TestSuiteWithNoCategories.class);
+ Result result= new JUnitCore().run(baseRequest.filterWith(include));
+ assertTrue(result.wasSuccessful());
+ assertEquals(2, result.getRunCount());
+ }
+
+ @Test
+ public void categoryFilterLeavesOnlyMatchingMethods()
+ throws InitializationError, NoTestsRemainException {
+ CategoryFilter filter= CategoryFilter.include(SlowTests.class);
+ BlockJUnit4ClassRunner runner= new BlockJUnit4ClassRunner(A.class);
+ filter.apply(runner);
+ assertEquals(1, runner.testCount());
+ }
+
+ public static class OneFastOneSlow {
+ @Category(FastTests.class)
+ @Test
+ public void a() {
+
+ }
+
+ @Category(SlowTests.class)
+ @Test
+ public void b() {
+
+ }
+ }
+
+ @Test
+ public void categoryFilterRejectsIncompatibleCategory()
+ throws InitializationError, NoTestsRemainException {
+ CategoryFilter filter= CategoryFilter.include(SlowTests.class);
+ BlockJUnit4ClassRunner runner= new BlockJUnit4ClassRunner(
+ OneFastOneSlow.class);
+ filter.apply(runner);
+ assertEquals(1, runner.testCount());
+ }
+
+ public static class OneFast {
+ @Category(FastTests.class)
+ @Test
+ public void a() {
+
+ }
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(SlowTests.class)
+ @SuiteClasses( { OneFast.class })
+ public static class OneFastSuite {
+ }
+
+ @Test
+ public void ifNoTestsToRunUseErrorRunner() {
+ Result result= JUnitCore.runClasses(OneFastSuite.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ }
+
+ @Test
+ public void describeACategoryFilter() {
+ CategoryFilter filter= CategoryFilter.include(SlowTests.class);
+ assertEquals("category " + SlowTests.class, filter.describe());
+ }
+
+ public static class OneThatIsBothFastAndSlow {
+ @Category({FastTests.class, SlowTests.class})
+ @Test
+ public void a() {
+
+ }
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(SlowTests.class)
+ @SuiteClasses( { OneThatIsBothFastAndSlow.class })
+ public static class ChooseSlowFromBoth {
+ }
+
+ @Test public void runMethodWithTwoCategories() {
+ assertThat(testResult(ChooseSlowFromBoth.class), isSuccessful());
+ }
+
+ public interface VerySlowTests extends SlowTests {
+
+ }
+
+ public static class OneVerySlowTest {
+ @Category(VerySlowTests.class)
+ @Test
+ public void a() {
+
+ }
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(SlowTests.class)
+ @SuiteClasses( { OneVerySlowTest.class })
+ public static class RunSlowFromVerySlow {
+ }
+
+ @Test public void subclassesOfIncludedCategoriesAreRun() {
+ assertThat(testResult(RunSlowFromVerySlow.class), isSuccessful());
+ }
+
+ public static class ClassAsCategory {
+
+ }
+
+ public static class OneMoreTest {
+ @Category(ClassAsCategory.class) @Test public void a() {}
+ }
+
+ @RunWith(Categories.class)
+ @IncludeCategory(ClassAsCategory.class)
+ @SuiteClasses( { OneMoreTest.class })
+ public static class RunClassAsCategory {
+ }
+
+ @Test public void classesCanBeCategories() {
+ assertThat(testResult(RunClassAsCategory.class), isSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java b/junit4/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java
new file mode 100644
index 0000000..c020320
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java
@@ -0,0 +1,24 @@
+package org.junit.tests.experimental.max;
+
+import static org.junit.Assert.assertNull;
+import org.junit.Test;
+import org.junit.runner.Description;
+
+public class DescriptionTest {
+
+ @Test
+ public void parseClass_whenCantParse() {
+ assertNull(Description.TEST_MECHANISM.getTestClass());
+ }
+
+ @Test
+ public void parseMethod_whenCantParse() {
+ assertNull(Description.TEST_MECHANISM.getMethodName());
+ }
+
+ @Test(expected= IllegalArgumentException.class)
+ public void createSuiteDescription_whenZeroLength() {
+ Description.createSuiteDescription("");
+ }
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java b/junit4/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java
new file mode 100644
index 0000000..68a25d6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java
@@ -0,0 +1,53 @@
+package org.junit.tests.experimental.max;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+import java.util.List;
+
+import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.max.MaxCore;
+import org.junit.runner.Description;
+import org.junit.runner.Request;
+
+public class JUnit38SortingTest {
+ private MaxCore fMax;
+ private File fMaxFile;
+
+ @Before
+ public void createMax() {
+ fMaxFile= new File("MaxCore.ser");
+ if (fMaxFile.exists())
+ fMaxFile.delete();
+ fMax= MaxCore.storedLocally(fMaxFile);
+ }
+
+ @After
+ public void forgetMax() {
+ fMaxFile.delete();
+ }
+
+ public static class JUnit4Test {
+ @Test public void pass() {}
+ }
+
+ public static class JUnit38Test extends TestCase {
+ public void testFails() { fail(); }
+ public void testSucceeds() {}
+ public void testSucceedsToo() {}
+ }
+
+ @Test
+ public void preferRecentlyFailed38Test() {
+ Request request= Request.classes(JUnit4Test.class, JUnit38Test.class);
+ fMax.run(request);
+ List<Description> tests= fMax.sortedLeavesForTest(request);
+ Description dontSucceed= Description.createTestDescription(
+ JUnit38Test.class, "testFails");
+ assertEquals(dontSucceed, tests.get(0));
+ }
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java b/junit4/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java
new file mode 100644
index 0000000..372af8f
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java
@@ -0,0 +1,293 @@
+package org.junit.tests.experimental.max;
+
+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;
+import java.util.List;
+
+import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.max.MaxCore;
+import org.junit.internal.runners.JUnit38ClassRunner;
+import org.junit.runner.Computer;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+import org.junit.tests.AllTests;
+
+public class MaxStarterTest {
+ private MaxCore fMax;
+
+ private File fMaxFile;
+
+ @Before
+ public void createMax() {
+ fMaxFile= new File("MaxCore.ser");
+ if (fMaxFile.exists())
+ fMaxFile.delete();
+ fMax= MaxCore.storedLocally(fMaxFile);
+ }
+
+ @After
+ public void forgetMax() {
+ fMaxFile.delete();
+ }
+
+ public static class TwoTests {
+ @Test
+ public void succeed() {
+ }
+
+ @Test
+ public void dontSucceed() {
+ fail();
+ }
+ }
+
+ @Test
+ public void twoTestsNotRunComeBackInRandomOrder() {
+ Request request= Request.aClass(TwoTests.class);
+ List<Description> things= fMax.sortedLeavesForTest(request);
+ Description succeed= Description.createTestDescription(TwoTests.class,
+ "succeed");
+ Description dontSucceed= Description.createTestDescription(
+ TwoTests.class, "dontSucceed");
+ assertTrue(things.contains(succeed));
+ assertTrue(things.contains(dontSucceed));
+ assertEquals(2, things.size());
+ }
+
+ @Test
+ public void preferNewTests() {
+ Request one= Request.method(TwoTests.class, "succeed");
+ fMax.run(one);
+ Request two= Request.aClass(TwoTests.class);
+ List<Description> things= fMax.sortedLeavesForTest(two);
+ Description dontSucceed= Description.createTestDescription(
+ TwoTests.class, "dontSucceed");
+ assertEquals(dontSucceed, things.get(0));
+ assertEquals(2, things.size());
+ }
+
+ // This covers a seemingly-unlikely case, where you had a test that failed
+ // on the
+ // last run and you also introduced new tests. In such a case it pretty much
+ // doesn't matter
+ // which order they run, you just want them both to be early in the sequence
+ @Test
+ public void preferNewTestsOverTestsThatFailed() {
+ Request one= Request.method(TwoTests.class, "dontSucceed");
+ fMax.run(one);
+ Request two= Request.aClass(TwoTests.class);
+ List<Description> things= fMax.sortedLeavesForTest(two);
+ Description succeed= Description.createTestDescription(TwoTests.class,
+ "succeed");
+ assertEquals(succeed, things.get(0));
+ assertEquals(2, things.size());
+ }
+
+ @Test
+ public void preferRecentlyFailed() {
+ Request request= Request.aClass(TwoTests.class);
+ fMax.run(request);
+ List<Description> tests= fMax.sortedLeavesForTest(request);
+ Description dontSucceed= Description.createTestDescription(
+ TwoTests.class, "dontSucceed");
+ assertEquals(dontSucceed, tests.get(0));
+ }
+
+ @Test
+ public void sortTestsInMultipleClasses() {
+ Request request= Request.classes(Computer.serial(), TwoTests.class,
+ TwoTests.class);
+ fMax.run(request);
+ List<Description> tests= fMax.sortedLeavesForTest(request);
+ Description dontSucceed= Description.createTestDescription(
+ TwoTests.class, "dontSucceed");
+ assertEquals(dontSucceed, tests.get(0));
+ assertEquals(dontSucceed, tests.get(1));
+ }
+
+ public static class TwoUnEqualTests {
+ @Test
+ public void slow() throws InterruptedException {
+ Thread.sleep(100);
+ fail();
+ }
+
+ @Test
+ public void fast() {
+ fail();
+ }
+
+ }
+
+ @Test
+ public void rememberOldRuns() {
+ fMax.run(TwoUnEqualTests.class);
+
+ MaxCore reincarnation= MaxCore.storedLocally(fMaxFile);
+ List<Failure> failures= reincarnation.run(TwoUnEqualTests.class)
+ .getFailures();
+ assertEquals("fast", failures.get(0).getDescription().getMethodName());
+ assertEquals("slow", failures.get(1).getDescription().getMethodName());
+ }
+
+ @Test
+ public void preferFast() {
+ Request request= Request.aClass(TwoUnEqualTests.class);
+ fMax.run(request);
+ Description thing= fMax.sortedLeavesForTest(request).get(1);
+ assertEquals(Description.createTestDescription(TwoUnEqualTests.class,
+ "slow"), thing);
+ }
+
+ @Test
+ public void listenersAreCalledCorrectlyInTheFaceOfFailures()
+ throws Exception {
+ JUnitCore core= new JUnitCore();
+ final List<Failure> failures= new ArrayList<Failure>();
+ core.addListener(new RunListener() {
+ @Override
+ public void testRunFinished(Result result) throws Exception {
+ failures.addAll(result.getFailures());
+ }
+ });
+ fMax.run(Request.aClass(TwoTests.class), core);
+ assertEquals(1, failures.size());
+ }
+
+ @Test
+ public void testsAreOnlyIncludedOnceWhenExpandingForSorting()
+ throws Exception {
+ Result result= fMax.run(Request.aClass(TwoTests.class));
+ assertEquals(2, result.getRunCount());
+ }
+
+ public static class TwoOldTests extends TestCase {
+ public void testOne() {
+ }
+
+ public void testTwo() {
+ }
+ }
+
+ @Test
+ public void junit3TestsAreRunOnce() throws Exception {
+ Result result= fMax.run(Request.aClass(TwoOldTests.class),
+ new JUnitCore());
+ assertEquals(2, result.getRunCount());
+ }
+
+ @Test
+ public void filterSingleMethodFromOldTestClass() throws Exception {
+ final Description method= Description.createTestDescription(
+ TwoOldTests.class, "testOne");
+ Filter filter= Filter.matchMethodDescription(method);
+ JUnit38ClassRunner child= new JUnit38ClassRunner(TwoOldTests.class);
+ child.filter(filter);
+ assertEquals(1, child.testCount());
+ }
+
+ @Test
+ public void testCountsStandUpToFiltration() {
+ assertFilterLeavesTestUnscathed(AllTests.class);
+ }
+
+ private void assertFilterLeavesTestUnscathed(Class<?> testClass) {
+ Request oneClass= Request.aClass(testClass);
+ Request filtered= oneClass.filterWith(new Filter() {
+ @Override
+ public boolean shouldRun(Description description) {
+ return true;
+ }
+
+ @Override
+ public String describe() {
+ return "Everything";
+ }
+ });
+
+ int filterCount= filtered.getRunner().testCount();
+ int coreCount= oneClass.getRunner().testCount();
+ assertEquals("Counts match up in " + testClass, coreCount, filterCount);
+ }
+
+ private static class MalformedJUnit38Test {
+ private MalformedJUnit38Test() {
+ }
+
+ @SuppressWarnings("unused")
+ public void testSucceeds() {
+ }
+ }
+
+ @Test
+ public void maxShouldSkipMalformedJUnit38Classes() {
+ Request request= Request.aClass(MalformedJUnit38Test.class);
+ fMax.run(request);
+ }
+
+ public static class MalformedJUnit38TestMethod extends TestCase {
+ @SuppressWarnings("unused")
+ private void testNothing() {
+ }
+ }
+
+ String fMessage= null;
+
+ @Test
+ public void correctErrorFromMalformedTest() {
+ Request request= Request.aClass(MalformedJUnit38TestMethod.class);
+ JUnitCore core= new JUnitCore();
+ Request sorted= fMax.sortRequest(request);
+ Runner runner= sorted.getRunner();
+ Result result= core.run(runner);
+ Failure failure= result.getFailures().get(0);
+ assertThat(failure.toString(), containsString("MalformedJUnit38TestMethod"));
+ assertThat(failure.toString(), containsString("testNothing"));
+ assertThat(failure.toString(), containsString("isn't public"));
+ }
+
+ public static class HalfMalformedJUnit38TestMethod extends TestCase {
+ public void testSomething() {
+ }
+
+ @SuppressWarnings("unused")
+ private void testNothing() {
+ }
+ }
+
+ @Test
+ public void halfMalformed() {
+ assertThat(JUnitCore.runClasses(HalfMalformedJUnit38TestMethod.class)
+ .getFailureCount(), is(1));
+ }
+
+
+ @Test
+ public void correctErrorFromHalfMalformedTest() {
+ Request request= Request.aClass(HalfMalformedJUnit38TestMethod.class);
+ JUnitCore core= new JUnitCore();
+ Request sorted= fMax.sortRequest(request);
+ Runner runner= sorted.getRunner();
+ Result result= core.run(runner);
+ Failure failure= result.getFailures().get(0);
+ assertThat(failure.toString(), containsString("MalformedJUnit38TestMethod"));
+ assertThat(failure.toString(), containsString("testNothing"));
+ assertThat(failure.toString(), containsString("isn't public"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java b/junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java
new file mode 100644
index 0000000..3f9b2f1
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java
@@ -0,0 +1,54 @@
+package org.junit.tests.experimental.parallel;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+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;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+
+public class ParallelClassTest {
+
+ public static class Example1 {
+ @Test public void one() throws InterruptedException {
+ Thread.sleep(1000);
+ }
+ }
+ public static class Example2 {
+ @Test public void one() throws InterruptedException {
+ Thread.sleep(1000);
+ }
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses({Example1.class, Example2.class})
+ public static class ExampleSuite {}
+
+ @Test(timeout=1500) public void testsRunInParallel() {
+ long start= System.currentTimeMillis();
+ Result result= JUnitCore.runClasses(ParallelComputer.classes(), Example1.class, Example2.class);
+ assertTrue(result.wasSuccessful());
+ long end= System.currentTimeMillis();
+ assertThat(end - start, greaterThan(999)); // Overhead could be less than half a millisecond
+ }
+
+ private Matcher<Long> greaterThan(final long l) {
+ return new TypeSafeMatcher<Long>() {
+ @Override
+ public boolean matchesSafely(Long item) {
+ return item > l;
+ }
+
+ public void describeTo(Description description) {
+ description.appendText("greater than " + l);
+ }
+ };
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java b/junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java
new file mode 100644
index 0000000..be5a792
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java
@@ -0,0 +1,44 @@
+package org.junit.tests.experimental.parallel;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+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;
+
+public class ParallelMethodTest {
+ public static class Example {
+ @Test public void one() throws InterruptedException {
+ Thread.sleep(1000);
+ }
+ @Test public void two() throws InterruptedException {
+ Thread.sleep(1000);
+ }
+ }
+
+ @Test public void testsRunInParallel() {
+ long start= System.currentTimeMillis();
+ Result result= JUnitCore.runClasses(ParallelComputer.methods(),
+ Example.class);
+ assertTrue(result.wasSuccessful());
+ long end= System.currentTimeMillis();
+ assertThat(end - start, betweenInclusive(1000, 1900));
+ }
+
+ private Matcher<Long> betweenInclusive(final long min, final long max) {
+ return new TypeSafeMatcher<Long>() {
+ @Override
+ public boolean matchesSafely(Long item) {
+ return item >= min && item <= max;
+ }
+
+ public void describeTo(Description description) {
+ description.appendText("between " + min + " and " + max);
+ }
+ };
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java b/junit4/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java
new file mode 100644
index 0000000..de715cb
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java
@@ -0,0 +1,51 @@
+package org.junit.tests.experimental.results;
+
+import static java.util.Arrays.asList;
+import static org.hamcrest.CoreMatchers.allOf;
+import static org.junit.Assert.assertThat;
+import static org.junit.internal.matchers.StringContains.containsString;
+
+import java.util.Arrays;
+
+import org.junit.experimental.results.PrintableResult;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.Description;
+import org.junit.runner.RunWith;
+import org.junit.runner.notification.Failure;
+
+@RunWith(Theories.class)
+public class PrintableResultTest {
+ @SuppressWarnings("unchecked")
+ @Theory(nullsAccepted= false)
+ public void backTraceHasGoodToString(String descriptionName,
+ final String stackTraceClassName) {
+ Failure failure= new Failure(Description
+ .createSuiteDescription(descriptionName), new Throwable() {
+ private static final long serialVersionUID= 1L;
+
+ @Override
+ public StackTraceElement[] getStackTrace() {
+ return new StackTraceElement[] { new StackTraceElement(
+ stackTraceClassName, "methodName", "fileName", 1) };
+ }
+ });
+
+ assertThat(new PrintableResult(asList(failure)).toString(), allOf(
+ containsString(descriptionName), containsString(stackTraceClassName)));
+ }
+
+ @DataPoint
+ public static String SHELL_POINT= "Shell Point";
+
+ @Theory
+ public void includeMultipleFailures(String secondExceptionName) {
+ PrintableResult backtrace= new PrintableResult(Arrays.asList(
+ new Failure(Description.createSuiteDescription("firstName"),
+ new RuntimeException("firstException")), new Failure(
+ Description.createSuiteDescription("secondName"),
+ new RuntimeException(secondExceptionName))));
+ assertThat(backtrace.toString(), containsString(secondExceptionName));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java b/junit4/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java
new file mode 100644
index 0000000..1263a8c
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java
@@ -0,0 +1,21 @@
+package org.junit.tests.experimental.results;
+
+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;
+public class ResultMatchersTest {
+ @Test
+ public void hasFailuresHasGoodDescription() {
+ assertThat(ResultMatchers.failureCountIs(3).toString(),
+ is("has 3 failures"));
+ }
+
+ @Theory
+ public void hasFailuresDescriptionReflectsInput(int i) {
+ assertThat(ResultMatchers.failureCountIs(i).toString(),
+ containsString("" + i));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/BlockJUnit4ClassRunnerOverrideTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/BlockJUnit4ClassRunnerOverrideTest.java
new file mode 100644
index 0000000..1fa3714
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/BlockJUnit4ClassRunnerOverrideTest.java
@@ -0,0 +1,93 @@
+package org.junit.tests.experimental.rules;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.rules.MethodRule;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runner.RunWith;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.InitializationError;
+import org.junit.runners.model.Statement;
+
+@SuppressWarnings("deprecation")
+public class BlockJUnit4ClassRunnerOverrideTest {
+ public static class FlipBitRule implements MethodRule {
+ public Statement apply(final Statement base, FrameworkMethod method,
+ final Object target) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ target.getClass().getField("flipBit").set(target, true);
+ base.evaluate();
+ }
+ };
+ }
+
+ }
+
+ public static class OverrideRulesRunner extends BlockJUnit4ClassRunner {
+ public OverrideRulesRunner(Class<?> klass) throws InitializationError {
+ super(klass);
+ }
+
+ @Override
+ protected List<MethodRule> rules(Object test) {
+ final LinkedList<MethodRule> methodRules= new LinkedList<MethodRule>(
+ super.rules(test));
+ methodRules.add(new FlipBitRule());
+ return methodRules;
+ }
+ }
+
+ @RunWith(OverrideRulesRunner.class)
+ public static class OverrideRulesTest {
+ public boolean flipBit= false;
+
+ @Test
+ public void testFlipBit() {
+ assertTrue(flipBit);
+ }
+ }
+
+ @Test
+ public void overrideRulesMethod() {
+ assertThat(testResult(OverrideTestRulesTest.class), isSuccessful());
+ }
+
+ public static class OverrideTestRulesRunner extends BlockJUnit4ClassRunner {
+ public OverrideTestRulesRunner(Class<?> klass)
+ throws InitializationError {
+ super(klass);
+ }
+
+ @Override
+ protected List<TestRule> getTestRules(final Object test) {
+ final LinkedList<TestRule> methodRules= new LinkedList<TestRule>(
+ super.getTestRules(test));
+ methodRules.add(new TestRule() {
+ public Statement apply(Statement base, Description description) {
+ return new FlipBitRule().apply(base, null, test);
+ }
+ });
+ return methodRules;
+ }
+ }
+
+ @RunWith(OverrideTestRulesRunner.class)
+ public static class OverrideTestRulesTest extends OverrideRulesTest {
+ }
+
+ @Test
+ public void overrideTestRulesMethod() {
+ assertThat(testResult(OverrideRulesTest.class), isSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/ClassRulesTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/ClassRulesTest.java
new file mode 100644
index 0000000..70b2d84
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/ClassRulesTest.java
@@ -0,0 +1,101 @@
+/**
+ * Created Oct 19, 2009
+ */
+package org.junit.tests.experimental.rules;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.rules.ExternalResource;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runners.model.Statement;
+
+/**
+ * Tests to exercise class-level rules.
+ */
+public class ClassRulesTest {
+ public static class Counter extends ExternalResource {
+ public int count = 0;
+
+ @Override
+ protected void before() throws Throwable {
+ count++;
+ }
+ }
+
+ public static class ExampleTestWithClassRule {
+ @ClassRule
+ public static Counter counter= new Counter();
+
+ @Test
+ public void firstTest() {
+ assertEquals(1, counter.count);
+ }
+
+ @Test
+ public void secondTest() {
+ assertEquals(1, counter.count);
+ }
+ }
+
+ @Test
+ public void ruleIsAppliedOnce() {
+ ExampleTestWithClassRule.counter.count= 0;
+ JUnitCore.runClasses(ExampleTestWithClassRule.class);
+ assertEquals(1, ExampleTestWithClassRule.counter.count);
+ }
+
+ public static class SubclassOfTestWithClassRule extends
+ ExampleTestWithClassRule {
+
+ }
+
+ @Test
+ public void ruleIsIntroducedAndEvaluatedOnSubclass() {
+ ExampleTestWithClassRule.counter.count= 0;
+ JUnitCore.runClasses(SubclassOfTestWithClassRule.class);
+ assertEquals(1, ExampleTestWithClassRule.counter.count);
+ }
+
+ public static class CustomCounter implements TestRule {
+ public int count = 0;
+
+ public Statement apply(final Statement base, Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ count++;
+ base.evaluate();
+ }
+ };
+ }
+ }
+
+ public static class ExampleTestWithCustomClassRule {
+ @ClassRule
+ public static CustomCounter counter= new CustomCounter();
+
+ @Test
+ public void firstTest() {
+ assertEquals(1, counter.count);
+ }
+
+ @Test
+ public void secondTest() {
+ assertEquals(1, counter.count);
+ }
+ }
+
+
+ @Test
+ public void customRuleIsAppliedOnce() {
+ ExampleTestWithCustomClassRule.counter.count= 0;
+ Result result= JUnitCore.runClasses(ExampleTestWithCustomClassRule.class);
+ assertTrue(result.wasSuccessful());
+ assertEquals(1, ExampleTestWithCustomClassRule.counter.count);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionRuleTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionRuleTest.java
new file mode 100644
index 0000000..b5119cd
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionRuleTest.java
@@ -0,0 +1,232 @@
+package org.junit.tests.experimental.rules;
+
+import static org.hamcrest.CoreMatchers.any;
+import static org.junit.Assert.assertThat;
+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.both;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.internal.matchers.TypeSafeMatcher;
+import org.junit.rules.ExpectedException;
+
+public class ExpectedExceptionRuleTest {
+ public static class HasExpectedException {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsNothing() {
+
+ }
+
+ @Test
+ public void throwsNullPointerException() {
+ thrown.expect(NullPointerException.class);
+ throw new NullPointerException();
+ }
+
+ @Test
+ public void throwsNullPointerExceptionWithMessage() {
+ thrown.expect(NullPointerException.class);
+ thrown.expectMessage("happened?");
+ throw new NullPointerException("What happened?");
+ }
+ }
+
+ @Test
+ public void expectedExceptionPasses() {
+ assertThat(testResult(HasExpectedException.class), isSuccessful());
+ }
+
+ public static class HasWrongExpectedException {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsNullPointerException() {
+ thrown.expect(NullPointerException.class);
+ throw new IllegalArgumentException();
+ }
+ }
+
+ @Test
+ public void unExpectedExceptionFails() {
+ assertThat(
+ testResult(HasWrongExpectedException.class),
+ hasSingleFailureContaining("Expected: an instance of java.lang.NullPointerException"));
+ }
+
+ public static class HasWrongMessage {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsNullPointerException() {
+ thrown.expectMessage("expectedMessage");
+ throw new IllegalArgumentException("actualMessage");
+ }
+ }
+
+ @Test
+ public void wrongMessageFails() {
+ assertThat(
+ testResult(HasWrongMessage.class), both(
+ hasSingleFailureContaining("expectedMessage")).and(
+ hasSingleFailureContaining("actualMessage")));
+ }
+
+ public static class WronglyExpectsException {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void doesntThrowNullPointerException() {
+ thrown.expect(NullPointerException.class);
+ }
+ }
+
+ @Test
+ public void failsIfExceptionNeverComes() {
+ assertThat(
+ testResult(WronglyExpectsException.class),
+ hasSingleFailureContaining("Expected test to throw an instance of java.lang.NullPointerException"));
+ }
+
+ public static class WronglyExpectsExceptionMessage {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void doesntThrowAnything() {
+ thrown.expectMessage("anything!");
+ }
+ }
+
+ @Test
+ public void failsIfExceptionMessageNeverComes() {
+ assertThat(
+ testResult(WronglyExpectsExceptionMessage.class),
+ hasSingleFailureContaining("Expected test to throw exception with message a string containing \"anything!\""));
+ }
+
+ public static class ExpectsSubstring {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsMore() {
+ thrown.expectMessage("anything!");
+ throw new NullPointerException(
+ "This could throw anything! (as long as it has the right substring)");
+ }
+ }
+
+ @Test
+ public void passesWithSubstringMethod() {
+ assertThat(testResult(ExpectsSubstring.class), isSuccessful());
+ }
+
+ public static class ExpectsSubstringNullMessage {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsMore() {
+ thrown.expectMessage("anything!");
+ throw new NullPointerException();
+ }
+ }
+
+ @Test
+ public void failsWithNullExceptionMessage() {
+ assertThat(testResult(ExpectsSubstringNullMessage.class),
+ hasSingleFailureContaining("NullPointerException"));
+ }
+
+ public static class ExpectsMessageMatcher {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsMore() {
+ thrown.expectMessage(startsWith("Ack"));
+ throw new NullPointerException("Ack!");
+ }
+ }
+
+ @Test
+ public void succeedsWithMessageMatcher() {
+ assertThat(testResult(ExpectsMessageMatcher.class), isSuccessful());
+ }
+
+ public static class ExpectedMessageMatcherFails {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsMore() {
+ thrown.expectMessage(startsWith("Wrong start"));
+ throw new NullPointerException("Back!");
+ }
+ }
+
+
+
+ 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);
+ }
+ };
+ }
+
+ @Test
+ public void failsWithMatcher() {
+ assertThat(testResult(ExpectedMessageMatcherFails.class),
+ hasSingleFailureContaining("Wrong start"));
+ }
+
+ public static class ExpectsMatcher {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsMore() {
+ thrown.expect(any(Throwable.class));
+ throw new NullPointerException("Ack!");
+ }
+ }
+
+ @Test
+ public void succeedsWithMatcher() {
+ assertThat(testResult(ExpectsMatcher.class), isSuccessful());
+ }
+
+ public static class ExpectsMultipleMatchers {
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
+ @Test
+ public void throwsMore() {
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("Ack!");
+ throw new NullPointerException("Ack!");
+ }
+ }
+
+ @Test
+ public void failsWithMultipleMatchers() {
+ assertThat(testResult(ExpectsMultipleMatchers.class),
+ hasSingleFailureContaining("IllegalArgumentException"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/ExternalResourceRuleTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/ExternalResourceRuleTest.java
new file mode 100644
index 0000000..48cbeb9
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/ExternalResourceRuleTest.java
@@ -0,0 +1,37 @@
+package org.junit.tests.experimental.rules;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExternalResource;
+
+public class ExternalResourceRuleTest {
+ private static String callSequence;
+
+ public static class UsesExternalResource {
+ @Rule public ExternalResource resource = new ExternalResource() {
+ @Override
+ protected void before() throws Throwable {
+ callSequence += "before ";
+ };
+
+ @Override
+ protected void after() {
+ callSequence += "after ";
+ };
+ };
+
+ @Test public void testFoo() {
+ callSequence += "test ";
+ }
+ }
+
+ @Test public void externalResourceGeneratesCorrectSequence() {
+ callSequence= "";
+ assertThat(testResult(UsesExternalResource.class), isSuccessful());
+ assertEquals("before test after ", callSequence);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/LoggingTestWatcher.java b/junit4/src/test/java/org/junit/tests/experimental/rules/LoggingTestWatcher.java
new file mode 100644
index 0000000..98251b9
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/LoggingTestWatcher.java
@@ -0,0 +1,32 @@
+package org.junit.tests.experimental.rules;
+
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+class LoggingTestWatcher extends TestWatcher {
+ private final StringBuilder log;
+
+ LoggingTestWatcher(StringBuilder log) {
+ this.log= log;
+ }
+
+ @Override
+ protected void succeeded(Description description) {
+ log.append("succeeded ");
+ }
+
+ @Override
+ protected void failed(Throwable e, Description description) {
+ log.append("failed ");
+ }
+
+ @Override
+ protected void starting(Description description) {
+ log.append("starting ");
+ }
+
+ @Override
+ protected void finished(Description description) {
+ log.append("finished ");
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java
new file mode 100644
index 0000000..116953e
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java
@@ -0,0 +1,275 @@
+package org.junit.tests.experimental.rules;
+
+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.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;
+import org.junit.rules.MethodRule;
+import org.junit.rules.TestName;
+import org.junit.rules.TestWatchman;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+
+@SuppressWarnings("deprecation")
+public class MethodRulesTest {
+ private static boolean wasRun;
+
+ public static class ExampleTest {
+ @Rule
+ public MethodRule example= new MethodRule() {
+ public Statement apply(final Statement base,
+ FrameworkMethod method, Object target) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ wasRun= true;
+ base.evaluate();
+ };
+ };
+ }
+ };
+
+ @Test
+ public void nothing() {
+
+ }
+ }
+
+ @Test
+ public void ruleIsIntroducedAndEvaluated() {
+ wasRun= false;
+ JUnitCore.runClasses(ExampleTest.class);
+ assertTrue(wasRun);
+ }
+
+ public static class SonOfExampleTest extends ExampleTest {
+
+ }
+
+ @Test
+ public void ruleIsIntroducedAndEvaluatedOnSubclass() {
+ wasRun= false;
+ JUnitCore.runClasses(SonOfExampleTest.class);
+ assertTrue(wasRun);
+ }
+
+ private static int runCount;
+
+ public static class MultipleRuleTest {
+ private static class Increment implements MethodRule {
+ public Statement apply(final Statement base,
+ FrameworkMethod method, Object target) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ runCount++;
+ base.evaluate();
+ };
+ };
+ }
+ }
+
+ @Rule
+ public MethodRule incrementor1= new Increment();
+
+ @Rule
+ public MethodRule incrementor2= new Increment();
+
+ @Test
+ public void nothing() {
+
+ }
+ }
+
+ @Test
+ public void multipleRulesAreRun() {
+ runCount= 0;
+ JUnitCore.runClasses(MultipleRuleTest.class);
+ assertEquals(2, runCount);
+ }
+
+ public static class NoRulesTest {
+ public int x;
+
+ @Test
+ public void nothing() {
+
+ }
+ }
+
+ @Test
+ public void ignoreNonRules() {
+ Result result= JUnitCore.runClasses(NoRulesTest.class);
+ assertEquals(0, result.getFailureCount());
+ }
+
+ private static String log;
+
+ public static class OnFailureTest {
+ @Rule
+ public MethodRule watchman= new TestWatchman() {
+ @Override
+ public void failed(Throwable e, FrameworkMethod method) {
+ log+= method.getName() + " " + e.getClass().getSimpleName();
+ }
+ };
+
+ @Test
+ public void nothing() {
+ fail();
+ }
+ }
+
+ @Test
+ public void onFailure() {
+ log= "";
+ Result result= JUnitCore.runClasses(OnFailureTest.class);
+ assertEquals("nothing AssertionError", log);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ public static class WatchmanTest {
+ private static String watchedLog;
+
+ @Rule
+ public MethodRule watchman= new TestWatchman() {
+ @Override
+ public void failed(Throwable e, FrameworkMethod method) {
+ watchedLog+= method.getName() + " "
+ + e.getClass().getSimpleName() + "\n";
+ }
+
+ @Override
+ public void succeeded(FrameworkMethod method) {
+ watchedLog+= method.getName() + " " + "success!\n";
+ }
+ };
+
+ @Test
+ public void fails() {
+ fail();
+ }
+
+ @Test
+ public void succeeds() {
+ }
+ }
+
+ @Test
+ public void succeeded() {
+ WatchmanTest.watchedLog= "";
+ JUnitCore.runClasses(WatchmanTest.class);
+ assertThat(WatchmanTest.watchedLog, containsString("fails AssertionError"));
+ assertThat(WatchmanTest.watchedLog, containsString("succeeds success!"));
+ }
+
+ public static class BeforesAndAfters {
+ private static String watchedLog;
+
+ @Before public void before() {
+ watchedLog+= "before ";
+ }
+
+ @Rule
+ public MethodRule watchman= new TestWatchman() {
+ @Override
+ public void starting(FrameworkMethod method) {
+ watchedLog+= "starting ";
+ }
+
+ @Override
+ public void finished(FrameworkMethod method) {
+ watchedLog+= "finished ";
+ }
+
+ @Override
+ public void succeeded(FrameworkMethod method) {
+ watchedLog+= "succeeded ";
+ }
+ };
+
+ @After public void after() {
+ watchedLog+= "after ";
+ }
+
+ @Test
+ public void succeeds() {
+ watchedLog+= "test ";
+ }
+ }
+
+ @Test
+ public void beforesAndAfters() {
+ BeforesAndAfters.watchedLog= "";
+ JUnitCore.runClasses(BeforesAndAfters.class);
+ assertThat(BeforesAndAfters.watchedLog, is("starting before test after succeeded finished "));
+ }
+
+ public static class WrongTypedField {
+ @Rule public int x = 5;
+ @Test public void foo() {}
+ }
+
+ @Test public void validateWrongTypedField() {
+ assertThat(testResult(WrongTypedField.class),
+ hasSingleFailureContaining("must implement MethodRule"));
+ }
+
+ public static class SonOfWrongTypedField extends WrongTypedField {
+
+ }
+
+ @Test public void validateWrongTypedFieldInSuperclass() {
+ assertThat(testResult(SonOfWrongTypedField.class),
+ hasSingleFailureContaining("must implement MethodRule"));
+ }
+
+ public static class PrivateRule {
+ @SuppressWarnings("unused")
+ @Rule private TestRule rule = new TestName();
+ @Test public void foo() {}
+ }
+
+ @Test public void validatePrivateRule() {
+ assertThat(testResult(PrivateRule.class),
+ hasSingleFailureContaining("must be public"));
+ }
+
+ public static class CustomTestName implements TestRule {
+ public String name = null;
+
+ public Statement apply(final Statement base, final Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ name = description.getMethodName();
+ base.evaluate();
+ }
+ };
+ }
+ }
+
+ public static class UsesCustomMethodRule {
+ @Rule public CustomTestName counter = new CustomTestName();
+ @Test public void foo() {
+ assertEquals("foo", counter.name);
+ }
+ }
+
+ @Test public void useCustomMethodRule() {
+ assertThat(testResult(UsesCustomMethodRule.class), isSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/NameRulesTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/NameRulesTest.java
new file mode 100644
index 0000000..4f15bde
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/NameRulesTest.java
@@ -0,0 +1,50 @@
+package org.junit.tests.experimental.rules;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.runners.Enclosed;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+@RunWith(Enclosed.class)
+public class NameRulesTest {
+ public static class TestNames {
+ @Rule
+ public TestName name= new TestName();
+
+ @Test
+ public void testA() {
+ assertEquals("testA", name.getMethodName());
+ }
+
+ @Test
+ public void testB() {
+ assertEquals("testB", name.getMethodName());
+ }
+ }
+
+ public static class BeforeAndAfterTest {
+ @Rule
+ public TestName name= new TestName();
+
+ private final String expectedName= "x";
+
+ @Before
+ public void setUp() {
+ assertEquals(expectedName, name.getMethodName());
+ }
+
+ @Test
+ public void x() {
+ assertEquals(expectedName, name.getMethodName());
+ }
+
+ @After
+ public void tearDown() {
+ assertEquals(expectedName, name.getMethodName());
+ }
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java
new file mode 100644
index 0000000..e1ea4c5
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java
@@ -0,0 +1,60 @@
+package org.junit.tests.experimental.rules;
+
+import static java.util.Arrays.asList;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.rules.RuleChain.outerRule;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+
+public class RuleChainTest {
+ private static final List<String> LOG= new ArrayList<String>();
+
+ private static class LoggingRule extends TestWatcher {
+ private final String label;
+
+ public LoggingRule(String label) {
+ this.label= label;
+ }
+
+ @Override
+ protected void starting(Description description) {
+ LOG.add("starting " + label);
+ }
+
+ @Override
+ protected void finished(Description description) {
+ LOG.add("finished " + label);
+ }
+ }
+
+ public static class UseRuleChain {
+ @Rule
+ public final RuleChain chain= outerRule(new LoggingRule("outer rule"))
+ .around(new LoggingRule("middle rule")).around(
+ new LoggingRule("inner rule"));
+
+ @Test
+ public void example() {
+ assertTrue(true);
+ }
+ }
+
+ @Test
+ public void executeRulesInCorrectOrder() throws Exception {
+ testResult(UseRuleChain.class);
+ List<String> expectedLog= asList("starting outer rule",
+ "starting middle rule", "starting inner rule",
+ "finished inner rule", "finished middle rule",
+ "finished outer rule");
+ assertEquals(expectedLog, LOG);
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/RuleFieldValidatorTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/RuleFieldValidatorTest.java
new file mode 100644
index 0000000..fa6dcbf
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/RuleFieldValidatorTest.java
@@ -0,0 +1,96 @@
+package org.junit.tests.experimental.rules;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_VALIDATOR;
+import static org.junit.internal.runners.rules.RuleFieldValidator.RULE_VALIDATOR;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.MethodRule;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestRule;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+import org.junit.runners.model.TestClass;
+
+@SuppressWarnings("deprecation")
+public class RuleFieldValidatorTest {
+ private final List<Throwable> errors = new ArrayList<Throwable>();
+
+ @Test
+ public void rejectProtectedClassRule() {
+ TestClass target= new TestClass(TestWithProtectedClassRule.class);
+ CLASS_RULE_VALIDATOR.validate(target, errors);
+ assertOneErrorWithMessage("The @ClassRule 'temporaryFolder' must be public.");
+ }
+
+ public static class TestWithProtectedClassRule {
+ @ClassRule
+ protected static TestRule temporaryFolder = new TemporaryFolder();
+ }
+
+ @Test
+ public void rejectNonStaticClassRule() {
+ TestClass target= new TestClass(TestWithNonStaticClassRule.class);
+ CLASS_RULE_VALIDATOR.validate(target, errors);
+ assertOneErrorWithMessage("The @ClassRule 'temporaryFolder' must be static.");
+ }
+
+ public static class TestWithNonStaticClassRule {
+ @ClassRule
+ public TestRule temporaryFolder = new TemporaryFolder();
+ }
+
+ @Test
+ public void acceptNonStaticTestRule() {
+ TestClass target= new TestClass(TestWithNonStaticTestRule.class);
+ RULE_VALIDATOR.validate(target, errors);
+ assertNumberOfErrors(0);
+ }
+
+ public static class TestWithNonStaticTestRule {
+ @Rule
+ public TestRule temporaryFolder = new TemporaryFolder();
+ }
+
+ @Test
+ public void acceptMethodRule() throws Exception {
+ TestClass target= new TestClass(TestWithMethodRule.class);
+ RULE_VALIDATOR.validate(target, errors);
+ assertNumberOfErrors(0);
+ }
+
+ public static class TestWithMethodRule {
+ @Rule
+ public MethodRule temporaryFolder = new MethodRule(){
+ public Statement apply(Statement base, FrameworkMethod method,
+ Object target) {
+ return null;
+ }};
+ }
+
+ @Test
+ public void rejectArbitraryObjectWithRuleAnnotation() throws Exception {
+ TestClass target= new TestClass(TestWithArbitraryObjectWithRuleAnnotation.class);
+ RULE_VALIDATOR.validate(target, errors);
+ assertOneErrorWithMessage("The @Rule 'arbitraryObject' must implement MethodRule or TestRule.");
+ }
+
+ public static class TestWithArbitraryObjectWithRuleAnnotation {
+ @Rule
+ public Object arbitraryObject = 1;
+ }
+
+ private void assertOneErrorWithMessage(String message) {
+ assertNumberOfErrors(1);
+ assertEquals("Wrong error message:", message, errors.get(0).getMessage());
+ }
+
+ private void assertNumberOfErrors(int numberOfErrors) {
+ assertEquals("Wrong number of errors:", numberOfErrors, errors.size());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java
new file mode 100644
index 0000000..200d51e
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java
@@ -0,0 +1,200 @@
+package org.junit.tests.experimental.rules;
+
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.failureCountIs;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import static org.junit.internal.matchers.IsCollectionContaining.hasItem;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.junit.After;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+public class TempFolderRuleTest {
+ private static File[] createdFiles= new File[20];
+
+ public static class HasTempFolder {
+ @Rule
+ public TemporaryFolder folder= new TemporaryFolder();
+
+ @Test
+ public void testUsingTempFolder() throws IOException {
+ createdFiles[0]= folder.newFile("myfile.txt");
+ assertTrue(createdFiles[0].exists());
+ }
+ }
+
+ @Test
+ public void tempFolderIsDeleted() {
+ assertThat(testResult(HasTempFolder.class), isSuccessful());
+ assertFalse(createdFiles[0].exists());
+ }
+
+ public static class CreatesSubFolder {
+ @Rule
+ public TemporaryFolder folder= new TemporaryFolder();
+
+ @Test
+ public void testUsingTempFolder() throws IOException {
+ String subfolder = "subfolder";
+ String filename = "a.txt";
+ createdFiles[0]= folder.newFolder(subfolder);
+ new File(createdFiles[0], filename).createNewFile();
+
+ File expectedFile = new File(folder.getRoot(), join(subfolder, filename));
+
+ assertTrue(expectedFile.exists());
+ }
+
+ @Test
+ public void testUsingTempTreeFolders() throws IOException {
+ String subfolder = "subfolder";
+ String anotherfolder = "anotherfolder";
+ String filename = "a.txt";
+
+ createdFiles[0] = folder.newFolder(subfolder, anotherfolder);
+ new File(createdFiles[0], filename).createNewFile();
+
+ File expectedFile = new File(folder.getRoot(), join(subfolder, anotherfolder, filename));
+
+ assertTrue(expectedFile.exists());
+ }
+
+ private String join(String... folderNames) {
+ StringBuilder path = new StringBuilder();
+ for (String folderName : folderNames) {
+ path.append(File.separator).append(folderName);
+ }
+ return path.toString();
+ }
+ }
+
+ @Test
+ public void subFolderIsDeleted() {
+ assertThat(testResult(CreatesSubFolder.class), isSuccessful());
+ assertFalse(createdFiles[0].exists());
+ }
+
+ public static class CreatesRandomSubFolders {
+ @Rule
+ public TemporaryFolder folder= new TemporaryFolder();
+
+ @Test
+ public void testUsingRandomTempFolders() throws IOException {
+ for (int i= 0; i < 20; i++) {
+ File newFolder= folder.newFolder();
+ assertThat(Arrays.asList(createdFiles), not(hasItem(newFolder)));
+ createdFiles[i]= newFolder;
+ new File(newFolder, "a.txt").createNewFile();
+ assertTrue(newFolder.exists());
+ }
+ }
+ }
+
+ @Test
+ public void randomSubFoldersAreDeleted() {
+ assertThat(testResult(CreatesRandomSubFolders.class), isSuccessful());
+ for (File f : createdFiles) {
+ assertFalse(f.exists());
+ }
+ }
+
+ public static class CreatesRandomFiles {
+ @Rule
+ public TemporaryFolder folder= new TemporaryFolder();
+
+ @Test
+ public void testUsingRandomTempFiles() throws IOException {
+ for (int i= 0; i < 20; i++) {
+ File newFile= folder.newFile();
+ assertThat(Arrays.asList(createdFiles), not(hasItem(newFile)));
+ createdFiles[i]= newFile;
+ assertTrue(newFile.exists());
+ }
+ }
+ }
+
+ @Test
+ public void randomFilesAreDeleted() {
+ assertThat(testResult(CreatesRandomFiles.class), isSuccessful());
+ for (File f : createdFiles) {
+ assertFalse(f.exists());
+ }
+ }
+
+ @Test
+ public void recursiveDeleteFolderWithOneElement() throws IOException {
+ TemporaryFolder folder= new TemporaryFolder();
+ folder.create();
+ File file= folder.newFile("a");
+ folder.delete();
+ assertFalse(file.exists());
+ assertFalse(folder.getRoot().exists());
+ }
+
+ @Test
+ public void recursiveDeleteFolderWithOneRandomElement() throws IOException {
+ TemporaryFolder folder= new TemporaryFolder();
+ folder.create();
+ File file= folder.newFile();
+ folder.delete();
+ assertFalse(file.exists());
+ assertFalse(folder.getRoot().exists());
+ }
+
+ @Test
+ public void recursiveDeleteFolderWithZeroElements() throws IOException {
+ TemporaryFolder folder= new TemporaryFolder();
+ folder.create();
+ folder.delete();
+ assertFalse(folder.getRoot().exists());
+ }
+
+ private static final String GET_ROOT_DUMMY= "dummy-getRoot";
+
+ private static final String NEW_FILE_DUMMY= "dummy-newFile";
+
+ private static final String NEW_FOLDER_DUMMY= "dummy-newFolder";
+
+ public static class IncorrectUsage {
+ public TemporaryFolder folder= new TemporaryFolder();
+
+ @Test
+ public void testGetRoot() throws IOException {
+ new File(folder.getRoot(), GET_ROOT_DUMMY).createNewFile();
+ }
+
+ @Test
+ public void testNewFile() throws IOException {
+ folder.newFile(NEW_FILE_DUMMY);
+ }
+
+ @Test
+ public void testNewFolder() {
+ folder.newFolder(NEW_FOLDER_DUMMY);
+ }
+ }
+
+ @Test
+ public void incorrectUsageWithoutApplyingTheRuleShouldNotPolluteTheCurrentWorkingDirectory() {
+ assertThat(testResult(IncorrectUsage.class), failureCountIs(3));
+ assertFalse("getRoot should have failed early", new File(GET_ROOT_DUMMY).exists());
+ assertFalse("newFile should have failed early", new File(NEW_FILE_DUMMY).exists());
+ assertFalse("newFolder should have failed early", new File(NEW_FOLDER_DUMMY).exists());
+ }
+
+ @After
+ public void cleanCurrentWorkingDirectory() {
+ new File(GET_ROOT_DUMMY).delete();
+ new File(NEW_FILE_DUMMY).delete();
+ new File(NEW_FOLDER_DUMMY).delete();
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java
new file mode 100644
index 0000000..167eb20
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java
@@ -0,0 +1,289 @@
+package org.junit.tests.experimental.rules;
+
+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.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.TestName;
+import org.junit.rules.TestRule;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+
+public class TestRuleTest {
+ private static boolean wasRun;
+
+ public static class ExampleTest {
+ @Rule
+ public TestRule example= new TestRule() {
+ public Statement apply(final Statement base, Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ wasRun= true;
+ base.evaluate();
+ };
+ };
+ }
+ };
+
+ @Test
+ public void nothing() {
+
+ }
+ }
+
+ @Test
+ public void ruleIsIntroducedAndEvaluated() {
+ wasRun= false;
+ JUnitCore.runClasses(ExampleTest.class);
+ assertTrue(wasRun);
+ }
+
+ @SuppressWarnings("deprecation")
+ public static class BothKindsOfRule implements TestRule, org.junit.rules.MethodRule {
+ public int applications = 0;
+
+ public Statement apply(Statement base, FrameworkMethod method,
+ Object target) {
+ applications++;
+ return base;
+ }
+
+ public Statement apply(Statement base, Description description) {
+ applications++;
+ return base;
+ }
+ }
+
+ public static class OneFieldTwoKindsOfRule {
+ @Rule public BothKindsOfRule both = new BothKindsOfRule();
+
+ @Test public void onlyOnce() {
+ assertEquals(1, both.applications);
+ }
+ }
+
+
+ @Test
+ public void onlyApplyOnceEvenIfImplementsBothInterfaces() {
+ assertTrue(JUnitCore.runClasses(OneFieldTwoKindsOfRule.class).wasSuccessful());
+ }
+
+ public static class SonOfExampleTest extends ExampleTest {
+
+ }
+
+ @Test
+ public void ruleIsIntroducedAndEvaluatedOnSubclass() {
+ wasRun= false;
+ JUnitCore.runClasses(SonOfExampleTest.class);
+ assertTrue(wasRun);
+ }
+
+ private static int runCount;
+
+ public static class MultipleRuleTest {
+ private static class Increment implements TestRule {
+ public Statement apply(final Statement base, Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ runCount++;
+ base.evaluate();
+ };
+ };
+ }
+ }
+
+ @Rule
+ public TestRule incrementor1= new Increment();
+
+ @Rule
+ public TestRule incrementor2= new Increment();
+
+ @Test
+ public void nothing() {
+
+ }
+ }
+
+ @Test
+ public void multipleRulesAreRun() {
+ runCount= 0;
+ JUnitCore.runClasses(MultipleRuleTest.class);
+ assertEquals(2, runCount);
+ }
+
+ public static class NoRulesTest {
+ public int x;
+
+ @Test
+ public void nothing() {
+
+ }
+ }
+
+ @Test
+ public void ignoreNonRules() {
+ Result result= JUnitCore.runClasses(NoRulesTest.class);
+ assertEquals(0, result.getFailureCount());
+ }
+
+ private static String log;
+
+ public static class OnFailureTest {
+ @Rule
+ public TestRule watcher= new TestWatcher() {
+ @Override
+ protected void failed(Throwable e, Description description) {
+ log+= description + " " + e.getClass().getSimpleName();
+ }
+ };
+
+ @Test
+ public void nothing() {
+ fail();
+ }
+ }
+
+ @Test
+ public void onFailure() {
+ log= "";
+ Result result= JUnitCore.runClasses(OnFailureTest.class);
+ assertEquals(String.format("nothing(%s) AssertionError", OnFailureTest.class.getName()), log);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ public static class WatchmanTest {
+ private static String watchedLog;
+
+ @Rule
+ public TestRule watcher= new TestWatcher() {
+ @Override
+ protected void failed(Throwable e, Description description) {
+ watchedLog+= description + " "
+ + e.getClass().getSimpleName() + "\n";
+ }
+
+ @Override
+ protected void succeeded(Description description) {
+ watchedLog+= description + " " + "success!\n";
+ }
+ };
+
+ @Test
+ public void fails() {
+ fail();
+ }
+
+ @Test
+ public void succeeds() {
+ }
+ }
+
+ @Test
+ public void succeeded() {
+ WatchmanTest.watchedLog= "";
+ JUnitCore.runClasses(WatchmanTest.class);
+ assertThat(WatchmanTest.watchedLog, containsString(String.format("fails(%s) AssertionError", WatchmanTest.class.getName())));
+ assertThat(WatchmanTest.watchedLog, containsString(String.format("succeeds(%s) success!", WatchmanTest.class.getName())));
+ }
+
+ public static class BeforesAndAfters {
+ private static StringBuilder watchedLog= new StringBuilder();
+
+ @Before
+ public void before() {
+ watchedLog.append("before ");
+ }
+
+ @Rule
+ public TestRule watcher= new LoggingTestWatcher(watchedLog);
+
+ @After
+ public void after() {
+ watchedLog.append("after ");
+ }
+
+ @Test
+ public void succeeds() {
+ watchedLog.append("test ");
+ }
+ }
+
+ @Test
+ public void beforesAndAfters() {
+ BeforesAndAfters.watchedLog= new StringBuilder();
+ JUnitCore.runClasses(BeforesAndAfters.class);
+ assertThat(BeforesAndAfters.watchedLog.toString(),
+ is("starting before test after succeeded finished "));
+ }
+
+ public static class WrongTypedField {
+ @Rule public int x = 5;
+ @Test public void foo() {}
+ }
+
+ @Test public void validateWrongTypedField() {
+ assertThat(testResult(WrongTypedField.class),
+ hasSingleFailureContaining("must implement MethodRule"));
+ }
+
+ public static class SonOfWrongTypedField extends WrongTypedField {
+
+ }
+
+ @Test public void validateWrongTypedFieldInSuperclass() {
+ assertThat(testResult(SonOfWrongTypedField.class),
+ hasSingleFailureContaining("must implement MethodRule"));
+ }
+
+ public static class PrivateRule {
+ @SuppressWarnings("unused")
+ @Rule private TestRule rule = new TestName();
+ @Test public void foo() {}
+ }
+
+ @Test public void validatePrivateRule() {
+ assertThat(testResult(PrivateRule.class),
+ hasSingleFailureContaining("must be public"));
+ }
+
+ public static class CustomTestName implements TestRule {
+ public String name = null;
+
+ public Statement apply(final Statement base, final Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ name = description.getMethodName();
+ base.evaluate();
+ }
+ };
+ }
+ }
+
+ public static class UsesCustomMethodRule {
+ @Rule public CustomTestName counter = new CustomTestName();
+ @Test public void foo() {
+ assertEquals("foo", counter.name);
+ }
+ }
+
+ @Test public void useCustomMethodRule() {
+ assertThat(testResult(UsesCustomMethodRule.class), isSuccessful());
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java
new file mode 100644
index 0000000..19ac3e6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java
@@ -0,0 +1,52 @@
+package org.junit.tests.experimental.rules;
+
+import static junit.framework.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
+import static org.junit.runner.JUnitCore.runClasses;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+
+public class TestWatcherTest {
+ public static class ViolatedAssumptionTest {
+ private static StringBuilder watchedLog= new StringBuilder();
+
+ @Rule
+ public TestRule watcher= new LoggingTestWatcher(watchedLog);
+
+ @Test
+ public void succeeds() {
+ assumeTrue(false);
+ }
+ }
+
+ @Test
+ public void neitherLogSuccessNorFailedForViolatedAssumption() {
+ ViolatedAssumptionTest.watchedLog= new StringBuilder();
+ runClasses(ViolatedAssumptionTest.class);
+ assertThat(ViolatedAssumptionTest.watchedLog.toString(),
+ is("starting finished "));
+ }
+
+ public static class FailingTest {
+ private static StringBuilder watchedLog= new StringBuilder();
+
+ @Rule
+ public TestRule watcher= new LoggingTestWatcher(watchedLog);
+
+ @Test
+ public void succeeds() {
+ fail();
+ }
+ }
+
+ @Test
+ public void logFailingTest() {
+ FailingTest.watchedLog= new StringBuilder();
+ runClasses(FailingTest.class);
+ assertThat(FailingTest.watchedLog.toString(),
+ is("starting failed finished "));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/TestWatchmanTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/TestWatchmanTest.java
new file mode 100644
index 0000000..9ef22cb
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/TestWatchmanTest.java
@@ -0,0 +1,72 @@
+package org.junit.tests.experimental.rules;
+
+import static junit.framework.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
+import static org.junit.runner.JUnitCore.runClasses;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestWatchman;
+import org.junit.runners.model.FrameworkMethod;
+
+@SuppressWarnings("deprecation")
+public class TestWatchmanTest {
+ public static class ViolatedAssumptionTest {
+ @Rule
+ public static LoggingTestWatchman watchman= new LoggingTestWatchman();
+
+ @Test
+ public void succeeds() {
+ assumeTrue(false);
+ }
+ }
+
+ @Test
+ public void neitherLogSuccessNorFailedForViolatedAssumption() {
+ runClasses(ViolatedAssumptionTest.class);
+ assertThat(ViolatedAssumptionTest.watchman.log.toString(),
+ is("starting finished "));
+ }
+
+ public static class FailingTest {
+ @Rule
+ public static LoggingTestWatchman watchman= new LoggingTestWatchman();
+
+ @Test
+ public void succeeds() {
+ fail();
+ }
+ }
+
+ @Test
+ public void logFailingTest() {
+ runClasses(FailingTest.class);
+ assertThat(FailingTest.watchman.log.toString(),
+ is("starting failed finished "));
+ }
+
+ private static class LoggingTestWatchman extends TestWatchman {
+ private final StringBuilder log= new StringBuilder();
+
+ @Override
+ public void succeeded(FrameworkMethod method) {
+ log.append("succeeded ");
+ }
+
+ @Override
+ public void failed(Throwable e, FrameworkMethod method) {
+ log.append("failed ");
+ }
+
+ @Override
+ public void starting(FrameworkMethod method) {
+ log.append("starting ");
+ }
+
+ @Override
+ public void finished(FrameworkMethod method) {
+ log.append("finished ");
+ }
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java
new file mode 100644
index 0000000..28d3553
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java
@@ -0,0 +1,39 @@
+package org.junit.tests.experimental.rules;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.matchers.JUnitMatchers.containsString;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.rules.Timeout;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+
+public class TimeoutRuleTest {
+ public static class HasGlobalTimeout {
+ public static String log;
+
+ @Rule public TestRule globalTimeout = new Timeout(20);
+
+ @Test public void testInfiniteLoop1() {
+ log+= "ran1";
+ for(;;) {}
+ }
+
+ @Test public void testInfiniteLoop2() {
+ log+= "ran2";
+ for(;;) {}
+ }
+ }
+
+ @Ignore("For gump, for now")
+ @Test(timeout=100) public void globalTimeoutAvoidsInfiniteLoop() {
+ HasGlobalTimeout.log = "";
+ Result result= JUnitCore.runClasses(HasGlobalTimeout.class);
+ assertEquals(2, result.getFailureCount());
+ assertThat(HasGlobalTimeout.log, containsString("ran1"));
+ assertThat(HasGlobalTimeout.log, containsString("ran2"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java b/junit4/src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java
new file mode 100644
index 0000000..ef75174
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java
@@ -0,0 +1,133 @@
+package org.junit.tests.experimental.rules;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+
+import java.util.concurrent.Callable;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.results.PrintableResult;
+import org.junit.rules.ErrorCollector;
+import org.junit.rules.Verifier;
+
+public class VerifierRuleTest {
+ public static class UsesErrorCollector {
+ @Rule
+ public ErrorCollector collector= new ErrorCollector();
+
+ @Test public void example() {
+ collector.addError(new Throwable("message"));
+ }
+ }
+
+ @Test public void usedErrorCollectorShouldFail() {
+ assertThat(testResult(UsesErrorCollector.class), hasFailureContaining("message"));
+ }
+
+ public static class UsesErrorCollectorTwice {
+ @Rule
+ public ErrorCollector collector= new ErrorCollector();
+
+ @Test public void example() {
+ collector.addError(new Throwable("first thing went wrong"));
+ collector.addError(new Throwable("second thing went wrong"));
+ }
+ }
+
+ @Test public void usedErrorCollectorTwiceShouldFail() {
+ PrintableResult testResult= testResult(UsesErrorCollectorTwice.class);
+ assertThat(testResult, hasFailureContaining("first thing went wrong"));
+ assertThat(testResult, hasFailureContaining("second thing went wrong"));
+ }
+
+ public static class UsesErrorCollectorCheckThat {
+ @Rule
+ public ErrorCollector collector= new ErrorCollector();
+
+ @Test public void example() {
+ collector.checkThat(3, is(4));
+ collector.checkThat(5, is(6));
+ collector.checkThat("reason 1", 7, is(8));
+ collector.checkThat("reason 2", 9, is(16));
+ }
+ }
+
+ @Test public void usedErrorCollectorCheckThatShouldFail() {
+ PrintableResult testResult= testResult(UsesErrorCollectorCheckThat.class);
+ assertThat(testResult, hasFailureContaining("got: <3>"));
+ assertThat(testResult, hasFailureContaining("got: <5>"));
+ assertThat(testResult, hasFailureContaining("reason 1"));
+ assertThat(testResult, hasFailureContaining("got: <7>"));
+ assertThat(testResult, hasFailureContaining("reason 2"));
+ assertThat(testResult, hasFailureContaining("got: <9>"));
+ }
+
+ public static class UsesErrorCollectorCheckSucceeds {
+ @Rule
+ public ErrorCollector collector= new ErrorCollector();
+
+ @Test public void example() {
+ collector.checkSucceeds(new Callable<Object>() {
+ public Object call() throws Exception {
+ throw new RuntimeException("first!");
+ }
+ });
+ collector.checkSucceeds(new Callable<Object>() {
+ public Object call() throws Exception {
+ throw new RuntimeException("second!");
+ }
+ });
+ }
+ }
+
+ @Test public void usedErrorCollectorCheckSucceedsShouldFail() {
+ PrintableResult testResult= testResult(UsesErrorCollectorCheckSucceeds.class);
+ assertThat(testResult, hasFailureContaining("first!"));
+ assertThat(testResult, hasFailureContaining("second!"));
+ }
+
+ public static class UsesErrorCollectorCheckSucceedsPasses {
+ @Rule
+ public ErrorCollector collector= new ErrorCollector();
+
+ @Test public void example() {
+ assertEquals(3, collector.checkSucceeds(new Callable<Object>() {
+ public Object call() throws Exception {
+ return 3;
+ }
+ }));
+ }
+ }
+
+ @Test public void usedErrorCollectorCheckSucceedsShouldPass() {
+ PrintableResult testResult= testResult(UsesErrorCollectorCheckSucceedsPasses.class);
+ assertThat(testResult, isSuccessful());
+ }
+
+ private static String sequence;
+
+ public static class UsesVerifier {
+ @Rule
+ public Verifier collector= new Verifier() {
+ @Override
+ protected void verify() {
+ sequence+= "verify ";
+ }
+ };
+
+ @Test public void example() {
+ sequence+= "test ";
+ }
+ }
+
+ @Test public void verifierRunsAfterTest() {
+ sequence = "";
+ assertThat(testResult(UsesVerifier.class), isSuccessful());
+ assertEquals("test verify ", sequence);
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/AllMembersSupplierTest.java b/junit4/src/test/java/org/junit/tests/experimental/theories/AllMembersSupplierTest.java
new file mode 100644
index 0000000..e3fa0f0
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/AllMembersSupplierTest.java
@@ -0,0 +1,34 @@
+package org.junit.tests.experimental.theories;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.ParameterSignature;
+import org.junit.experimental.theories.PotentialAssignment;
+import org.junit.experimental.theories.internal.AllMembersSupplier;
+import org.junit.runners.model.TestClass;
+
+public class AllMembersSupplierTest {
+ public static class HasDataPoints {
+ @DataPoints
+ public static Object[] objects= { 1, 2 };
+
+ public HasDataPoints(Object obj) {
+ }
+ }
+
+ @Test
+ public void dataPointsAnnotationMeansTreatAsArrayOnly()
+ throws SecurityException, NoSuchMethodException {
+ List<PotentialAssignment> valueSources= new AllMembersSupplier(
+ new TestClass(HasDataPoints.class))
+ .getValueSources(ParameterSignature.signatures(
+ HasDataPoints.class.getConstructor(Object.class))
+ .get(0));
+ assertThat(valueSources.size(), is(2));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java b/junit4/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java
new file mode 100644
index 0000000..c0191c4
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java
@@ -0,0 +1,57 @@
+package org.junit.tests.experimental.theories;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
+import static org.junit.matchers.JUnitMatchers.hasItem;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.ParameterSignature;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.experimental.theories.suppliers.TestedOn;
+import org.junit.runner.RunWith;
+
+@RunWith(Theories.class)
+public class ParameterSignatureTest {
+ @DataPoint
+ public static Method getType() throws SecurityException,
+ NoSuchMethodException {
+ return ParameterSignatureTest.class.getMethod("getType", Method.class,
+ int.class);
+ }
+
+ @DataPoint
+ public static int ZERO= 0;
+
+ @DataPoint
+ public static int ONE= 1;
+
+ @Theory
+ public void getType(Method method, int index) {
+ assumeTrue(index < method.getParameterTypes().length);
+ assertEquals(method.getParameterTypes()[index], ParameterSignature
+ .signatures(method).get(index).getType());
+ }
+
+ public void foo(@TestedOn(ints= { 1, 2, 3 })
+ int x) {
+ }
+
+ @Test
+ public void getAnnotations() throws SecurityException,
+ NoSuchMethodException {
+ Method method= ParameterSignatureTest.class.getMethod("foo", int.class);
+ List<Annotation> annotations= ParameterSignature.signatures(method)
+ .get(0).getAnnotations();
+ assertThat(new ArrayList<Object>(annotations),
+ hasItem(is(TestedOn.class)));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java b/junit4/src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java
new file mode 100644
index 0000000..91c0e04
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java
@@ -0,0 +1,75 @@
+package org.junit.tests.experimental.theories;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeThat;
+import static org.junit.internal.matchers.StringContains.containsString;
+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.experimental.theories.internal.ParameterizedAssertionError;
+import org.junit.runner.RunWith;
+
+@RunWith(Theories.class)
+public class ParameterizedAssertionErrorTest {
+ @DataPoint
+ public static final String METHOD_NAME= "methodName";
+
+ @DataPoint
+ public static final NullPointerException NULL_POINTER_EXCEPTION= new NullPointerException();
+
+ @DataPoint
+ public static Object[] NO_OBJECTS= new Object[0];
+
+ @DataPoint
+ public static ParameterizedAssertionError A= new ParameterizedAssertionError(
+ NULL_POINTER_EXCEPTION, METHOD_NAME);
+
+ @DataPoint
+ public static ParameterizedAssertionError B= new ParameterizedAssertionError(
+ NULL_POINTER_EXCEPTION, METHOD_NAME);
+
+ @DataPoint
+ public static ParameterizedAssertionError B2= new ParameterizedAssertionError(
+ NULL_POINTER_EXCEPTION, "methodName2");
+
+ @Theory
+ public void equalParameterizedAssertionErrorsHaveSameToString(
+ ParameterizedAssertionError a, ParameterizedAssertionError b) {
+ assumeThat(a, is(b));
+ assertThat(a.toString(), is(b.toString()));
+ }
+
+ @Theory
+ public void differentParameterizedAssertionErrorsHaveDifferentToStrings(
+ ParameterizedAssertionError a, ParameterizedAssertionError b) {
+ assumeThat(a, not(b));
+ assertThat(a.toString(), not(b.toString()));
+ }
+
+ @Theory
+ public void equalsReturnsTrue(Throwable targetException, String methodName,
+ Object[] params) {
+ assertThat(new ParameterizedAssertionError(targetException, methodName,
+ params), is(new ParameterizedAssertionError(targetException,
+ methodName, params)));
+ }
+
+ @Theory(nullsAccepted= false)
+ public void buildParameterizedAssertionError(String methodName, String param) {
+ assertThat(new ParameterizedAssertionError(new RuntimeException(),
+ methodName, param).toString(), containsString(methodName));
+ }
+
+ @Test
+ public void canJoinWhenToStringFails() {
+ assertThat(ParameterizedAssertionError.join(" ", new Object() {
+ @Override
+ public String toString() {
+ throw new UnsupportedOperationException();
+ }
+ }), is("[toString failed]"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java
new file mode 100644
index 0000000..60d7836
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java
@@ -0,0 +1,7 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+public interface Correspondent {
+
+ String getAnswer(String question, String... bucket);
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java
new file mode 100644
index 0000000..dcc5627
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java
@@ -0,0 +1,122 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Random;
+import java.util.Map.Entry;
+
+import org.hamcrest.BaseDescription;
+import org.hamcrest.Description;
+import org.junit.internal.AssumptionViolatedException;
+
+public class Guesser<T> extends ReguessableValue {
+ static class GuessMap extends HashMap<MethodCall, Object> implements
+ InvocationHandler {
+ private static final long serialVersionUID= 1L;
+
+ public GuessMap(GuessMap guesses) {
+ super(guesses);
+ }
+
+ public GuessMap() {
+ }
+
+ GuessMap replaceGuess(Object oldValue, Object newValue) {
+ GuessMap newGuesses= new GuessMap(this);
+ for (Entry<MethodCall, Object> entry : newGuesses.entrySet()) {
+ if (entry.getValue().equals(oldValue))
+ entry.setValue(newValue);
+ }
+ return newGuesses;
+ }
+
+ protected Object generateGuess(Class<?> returnType) {
+ if (returnType.equals(String.class))
+ return "GUESS" + new Random().nextInt();
+ if (returnType.equals(Integer.class)
+ || returnType.equals(int.class))
+ return new Random().nextInt();
+ return null;
+ }
+
+ Object getGuess(MethodCall call) {
+ if (!containsKey(call))
+ put(call, generateGuess(call.getReturnType()));
+ return get(call);
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ return getGuess(new MethodCall(method, args));
+ }
+ }
+
+ private final GuessMap guesses;
+
+ private final Class<? extends T> type;
+
+ public Guesser(Class<? extends T> type) {
+ this(type, new GuessMap());
+ }
+
+ public Guesser(Class<? extends T> type2, GuessMap guesses) {
+ this.type= type2;
+ this.guesses= guesses;
+ }
+
+ @SuppressWarnings("unchecked")
+ public T getProxy() {
+ return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class[] { getType() }, guesses);
+ }
+
+ @Override
+ public List<ReguessableValue> reguesses(AssumptionViolatedException e) {
+ final ArrayList<ReguessableValue> returnThis= new ArrayList<ReguessableValue>();
+ e.describeTo(new BaseDescription() {
+ @Override
+ protected void append(char arg0) {
+ }
+
+ boolean expectedSeen= false;
+ Object expected= null;
+
+ @Override
+ public Description appendValue(Object value) {
+ noteValue(value);
+ return super.appendValue(value);
+ }
+
+ private void noteValue(Object value) {
+ if (!expectedSeen) {
+ expected= value;
+ expectedSeen= true;
+ return;
+ }
+
+ GuessMap newGuesses= guesses.replaceGuess(expected, value);
+ returnThis.add(new Guesser<T>(getType(), newGuesses));
+ }
+ });
+ return returnThis;
+ }
+
+ @Override
+ public Object getValue() throws CouldNotGenerateValueException {
+ return getProxy();
+ }
+
+ public Class<? extends T> getType() {
+ return type;
+ }
+
+ @Override
+ public String getDescription() throws CouldNotGenerateValueException {
+ return "guesser[" + type + "]";
+ }
+
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java
new file mode 100644
index 0000000..f3eb550
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java
@@ -0,0 +1,57 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.experimental.theories.PotentialAssignment;
+import org.junit.internal.AssumptionViolatedException;
+
+public class GuesserQueue extends ArrayList<ReguessableValue> {
+ static class ReguessableDecorator extends ReguessableValue {
+ private final PotentialAssignment delegate;
+
+ public ReguessableDecorator(PotentialAssignment delegate) {
+ this.delegate= delegate;
+ }
+
+ @Override
+ public List<ReguessableValue> reguesses(AssumptionViolatedException e) {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public Object getValue() throws CouldNotGenerateValueException {
+ return delegate.getValue();
+ }
+
+ @Override
+ public String getDescription() throws CouldNotGenerateValueException {
+ return delegate.getDescription();
+ }
+ }
+
+ static GuesserQueue forSingleValues(
+ List<PotentialAssignment> potentials) {
+ GuesserQueue returnThis= new GuesserQueue();
+ for (PotentialAssignment potentialParameterValue : potentials) {
+ returnThis
+ .add(new GuesserQueue.ReguessableDecorator(potentialParameterValue));
+ }
+ return returnThis;
+ }
+
+ private static final long serialVersionUID = 1L;
+ private ReguessableValue lastRemoved;
+
+ public void update(AssumptionViolatedException e) {
+ if (lastRemoved != null)
+ addAll(lastRemoved.reguesses(e));
+ }
+
+ @Override
+ public ReguessableValue remove(int index) {
+ lastRemoved = super.remove(index);
+ return lastRemoved;
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java
new file mode 100644
index 0000000..85c44c5
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java
@@ -0,0 +1,54 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class MethodCall {
+ private final Method method;
+ private final Object[] args;
+
+ public MethodCall(Method method, Object... args) {
+ this.method = method;
+ this.args = args;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ MethodCall call = (MethodCall) obj;
+ return call.method.equals(method) && Arrays.deepEquals(call.args, args);
+ }
+
+ @Override
+ public int hashCode() {
+ return 1;
+ }
+
+ public Class<?> getReturnType() {
+ return method.getReturnType();
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s(%s)", method.getName(), argListString());
+ }
+
+ private String argListString() {
+ if (args == null)
+ return null;
+ return argList().toString().substring(1, argList().toString().length() - 1);
+ }
+
+ private List<Object> argList() {
+ ArrayList<Object> list = new ArrayList<Object>();
+ for (Object arg : args) {
+ list.add(new StringableObject(arg));
+ }
+ return list;
+ }
+
+ public Object stringableObject(Object arg) {
+ return new StringableObject(arg).stringableObject();
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java
new file mode 100644
index 0000000..6c96ed6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java
@@ -0,0 +1,16 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+import java.util.List;
+
+import org.junit.experimental.theories.PotentialAssignment;
+import org.junit.internal.AssumptionViolatedException;
+
+public abstract class ReguessableValue extends PotentialAssignment {
+
+ public ReguessableValue() {
+ super();
+ }
+
+ public abstract List<ReguessableValue> reguesses(
+ AssumptionViolatedException e);
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java
new file mode 100644
index 0000000..94d5b31
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java
@@ -0,0 +1,27 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+import java.util.Arrays;
+
+public class StringableObject {
+ public Object obj;
+
+ public StringableObject(Object obj) {
+ this.obj = obj;
+ }
+
+ public Object stringableObject() {
+ if (isListableArray())
+ return Arrays.asList((Object[]) obj);
+ else
+ return obj;
+ }
+
+ private boolean isListableArray() {
+ Class<?> type = obj.getClass();
+ return type.isArray() && !type.getComponentType().isPrimitive();
+ }
+
+ @Override public String toString() {
+ return stringableObject().toString();
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java
new file mode 100644
index 0000000..aa320d5
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java
@@ -0,0 +1,8 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Stub {
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java
new file mode 100644
index 0000000..91c0b42
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java
@@ -0,0 +1,65 @@
+package org.junit.tests.experimental.theories.extendingwithstubs;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.experimental.theories.ParameterSignature;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.internal.Assignments;
+import org.junit.internal.AssumptionViolatedException;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.InitializationError;
+import org.junit.runners.model.Statement;
+import org.junit.runners.model.TestClass;
+
+public class StubbedTheories extends Theories {
+ public StubbedTheories(Class<?> klass) throws InitializationError {
+ super(klass);
+ }
+
+ @Override
+ public Statement methodBlock(FrameworkMethod method) {
+ return new StubbedTheoryAnchor(method, getTestClass());
+ }
+
+ public static class StubbedTheoryAnchor extends TheoryAnchor {
+ public StubbedTheoryAnchor(FrameworkMethod method, TestClass testClass) {
+ super(method, testClass);
+ }
+
+ private List<GuesserQueue> queues= new ArrayList<GuesserQueue>();
+
+ @Override
+ protected void handleAssumptionViolation(AssumptionViolatedException e) {
+ super.handleAssumptionViolation(e);
+ for (GuesserQueue queue : queues)
+ queue.update(e);
+ }
+
+ @Override
+ protected void runWithIncompleteAssignment(Assignments incomplete)
+ throws InstantiationException, IllegalAccessException,
+ Throwable {
+ GuesserQueue guessers= createGuesserQueue(incomplete);
+ queues.add(guessers);
+ while (!guessers.isEmpty())
+ runWithAssignment(incomplete.assignNext(guessers.remove(0)));
+ queues.remove(guessers);
+ }
+
+ private GuesserQueue createGuesserQueue(Assignments incomplete)
+ throws InstantiationException, IllegalAccessException {
+ ParameterSignature nextUnassigned= incomplete.nextUnassigned();
+
+ if (nextUnassigned.hasAnnotation(Stub.class)) {
+ GuesserQueue queue= new GuesserQueue();
+ queue.add(new Guesser<Object>(nextUnassigned.getType()));
+ return queue;
+ }
+
+ return GuesserQueue.forSingleValues(incomplete.potentialsForNextUnassigned());
+ }
+ }
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java
new file mode 100644
index 0000000..24abd7a
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java
@@ -0,0 +1 @@
+package org.junit.tests.experimental.theories.extendingwithstubs; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assume.assumeThat; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; @RunWith(StubbedTheories.class) public class StubbedTheoriesTest { @Theory public void ask(@Stub Correspondent correspondent) { assumeThat(correspondent.getAnswer("What is five?", "four", "five"), is("five")); } } \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java
new file mode 100644
index 0000000..ba3f149
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java
@@ -0,0 +1,204 @@
+package org.junit.tests.experimental.theories.runner;
+
+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.Assume.assumeTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.runners.Enclosed;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+
+@RunWith(Enclosed.class)
+public class SuccessfulWithDataPointFields {
+ @RunWith(Theories.class)
+ public static class HasATwoParameterTheory {
+ @DataPoint
+ public static int ONE= 1;
+
+ @Theory
+ public void allIntsAreEqual(int x, int y) {
+ assertThat(x, is(y));
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class BeforeAndAfterOnSameInstance {
+ @DataPoint
+ public static String A= "A";
+
+ private int befores= 0;
+
+ @Before
+ public void incrementBefore() {
+ befores++;
+ }
+
+ @Theory
+ public void stringsAreOK(String string) {
+ assertTrue(befores == 1);
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class NewObjectEachTime {
+ @DataPoint
+ public static String A= "A";
+
+ @DataPoint
+ public static String B= "B";
+
+ private List<String> list= new ArrayList<String>();
+
+ @Theory
+ public void addToEmptyList(String string) {
+ list.add(string);
+ assertThat(list.size(), is(1));
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class PositiveInts {
+ @DataPoint
+ public static final int ONE= 1;
+
+ private int x;
+
+ public PositiveInts(int x) {
+ assumeTrue(x > 0);
+ this.x= x;
+ }
+
+ @Theory
+ public void haveAPostiveSquare() {
+ assertTrue(x * x > 0);
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class PositiveIntsWithNegativeField {
+ @DataPoint
+ public static final int ONE= 1;
+ @DataPoint
+ public static final int NEGONE= -1;
+
+ private int x;
+
+ public PositiveIntsWithNegativeField(int x) {
+ assumeTrue(x > 0);
+ this.x= x;
+ }
+
+ @Theory
+ public void haveAPostiveSquare() {
+ assertTrue(x > 0);
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class PositiveIntsWithMethodParams {
+ @DataPoint
+ public static final int ONE= 1;
+
+ private int x;
+
+ public PositiveIntsWithMethodParams(int x) {
+ assumeTrue(x > 0);
+ this.x= x;
+ }
+
+ @Theory
+ public void haveAPostiveSquare(int y) {
+ assumeTrue(y > 0);
+ assertTrue(x * y > 0);
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class DifferentTypesInConstructor {
+ @DataPoint
+ public static final int ONE= 1;
+
+ @DataPoint public static final String A = "A";
+
+ public DifferentTypesInConstructor(int x) {
+ }
+
+ @Theory
+ public void yesIndeed(String a) {
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class BeforeAndAfterEachTime {
+ public static int befores= 0;
+
+ @DataPoint
+ public static String A= "A";
+
+ @DataPoint
+ public static String B= "B";
+
+ @Before
+ public void incrementBefore() {
+ befores++;
+ }
+
+ @BeforeClass public static void resetCalls() {
+ befores = 0;
+ }
+
+ @Theory
+ public void stringsAreOK(String string) {
+ }
+
+ @AfterClass public static void calledTwice() {
+ assertEquals(2, befores);
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class OneTestTwoAnnotations {
+ public static int tests= 0;
+
+ @DataPoint
+ public static String A= "A";
+
+ @BeforeClass public static void resetCalls() {
+ tests = 0;
+ }
+
+ @Theory @Test
+ public void stringsAreOK(String string) {
+ tests++;
+ }
+
+ @AfterClass public static void calledTwice() {
+ assertEquals(1, tests);
+ }
+ }
+
+ @RunWith(Theories.class)
+ static public class StaticPublicNonDataPoints {
+ // DataPoint which passes the test
+ @DataPoint public static int ZERO = 0;
+
+ // Not annotated as a DataPoint and therefore should be ignored:
+ public static int ONE = 1;
+
+ @Theory
+ public void onlyAnnotatedFields(int i) {
+ assertTrue(i == 0);
+ }
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java
new file mode 100644
index 0000000..52dc528
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java
@@ -0,0 +1,37 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeTrue;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import org.junit.Test;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+
+public class TheoriesPerformanceTest {
+ @RunWith(Theories.class)
+ public static class UpToTen {
+ @DataPoints
+ public static int[] ints= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+
+ @Theory
+ public void threeInts(int x, int y, int z) {
+ // pass always
+ }
+ }
+
+ private static final boolean TESTING_PERFORMANCE= false;
+
+ // If we do not share the same instance of TestClass, repeatedly parsing the
+ // class's annotations looking for @Befores and @Afters gets really costly.
+ //
+ // Likewise, the TestClass must be passed into AllMembersSupplier, or the
+ // annotation parsing is again costly.
+ @Test
+ public void tryCombinationsQuickly() {
+ assumeTrue(TESTING_PERFORMANCE);
+ assertThat(testResult(UpToTen.class), isSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java
new file mode 100644
index 0000000..790d798
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java
@@ -0,0 +1,126 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.failureCountIs;
+import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;
+import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;
+import static org.junit.matchers.JUnitMatchers.both;
+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;
+import org.junit.runners.model.TestClass;
+
+public class UnsuccessfulWithDataPointFields {
+ @RunWith(Theories.class)
+ public static class HasATheory {
+ @DataPoint
+ public static int ONE= 1;
+
+ @Theory
+ public void everythingIsZero(int x) {
+ assertThat(x, is(0));
+ }
+ }
+
+ @Test
+ public void theoryClassMethodsShowUp() throws Exception {
+ assertThat(new Theories(HasATheory.class).getDescription()
+ .getChildren().size(), is(1));
+ }
+
+ @Test
+ public void theoryAnnotationsAreRetained() throws Exception {
+ assertThat(new TestClass(HasATheory.class).getAnnotatedMethods(
+ Theory.class).size(), is(1));
+ }
+
+ @Test
+ public void canRunTheories() throws Exception {
+ assertThat(testResult(HasATheory.class),
+ hasSingleFailureContaining("Expected"));
+ }
+
+ @RunWith(Theories.class)
+ public static class DoesntUseParams {
+ @DataPoint
+ public static int ONE= 1;
+
+ @Theory
+ public void everythingIsZero(int x, int y) {
+ assertThat(2, is(3));
+ }
+ }
+
+ @Test
+ public void reportBadParams() throws Exception {
+ assertThat(testResult(DoesntUseParams.class),
+ hasSingleFailureContaining("everythingIsZero(ONE, ONE)"));
+ }
+
+ @RunWith(Theories.class)
+ public static class NullsOK {
+ @DataPoint
+ public static String NULL= null;
+
+ @DataPoint
+ public static String A= "A";
+
+ @Theory
+ public void everythingIsA(String a) {
+ assertThat(a, is("A"));
+ }
+ }
+
+ @Test
+ public void nullsUsedUnlessProhibited() throws Exception {
+ assertThat(testResult(NullsOK.class),
+ hasSingleFailureContaining("null"));
+ }
+
+ @RunWith(Theories.class)
+ public static class DataPointsMustBeStatic {
+ @DataPoint
+ int THREE= 3;
+
+ @DataPoint
+ int FOUR= 3;
+
+ @Theory
+ public void numbers(int x) {
+
+ }
+ }
+
+ @Test
+ public void dataPointsMustBeStatic() {
+ assertThat(
+ testResult(DataPointsMustBeStatic.class),
+ both(failureCountIs(2))
+ .and(
+ hasFailureContaining("DataPoint field THREE must be static"))
+ .and(
+ hasFailureContaining("DataPoint field FOUR must be static")));
+ }
+
+ @RunWith(Theories.class)
+ public static class TheoriesMustBePublic {
+ @DataPoint
+ public static int THREE= 3;
+
+ @Theory
+ void numbers(int x) {
+
+ }
+ }
+
+ @Test
+ public void theoriesMustBePublic() {
+ assertThat(
+ testResult(TheoriesMustBePublic.class),
+ hasSingleFailureContaining("public"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java
new file mode 100644
index 0000000..3c83d82
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java
@@ -0,0 +1,50 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assume.assumeThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.internal.matchers.StringContains.containsString;
+import org.hamcrest.Matcher;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+
+@RunWith(Theories.class)
+public class WhenNoParametersMatch {
+ @DataPoints
+ public static int[] ints= { 0, 1, 3, 5, 1776 };
+
+ @DataPoints
+ public static Matcher<?>[] matchers= { not(0), is(1) };
+
+ @RunWith(Theories.class)
+ public static class AssumptionsFail {
+ @DataPoint
+ public static int DATA= 0;
+
+ @DataPoint
+ public static Matcher<Integer> MATCHER= null;
+
+ @Theory
+ public void nonZeroIntsAreFun(int x) {
+ assumeThat(x, MATCHER);
+ }
+ }
+
+ @Theory
+ public void showFailedAssumptionsWhenNoParametersFound(int data,
+ Matcher<Integer> matcher) throws Exception {
+ assumeThat(data, not(matcher));
+ AssumptionsFail.DATA= data;
+ AssumptionsFail.MATCHER= matcher;
+
+ String result= testResult(AssumptionsFail.class).toString();
+
+ assertThat(result, containsString(matcher.toString()));
+ assertThat(result, containsString("" + data));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java
new file mode 100644
index 0000000..659f430
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java
@@ -0,0 +1,152 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import static org.junit.internal.matchers.Each.each;
+import static org.junit.internal.matchers.StringContains.containsString;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.hamcrest.Matcher;
+import org.junit.Test;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.PotentialAssignment;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.experimental.theories.internal.Assignments;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.RunWith;
+import org.junit.runner.notification.Failure;
+import org.junit.runners.model.TestClass;
+
+public class WithDataPointMethod {
+ @RunWith(Theories.class)
+ public static class HasDataPointMethod {
+ @DataPoint
+ public static int oneHundred() {
+ return 100;
+ }
+
+ @Theory
+ public void allIntsOk(int x) {
+
+ }
+ }
+
+ @RunWith(Theories.class)
+ public static class HasUglyDataPointMethod {
+ @DataPoint
+ public static int oneHundred() {
+ return 100;
+ }
+
+ @DataPoint
+ public static int oneUglyHundred() {
+ throw new RuntimeException();
+ }
+
+ @Theory
+ public void allIntsOk(int x) {
+
+ }
+ }
+
+ @Test
+ public void pickUpDataPointMethods() {
+ assertThat(testResult(HasDataPointMethod.class), isSuccessful());
+ }
+
+ @Test
+ public void ignoreExceptionsFromDataPointMethods() {
+ assertThat(testResult(HasUglyDataPointMethod.class), isSuccessful());
+ }
+
+ @RunWith(Theories.class)
+ public static class DataPointMethodReturnsMutableObject {
+ @DataPoint
+ public static List<Object> empty() {
+ return new ArrayList<Object>();
+ }
+
+ @DataPoint
+ public static int ONE= 1;
+
+ @DataPoint
+ public static int TWO= 2;
+
+ @Theory
+ public void everythingsEmpty(List<Object> first, int number) {
+ assertThat(first.size(), is(0));
+ first.add("a");
+ }
+ }
+
+ @Test
+ public void mutableObjectsAreCreatedAfresh() {
+ assertThat(failures(DataPointMethodReturnsMutableObject.class), empty());
+ }
+
+ @RunWith(Theories.class)
+ public static class HasDateMethod {
+ @DataPoint
+ public int oneHundred() {
+ return 100;
+ }
+
+ public Date notADataPoint() {
+ return new Date();
+ }
+
+ @Theory
+ public void allIntsOk(int x) {
+
+ }
+
+ @Theory
+ public void onlyStringsOk(String s) {
+
+ }
+
+ @Theory
+ public void onlyDatesOk(Date d) {
+
+ }
+ }
+
+ @Test
+ public void ignoreDataPointMethodsWithWrongTypes() throws Exception {
+ assertThat(potentialValues(
+ HasDateMethod.class.getMethod("onlyStringsOk", String.class))
+ .toString(), not(containsString("100")));
+ }
+
+ @Test
+ public void ignoreDataPointMethodsWithoutAnnotation() throws Throwable {
+ assertThat(potentialValues(
+ HasDateMethod.class.getMethod("onlyDatesOk", Date.class))
+ .size(), is(0));
+ }
+
+ private List<PotentialAssignment> potentialValues(Method method)
+ throws Exception {
+ return Assignments.allUnassigned(method,
+ new TestClass(HasDateMethod.class))
+ .potentialsForNextUnassigned();
+ }
+
+ private List<Failure> failures(Class<?> type) {
+ return JUnitCore.runClasses(type).getFailures();
+ }
+
+ private Matcher<Iterable<Failure>> empty() {
+ Matcher<Failure> nullValue= nullValue();
+ return each(nullValue);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java
new file mode 100644
index 0000000..9b5f0ae
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java
@@ -0,0 +1,146 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import org.junit.Test;
+import org.junit.experimental.results.ResultMatchers;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.experimental.theories.suppliers.TestedOn;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.RunWith;
+
+public class WithExtendedParameterSources {
+ @RunWith(Theories.class)
+ public static class ParameterAnnotations {
+ @Theory
+ public void everythingIsOne(@TestedOn(ints= { 1 })
+ int number) {
+ assertThat(number, is(1));
+ }
+ }
+
+ @Test
+ public void testedOnLimitsParameters() throws Exception {
+ assertThat(testResult(ParameterAnnotations.class), ResultMatchers
+ .isSuccessful());
+ }
+
+ @RunWith(Theories.class)
+ public static class ShouldFilterNull {
+ @DataPoint
+ public static String NULL= null;
+
+ @DataPoint
+ public static String A= "a";
+
+ @Theory(nullsAccepted= false)
+ public void allStringsAreNonNull(String s) {
+ assertThat(s, notNullValue());
+ }
+ }
+
+ @Test
+ public void shouldFilterNull() {
+ assertThat(testResult(ShouldFilterNull.class), isSuccessful());
+ }
+
+ @RunWith(Theories.class)
+ public static class DataPointArrays {
+ public static String log= "";
+
+ @DataPoints
+ public static String[] STRINGS= new String[] { "A", "B" };
+
+ @Theory
+ public void addToLog(String string) {
+ log+= string;
+ }
+ }
+
+ @Test
+ public void getDataPointsFromArray() {
+ DataPointArrays.log= "";
+ JUnitCore.runClasses(DataPointArrays.class);
+ assertThat(DataPointArrays.log, is("AB"));
+ }
+
+ @RunWith(Theories.class)
+ public static class DataPointArrayMethod {
+ public static String log= "";
+
+ @DataPoints
+ public static String[] STRINGS() {
+ return new String[] { "A", "B" };
+ };
+
+ @Theory
+ public void addToLog(String string) {
+ log+= string;
+ }
+ }
+
+ @Test
+ public void getDataPointsFromArrayMethod() {
+ DataPointArrayMethod.log= "";
+ JUnitCore.runClasses(DataPointArrayMethod.class);
+ assertThat(DataPointArrayMethod.log, is("AB"));
+ }
+
+ @RunWith(Theories.class)
+ public static class DataPointMalformedArrayMethods {
+ public static String log= "";
+
+ @DataPoints
+ public static String[] STRINGS() {
+ return new String[] { "A", "B" };
+ };
+
+ @DataPoints
+ public static String STRING() {
+ return "C";
+ }
+
+ @DataPoints
+ public static int[] INTS() {
+ return new int[] { 1, 2, 3 };
+ }
+
+ @Theory
+ public void addToLog(String string) {
+ log+= string;
+ }
+ }
+
+ @Test
+ public void getDataPointsFromArrayMethodInSpiteOfMalformedness() {
+ DataPointArrayMethod.log= "";
+ JUnitCore.runClasses(DataPointArrayMethod.class);
+ assertThat(DataPointArrayMethod.log, is("AB"));
+ }
+
+ @RunWith(Theories.class)
+ public static class DataPointArrayToBeUsedForWholeParameter {
+ public static String log= "";
+
+ @DataPoint
+ public static String[] STRINGS= new String[] { "A", "B" };
+
+ @Theory
+ public void addToLog(String[] strings) {
+ log+= strings[0];
+ }
+ }
+
+ @Test
+ public void dataPointCanBeArray() {
+ DataPointArrayToBeUsedForWholeParameter.log= "";
+ JUnitCore.runClasses(DataPointArrayToBeUsedForWholeParameter.class);
+ assertThat(DataPointArrayToBeUsedForWholeParameter.log, is("A"));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java
new file mode 100644
index 0000000..2204fb6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java
@@ -0,0 +1,80 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.failureCountIs;
+import static org.junit.experimental.results.ResultMatchers.isSuccessful;
+import static org.junit.matchers.JUnitMatchers.containsString;
+import org.junit.Test;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.Theories;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+
+public class WithOnlyTestAnnotations {
+ @RunWith(Theories.class)
+ public static class HonorExpectedException {
+ @Test(expected= NullPointerException.class)
+ public void shouldThrow() {
+
+ }
+ }
+
+ @Test
+ public void honorExpected() throws Exception {
+ assertThat(testResult(HonorExpectedException.class).failureCount(), is(1));
+ }
+
+ @RunWith(Theories.class)
+ public static class HonorExpectedExceptionPasses {
+ @Test(expected= NullPointerException.class)
+ public void shouldThrow() {
+ throw new NullPointerException();
+ }
+ }
+
+ @Test
+ public void honorExpectedPassing() throws Exception {
+ assertThat(testResult(HonorExpectedExceptionPasses.class), isSuccessful());
+ }
+
+ @RunWith(Theories.class)
+ public static class HonorTimeout {
+ @Test(timeout= 5)
+ public void shouldStop() {
+ while (true) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+
+ }
+ }
+ }
+ }
+
+ @Test
+ public void honorTimeout() throws Exception {
+ assertThat(testResult(HonorTimeout.class), failureCountIs(1));
+ }
+
+ @RunWith(Theories.class)
+ static public class ErrorWhenTestHasParametersDespiteTheories {
+ @DataPoint
+ public static int ZERO = 0;
+
+ @Test
+ public void testMethod(int i) {
+ }
+ }
+
+ @Test public void testErrorWhenTestHasParametersDespiteTheories() {
+ JUnitCore core = new JUnitCore();
+ Result result = core.run(ErrorWhenTestHasParametersDespiteTheories.class);
+ assertEquals(1, result.getFailureCount());
+ String message = result.getFailures().get(0).getMessage();
+ assertThat(message, containsString("should have no parameters"));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java
new file mode 100644
index 0000000..579fc7e
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java
@@ -0,0 +1,177 @@
+package org.junit.tests.experimental.theories.runner;
+
+import static org.junit.Assert.*;
+import static org.junit.experimental.results.PrintableResult.*;
+import static org.junit.experimental.results.ResultMatchers.*;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.junit.experimental.results.PrintableResult;
+import org.junit.experimental.theories.DataPoint;
+import org.junit.experimental.theories.DataPoints;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+
+public class WithUnresolvedGenericTypeVariablesOnTheoryParms {
+ @Test
+ public void whereTypeVariableIsOnTheTheory() {
+ PrintableResult result= testResult(TypeVariableOnTheoryOnly.class);
+ assertThat(result, isSuccessful());
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnTheoryOnly {
+ @DataPoint
+ public static List<String> strings = Arrays.asList("foo", "bar");
+
+ @Theory
+ public <T> void forItems(Collection<?> items) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnTheoryParm() {
+ PrintableResult result= testResult(TypeVariableOnTheoryParm.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable T"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnTheoryParm {
+ @DataPoint
+ public static String string = "foo";
+
+ @Theory
+ public <T> void forItem(T item) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnParameterizedTheoryParm() {
+ PrintableResult result= testResult(TypeVariableOnParameterizedTheoryParm.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable T"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnParameterizedTheoryParm {
+ @DataPoint
+ public static List<String> strings = Arrays.asList("foo", "bar");
+
+ @Theory
+ public <T> void forItems(Collection<T> items) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnWildcardUpperBoundOnTheoryParm() {
+ PrintableResult result= testResult(TypeVariableOnWildcardUpperBoundOnTheoryParm.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable U"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnWildcardUpperBoundOnTheoryParm {
+ @DataPoint
+ public static List<String> strings = Arrays.asList("foo", "bar");
+
+ @Theory
+ public <U> void forItems(Collection<? extends U> items) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnWildcardLowerBoundOnTheoryParm() {
+ PrintableResult result= testResult(TypeVariableOnWildcardLowerBoundOnTheoryParm.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable V"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnWildcardLowerBoundOnTheoryParm {
+ @DataPoint
+ public static List<String> strings = Arrays.asList("foo", "bar");
+
+ @Theory
+ public <V> void forItems(Collection<? super V> items) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnArrayTypeOnTheoryParm() {
+ PrintableResult result= testResult(TypeVariableOnArrayTypeOnTheoryParm.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable T"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnArrayTypeOnTheoryParm {
+ @DataPoints
+ public static String[][] items() {
+ return new String[][] { new String[] { "foo" }, new String[] { "bar" } };
+ }
+
+ @Theory
+ public <T> void forItems(T[] items) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnComponentOfArrayTypeOnTheoryParm() {
+ PrintableResult result= testResult(TypeVariableOnComponentOfArrayTypeOnTheoryParm.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable U"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnComponentOfArrayTypeOnTheoryParm {
+ @DataPoints
+ public static List<?>[][] items() {
+ return new List<?>[][] {
+ new List<?>[] { Arrays.asList("foo") },
+ new List<?>[] { Arrays.asList("bar") }
+ };
+ }
+
+ @Theory
+ public <U> void forItems(Collection<U>[] items) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariableIsOnTheoryClass() {
+ PrintableResult result= testResult(TypeVariableOnTheoryClass.class);
+ assertThat(result, hasSingleFailureContaining("unresolved type variable T"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariableOnTheoryClass<T> {
+ @DataPoint
+ public static String item = "bar";
+
+ @Theory
+ public void forItem(T item) {
+ }
+ }
+
+ @Test
+ public void whereTypeVariablesAbound() {
+ PrintableResult result= testResult(TypeVariablesAbound.class);
+ assertThat(result, failureCountIs(7));
+ assertThat(result, hasFailureContaining("unresolved type variable A"));
+ assertThat(result, hasFailureContaining("unresolved type variable B"));
+ assertThat(result, hasFailureContaining("unresolved type variable C"));
+ assertThat(result, hasFailureContaining("unresolved type variable D"));
+ assertThat(result, hasFailureContaining("unresolved type variable E"));
+ assertThat(result, hasFailureContaining("unresolved type variable F"));
+ assertThat(result, hasFailureContaining("unresolved type variable G"));
+ }
+
+ @RunWith(Theories.class)
+ public static class TypeVariablesAbound<A, B extends A, C extends Collection<B>> {
+ @Theory
+ public <D, E extends D, F, G> void forItem(A first, Collection<B> second,
+ Map<C, ? extends D> third, List<? super E> fourth, F[] fifth,
+ Collection<G>[] sixth) {
+ }
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/internal/runners/statements/FailOnTimeoutTest.java b/junit4/src/test/java/org/junit/tests/internal/runners/statements/FailOnTimeoutTest.java
new file mode 100644
index 0000000..152d641
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/internal/runners/statements/FailOnTimeoutTest.java
@@ -0,0 +1,110 @@
+package org.junit.tests.internal.runners.statements;
+
+import static java.lang.Thread.sleep;
+import static org.junit.Assert.assertTrue;
+import static org.hamcrest.core.Is.is;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.internal.runners.statements.FailOnTimeout;
+import org.junit.rules.ExpectedException;
+import org.junit.runners.model.Statement;
+
+/**
+ * @author Asaf Ary, Stefan Birkner
+ */
+public class FailOnTimeoutTest {
+ private static final int TIMEOUT= 100;
+
+ @Rule
+ public final ExpectedException thrown= ExpectedException.none();
+
+ private final TestStatement statement= new TestStatement();
+
+ private final FailOnTimeout failOnTimeout= new FailOnTimeout(statement,
+ TIMEOUT);
+
+ @Test
+ public void throwExceptionWithNiceMessageOnTimeout() throws Throwable {
+ thrown.expectMessage("test timed out after 100 milliseconds");
+ evaluateWithWaitDuration(TIMEOUT + 50);
+ }
+
+ @Test
+ public void sendUpExceptionThrownByStatement() throws Throwable {
+ RuntimeException exception= new RuntimeException();
+ thrown.expect(is(exception));
+ evaluateWithException(exception);
+ }
+
+ @Test
+ public void throwExceptionIfTheSecondCallToEvaluateNeedsTooMuchTime()
+ throws Throwable {
+ thrown.expect(Exception.class);
+ evaluateWithWaitDuration(0);
+ evaluateWithWaitDuration(TIMEOUT + 50);
+ }
+
+ @Test
+ public void throwTimeoutExceptionOnSecondCallAlthoughFirstCallThrowsException()
+ throws Throwable {
+ thrown.expectMessage("test timed out after 100 milliseconds");
+ try {
+ evaluateWithException(new RuntimeException());
+ } catch (Throwable expected) {
+ }
+ evaluateWithWaitDuration(TIMEOUT + 50);
+ }
+
+ private void evaluateWithException(Exception exception) throws Throwable {
+ statement.nextException= exception;
+ statement.waitDuration= 0;
+ failOnTimeout.evaluate();
+ }
+
+ private void evaluateWithWaitDuration(int waitDuration) throws Throwable {
+ statement.nextException= null;
+ statement.waitDuration= waitDuration;
+ failOnTimeout.evaluate();
+ }
+
+ private static final class TestStatement extends Statement {
+ int waitDuration;
+
+ Exception nextException;
+
+ @Override
+ public void evaluate() throws Throwable {
+ sleep(waitDuration);
+ if (nextException != null)
+ throw nextException;
+ }
+ }
+
+ @Test
+ public void stopEndlessStatement() throws Throwable {
+ InfiniteLoopStatement infiniteLoop= new InfiniteLoopStatement();
+ FailOnTimeout infiniteLoopTimeout= new FailOnTimeout(infiniteLoop,
+ TIMEOUT);
+ try {
+ infiniteLoopTimeout.evaluate();
+ } catch (Exception timeoutException) {
+ sleep(20); // time to interrupt the thread
+ int firstCount= InfiniteLoopStatement.COUNT;
+ sleep(20); // time to increment the count
+ assertTrue("Thread has not been stopped.",
+ firstCount == InfiniteLoopStatement.COUNT);
+ }
+ }
+
+ private static final class InfiniteLoopStatement extends Statement {
+ private static int COUNT= 0;
+
+ @Override
+ public void evaluate() throws Throwable {
+ while (true) {
+ sleep(10); //sleep in order to enable interrupting thread
+ ++COUNT;
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java
new file mode 100644
index 0000000..d9076e3
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java
@@ -0,0 +1,81 @@
+package org.junit.tests.junit3compatibility;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.matchers.JUnitMatchers.containsString;
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.RunWith;
+import org.junit.runners.AllTests;
+
+public class AllTestsTest {
+
+ private static boolean run;
+
+ public static class OneTest extends TestCase {
+ public void testSomething() {
+ run= true;
+ }
+ }
+
+ @RunWith(AllTests.class)
+ public static class All {
+ static public junit.framework.Test suite() {
+ TestSuite suite= new TestSuite();
+ suite.addTestSuite(OneTest.class);
+ return suite;
+ }
+ }
+
+ @org.junit.Test public void ensureTestIsRun() {
+ JUnitCore runner= new JUnitCore();
+ run= false; // Have to explicitly set run here because the runner might independently run OneTest above
+ runner.run(All.class);
+ assertTrue(run);
+ }
+
+ @org.junit.Test public void correctTestCount() throws Throwable {
+ AllTests tests= new AllTests(All.class);
+ assertEquals(1, tests.testCount());
+ }
+
+ @org.junit.Test public void someUsefulDescription() throws Throwable {
+ AllTests tests= new AllTests(All.class);
+ assertThat(tests.getDescription().toString(), containsString("OneTest"));
+ }
+
+ public static class JUnit4Test {
+ @org.junit.Test public void testSomething() {
+ run= true;
+ }
+ }
+
+ @RunWith(AllTests.class)
+ public static class AllJUnit4 {
+ static public junit.framework.Test suite() {
+ TestSuite suite= new TestSuite();
+ suite.addTest(new JUnit4TestAdapter(JUnit4Test.class));
+ return suite;
+ }
+ }
+
+ @org.junit.Test public void correctTestCountAdapted() throws Throwable {
+ AllTests tests= new AllTests(AllJUnit4.class);
+ assertEquals(1, tests.testCount());
+ }
+
+ @RunWith(AllTests.class)
+ public static class BadSuiteMethod {
+ public static junit.framework.Test suite() {
+ throw new RuntimeException("can't construct");
+ }
+ }
+
+ @org.junit.Test(expected= RuntimeException.class)
+ public void exceptionThrownWhenSuiteIsBad() throws Throwable {
+ new AllTests(BadSuiteMethod.class);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java
new file mode 100644
index 0000000..91bc037
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java
@@ -0,0 +1,19 @@
+package org.junit.tests.junit3compatibility;
+
+import static org.junit.Assert.assertNull;
+import org.junit.Test;
+import org.junit.internal.builders.SuiteMethodBuilder;
+
+public class ClassRequestTest {
+ public static class PrivateSuiteMethod {
+ static junit.framework.Test suite() {
+ return null;
+ }
+ }
+
+ @Test
+ public void noSuiteMethodIfMethodPrivate() throws Throwable {
+ assertNull(new SuiteMethodBuilder()
+ .runnerForClass(PrivateSuiteMethod.class));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java
new file mode 100644
index 0000000..34a08a6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java
@@ -0,0 +1,89 @@
+package org.junit.tests.junit3compatibility;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestCase;
+import junit.framework.TestResult;
+import junit.framework.TestSuite;
+import junit.textui.ResultPrinter;
+import junit.textui.TestRunner;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ForwardCompatibilityPrintingTest extends TestCase {
+ static class TestResultPrinter extends ResultPrinter {
+ TestResultPrinter(PrintStream writer) {
+ super(writer);
+ }
+
+ /*
+ * Spoof printing time so the tests are deterministic
+ */
+ @Override
+ protected String elapsedTimeAsString(long runTime) {
+ return "0";
+ }
+ }
+
+ public void testError() {
+ ByteArrayOutputStream output= new ByteArrayOutputStream();
+ TestRunner runner= new TestRunner(new TestResultPrinter(
+ new PrintStream(output)));
+
+ String expected= expected(new String[] { ".E", "Time: 0",
+ "Errors here", "", "FAILURES!!!",
+ "Tests run: 1, Failures: 0, Errors: 1", "" });
+ ResultPrinter printer= new TestResultPrinter(new PrintStream(output)) {
+ @Override
+ public void printErrors(TestResult result) {
+ getWriter().println("Errors here");
+ }
+ };
+ runner.setPrinter(printer);
+ TestSuite suite= new TestSuite();
+ suite.addTest(new TestCase() {
+ @Override
+ public void runTest() throws Exception {
+ throw new Exception();
+ }
+ });
+ runner.doRun(suite);
+ assertEquals(expected, output.toString());
+ }
+
+ public static class ATest {
+ @Test public void error() {
+ Assert.fail();
+ }
+ }
+
+ public void testErrorAdapted() {
+ ByteArrayOutputStream output= new ByteArrayOutputStream();
+ TestRunner runner= new TestRunner(new TestResultPrinter(
+ new PrintStream(output)));
+
+ String expected= expected(new String[] { ".E", "Time: 0",
+ "Errors here", "", "FAILURES!!!",
+ "Tests run: 1, Failures: 0, Errors: 1", "" });
+ ResultPrinter printer= new TestResultPrinter(new PrintStream(output)) {
+ @Override
+ public void printErrors(TestResult result) {
+ getWriter().println("Errors here");
+ }
+ };
+ runner.setPrinter(printer);
+ runner.doRun(new JUnit4TestAdapter(ATest.class));
+ assertEquals(expected, output.toString());
+ }
+
+ private String expected(String[] lines) {
+ OutputStream expected= new ByteArrayOutputStream();
+ PrintStream expectedWriter= new PrintStream(expected);
+ for (int i= 0; i < lines.length; i++)
+ expectedWriter.println(lines[i]);
+ return expected.toString();
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java
new file mode 100644
index 0000000..2c73089
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java
@@ -0,0 +1,222 @@
+package org.junit.tests.junit3compatibility;
+
+import junit.framework.AssertionFailedError;
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestCase;
+import junit.framework.TestFailure;
+import junit.framework.TestListener;
+import junit.framework.TestResult;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.notification.RunNotifier;
+
+public class ForwardCompatibilityTest extends TestCase {
+ static String fLog;
+
+ static public class NewTest {
+ @Before public void before() {
+ fLog+= "before ";
+ }
+ @After public void after() {
+ fLog+= "after ";
+ }
+ @Test public void test() {
+ fLog+= "test ";
+ }
+ }
+
+ public void testCompatibility() {
+ fLog= "";
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(NewTest.class);
+ adapter.run(result);
+ assertEquals("before test after ", fLog);
+ }
+
+ public void testToString() {
+ JUnit4TestAdapter adapter= new JUnit4TestAdapter(NewTest.class);
+ junit.framework.Test test= adapter.getTests().get(0);
+ assertEquals(String.format("test(%s)", NewTest.class.getName()), test.toString());
+ }
+
+ public void testUseGlobalCache() {
+ JUnit4TestAdapter adapter1= new JUnit4TestAdapter(NewTest.class);
+ JUnit4TestAdapter adapter2= new JUnit4TestAdapter(NewTest.class);
+ assertSame(adapter1.getTests().get(0), adapter2.getTests().get(0));
+ }
+
+ static Exception exception= new Exception();
+
+ public static class ErrorTest {
+ @Test public void error() throws Exception {
+ throw exception;
+ }
+ }
+ public void testException() {
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(ErrorTest.class);
+ adapter.run(result);
+ assertEquals(exception, result.errors().nextElement().thrownException());
+ }
+
+ public void testNotifyResult() {
+ JUnit4TestAdapter adapter= new JUnit4TestAdapter(ErrorTest.class);
+ TestResult result= new TestResult();
+ final StringBuffer log= new StringBuffer();
+ result.addListener(new TestListener() {
+
+ public void startTest(junit.framework.Test test) {
+ log.append(" start " + test);
+ }
+
+ public void endTest(junit.framework.Test test) {
+ log.append(" end " + test);
+ }
+
+ public void addFailure(junit.framework.Test test, AssertionFailedError t) {
+ log.append(" failure " + test);
+ }
+
+ public void addError(junit.framework.Test test, Throwable t) {
+ log.append(" error " + test);
+ }
+ });
+ adapter.run(result);
+ String testName= String.format("error(%s)", ErrorTest.class.getName());
+ assertEquals(String.format(" start %s error %s end %s", testName, testName, testName), log.toString());
+ }
+
+
+ public static class NoExceptionTest {
+ @Test(expected=Exception.class) public void succeed() throws Exception {
+ }
+ }
+ public void testNoException() {
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(NoExceptionTest.class);
+ adapter.run(result);
+ assertFalse(result.wasSuccessful());
+ }
+
+ public static class ExpectedTest {
+ @Test(expected= Exception.class) public void expected() throws Exception {
+ throw new Exception();
+ }
+ }
+ public void testExpected() {
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(ExpectedTest.class);
+ adapter.run(result);
+ assertTrue(result.wasSuccessful());
+ }
+
+ public static class UnExpectedExceptionTest {
+ @Test(expected= Exception.class) public void expected() throws Exception {
+ throw new Error();
+ }
+ }
+
+ static String log;
+ public static class BeforeClassTest {
+ @BeforeClass public static void beforeClass() {
+ log+= "before class ";
+ }
+ @Before public void before() {
+ log+= "before ";
+ }
+ @Test public void one() {
+ log+= "test ";
+ }
+ @Test public void two() {
+ log+= "test ";
+ }
+ @After public void after() {
+ log+= "after ";
+ }
+ @AfterClass public static void afterClass() {
+ log+= "after class ";
+ }
+ }
+
+ public void testBeforeAndAfterClass() {
+ log= "";
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(BeforeClassTest.class);
+ adapter.run(result);
+ assertEquals("before class before test after before test after after class ", log);
+ }
+
+ public static class ExceptionInBeforeTest {
+ @Before public void error() {
+ throw new Error();
+ }
+ @Test public void nothing() {
+ }
+ }
+
+ public void testExceptionInBefore() {
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(ExceptionInBeforeTest.class);
+ adapter.run(result);
+ assertEquals(1, result.errorCount());
+ }
+
+ public static class InvalidMethodTest {
+ @BeforeClass public void shouldBeStatic() {}
+ @Test public void aTest() {}
+ }
+
+ public void testInvalidMethod() {
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(InvalidMethodTest.class);
+ adapter.run(result);
+ assertEquals(1, result.errorCount());
+ TestFailure failure= result.errors().nextElement();
+ assertTrue(failure.exceptionMessage().contains("Method shouldBeStatic() should be static"));
+ }
+
+ private static boolean wasRun= false;
+
+ public static class MarkerRunner extends Runner {
+ public MarkerRunner(Class<?> klass) {
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+ wasRun= true;
+ }
+
+ @Override
+ public int testCount() {
+ return 0;
+ }
+
+ @Override
+ public Description getDescription() {
+ return Description.EMPTY;
+ }
+ }
+
+ @RunWith(MarkerRunner.class)
+ public static class NoTests {
+ }
+
+ public void testRunWithClass() {
+ wasRun= false;
+ TestResult result= new TestResult();
+ junit.framework.Test adapter= new JUnit4TestAdapter(NoTests.class);
+ adapter.run(result);
+ assertTrue(wasRun);
+ }
+
+ public void testToStringSuite() {
+ junit.framework.Test adapter= new JUnit4TestAdapter(NoTests.class);
+ assertEquals(NoTests.class.getName(), adapter.toString());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java
new file mode 100644
index 0000000..6c87a8b
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java
@@ -0,0 +1,100 @@
+package org.junit.tests.junit3compatibility;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import junit.framework.AssertionFailedError;
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestListener;
+import junit.framework.TestResult;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.BlockJUnit4ClassRunner;
+
+public class InitializationErrorForwardCompatibilityTest {
+ public static class CantInitialize extends Runner {
+ private static final String UNIQUE_ERROR_MESSAGE= "Unique error message";
+
+ public CantInitialize(Class<?> klass) throws Exception {
+ throw new Exception(UNIQUE_ERROR_MESSAGE);
+ }
+
+ @Override
+ public Description getDescription() {
+ return Description.EMPTY;
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+ }
+ }
+
+ @RunWith(CantInitialize.class)
+ public static class CantInitializeTests {
+ }
+
+ private JUnit4TestAdapter fAdapter;
+
+ @Before public void createAdapter() {
+ fAdapter= new JUnit4TestAdapter(
+ CantInitializeTests.class);
+ }
+
+ @Test
+ public void initializationErrorsShowUpAsWarnings() {
+ assertEquals(1, fAdapter.getTests().size());
+ }
+
+ @Test
+ public void initializationErrorsAreThrownAtRuntime() {
+ TestResult result= new TestResult();
+ fAdapter.run(result);
+ assertEquals(1, result.errorCount());
+ assertEquals(CantInitialize.UNIQUE_ERROR_MESSAGE, result.errors()
+ .nextElement().exceptionMessage());
+ }
+
+ private final class ErrorRememberingListener implements TestListener {
+ private junit.framework.Test fError;
+
+ public void addError(junit.framework.Test test, Throwable t) {
+ fError= test;
+ }
+
+ public void addFailure(junit.framework.Test test,
+ AssertionFailedError t) {
+ }
+
+ public void endTest(junit.framework.Test test) {
+ }
+
+ public void startTest(junit.framework.Test test) {
+ }
+
+ public junit.framework.Test getError() {
+ return fError;
+ }
+ }
+
+ @Test
+ public void generatedErrorTestsMatchUp() {
+ junit.framework.Test shouldFail= fAdapter.getTests().get(0);
+ TestResult result= new TestResult();
+ ErrorRememberingListener listener= new ErrorRememberingListener();
+ result.addListener(listener);
+ fAdapter.run(result);
+ assertNotNull(listener.getError());
+ assertTrue(shouldFail == listener.getError());
+ }
+
+ public static class InitializesWithError extends BlockJUnit4ClassRunner {
+ public InitializesWithError(Class<?> klass) throws Exception {
+ super(klass);
+ throw new Exception();
+ }
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java
new file mode 100644
index 0000000..52fbd2c
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java
@@ -0,0 +1,79 @@
+package org.junit.tests.junit3compatibility;
+
+import static org.junit.Assert.assertEquals;
+import junit.extensions.TestDecorator;
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.internal.runners.JUnit38ClassRunner;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+
+public class JUnit38ClassRunnerTest {
+ public static class MyTest extends TestCase {
+ public void testA() {
+
+ }
+ }
+
+ @Test public void plansDecoratorCorrectly() {
+ JUnit38ClassRunner runner= new JUnit38ClassRunner(new TestDecorator(new TestSuite(MyTest.class)));
+ assertEquals(1, runner.testCount());
+ }
+
+ public static class AnnotatedTest {
+ @Test public void foo() {
+ Assert.fail();
+ }
+ }
+
+ @Test public void canUnadaptAnAdapter() {
+ JUnit38ClassRunner runner= new JUnit38ClassRunner(new JUnit4TestAdapter(AnnotatedTest.class));
+ Result result= new JUnitCore().run(runner);
+ Failure failure= result.getFailures().get(0);
+ assertEquals(Description.createTestDescription(AnnotatedTest.class, "foo"), failure.getDescription());
+ }
+
+ static int count;
+
+ static public class OneTest extends TestCase {
+ public void testOne() {
+ }
+ }
+
+ @Test public void testListener() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ RunListener listener= new RunListener() {
+ @Override
+ public void testStarted(Description description) {
+ assertEquals(Description.createTestDescription(OneTest.class, "testOne"),
+ description);
+ count++;
+ }
+ };
+
+ runner.addListener(listener);
+ count= 0;
+ Result result= runner.run(OneTest.class);
+ assertEquals(1, count);
+ assertEquals(1, result.getRunCount());
+ }
+
+ public static class ClassWithInvalidMethod extends TestCase {
+ @SuppressWarnings("unused")
+ private void testInvalid() {}
+ }
+
+ @Test public void invalidTestMethodReportedCorrectly() {
+ Result result= JUnitCore.runClasses(ClassWithInvalidMethod.class);
+ Failure failure= result.getFailures().get(0);
+ assertEquals("warning", failure.getDescription().getMethodName());
+ assertEquals("junit.framework.TestSuite$1", failure.getDescription().getClassName());
+ }
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java
new file mode 100644
index 0000000..8c68a1a
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java
@@ -0,0 +1,27 @@
+package org.junit.tests.junit3compatibility;
+
+import static org.junit.Assert.assertEquals;
+import junit.framework.AssertionFailedError;
+import junit.framework.TestCase;
+import junit.framework.TestListener;
+import org.junit.Test;
+import org.junit.internal.runners.JUnit38ClassRunner;
+import org.junit.runner.Result;
+import org.junit.runner.notification.RunListener;
+import org.junit.runner.notification.RunNotifier;
+
+public class OldTestClassAdaptingListenerTest {
+ @Test
+ public void addFailureDelegatesToNotifier() {
+ Result result= new Result();
+ RunListener listener= result.createListener();
+ RunNotifier notifier= new RunNotifier();
+ notifier.addFirstListener(listener);
+ TestCase testCase= new TestCase() {
+ };
+ TestListener adaptingListener= new JUnit38ClassRunner(testCase)
+ .createAdaptingListener(notifier);
+ adaptingListener.addFailure(testCase, new AssertionFailedError());
+ assertEquals(1, result.getFailureCount());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/OldTests.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/OldTests.java
new file mode 100644
index 0000000..ab154a6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/OldTests.java
@@ -0,0 +1,11 @@
+package org.junit.tests.junit3compatibility;
+import junit.framework.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.AllTests;
+
+@RunWith(AllTests.class)
+public class OldTests {
+ static public Test suite() {
+ return junit.tests.AllTests.suite();
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java b/junit4/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java
new file mode 100644
index 0000000..c4890d0
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java
@@ -0,0 +1,123 @@
+package org.junit.tests.junit3compatibility;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+
+public class SuiteMethodTest {
+ public static boolean wasRun;
+
+ static public class OldTest extends TestCase {
+ public OldTest(String name) {
+ super(name);
+ }
+
+ public static junit.framework.Test suite() {
+ TestSuite result= new TestSuite();
+ result.addTest(new OldTest("notObviouslyATest"));
+ return result;
+ }
+
+ public void notObviouslyATest() {
+ wasRun= true;
+ }
+ }
+
+ @Test public void makeSureSuiteIsCalled() {
+ wasRun= false;
+ JUnitCore.runClasses(OldTest.class);
+ assertTrue(wasRun);
+ }
+
+ static public class NewTest {
+ @Test public void sample() {
+ wasRun= true;
+ }
+
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(NewTest.class);
+ }
+ }
+
+ @Test public void makeSureSuiteWorksWithJUnit4Classes() {
+ wasRun= false;
+ JUnitCore.runClasses(NewTest.class);
+ assertTrue(wasRun);
+ }
+
+
+ public static class CompatibilityTest {
+ @Ignore @Test
+ public void ignored() {
+ }
+
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(CompatibilityTest.class);
+ }
+ }
+
+ // when executing as JUnit 3, ignored tests are stripped out before execution
+ @Test
+ public void descriptionAndRunNotificationsAreConsistent() {
+ Result result= JUnitCore.runClasses(CompatibilityTest.class);
+ assertEquals(0, result.getIgnoreCount());
+
+ Description description= Request.aClass(CompatibilityTest.class).getRunner().getDescription();
+ assertEquals(0, description.getChildren().size());
+ }
+
+ static public class NewTestSuiteFails {
+ @Test public void sample() {
+ wasRun= true;
+ }
+
+ public static junit.framework.Test suite() {
+ fail("called with JUnit 4 runner");
+ return null;
+ }
+ }
+
+ @Test public void suiteIsUsedWithJUnit4Classes() {
+ wasRun= false;
+ Result result= JUnitCore.runClasses(NewTestSuiteFails.class);
+ assertEquals(1, result.getFailureCount());
+ assertFalse(wasRun);
+ }
+
+ static public class NewTestSuiteNotUsed {
+ private static boolean wasIgnoredRun;
+
+ @Test public void sample() {
+ wasRun= true;
+ }
+
+ @Ignore @Test public void ignore() {
+ wasIgnoredRun= true;
+ }
+
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(NewTestSuiteNotUsed.class);
+ }
+ }
+
+ @Test public void makeSureSuiteNotUsedWithJUnit4Classes2() {
+ wasRun= false;
+ NewTestSuiteNotUsed.wasIgnoredRun= false;
+ Result res= JUnitCore.runClasses(NewTestSuiteNotUsed.class);
+ assertTrue(wasRun);
+ assertFalse(NewTestSuiteNotUsed.wasIgnoredRun);
+ assertEquals(0, res.getFailureCount());
+ assertEquals(1, res.getRunCount());
+ assertEquals(0, res.getIgnoreCount());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/listening/ListenerTest.java b/junit4/src/test/java/org/junit/tests/listening/ListenerTest.java
new file mode 100644
index 0000000..964c4d4
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/listening/ListenerTest.java
@@ -0,0 +1,33 @@
+package org.junit.tests.listening;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.notification.RunListener;
+
+public class ListenerTest {
+ static private String log;
+ public static class OneTest {
+ @Test public void nothing() {
+ }
+ }
+ @Test public void notifyListenersInTheOrderInWhichTheyAreAdded() {
+ JUnitCore core= new JUnitCore();
+ log= "";
+ core.addListener(new RunListener() {
+ @Override
+ public void testRunStarted(Description description) throws Exception {
+ log+="first ";
+ }
+ });
+ core.addListener(new RunListener() {
+ @Override
+ public void testRunStarted(Description description) throws Exception {
+ log+="second ";
+ }
+ });
+ core.run(OneTest.class);
+ assertEquals("first second ", log);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/listening/RunnerTest.java b/junit4/src/test/java/org/junit/tests/listening/RunnerTest.java
new file mode 100644
index 0000000..a07848d
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/listening/RunnerTest.java
@@ -0,0 +1,69 @@
+package org.junit.tests.listening;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import junit.framework.TestCase;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.notification.RunListener;
+
+public class RunnerTest {
+
+ private boolean wasRun;
+
+ public class MyListener extends RunListener {
+
+ int testCount;
+
+ @Override
+ public void testRunStarted(Description description) {
+ this.testCount= description.testCount();
+ }
+ }
+
+ public static class Example {
+ @Test public void empty() {
+ }
+ }
+
+ @Test public void newTestCount() {
+ JUnitCore runner= new JUnitCore();
+ MyListener listener= new MyListener();
+ runner.addListener(listener);
+ runner.run(Example.class);
+ assertEquals(1, listener.testCount);
+ }
+
+ public static class ExampleTest extends TestCase {
+ public void testEmpty() {
+ }
+ }
+
+ @Test public void oldTestCount() {
+ JUnitCore runner= new JUnitCore();
+ MyListener listener= new MyListener();
+ runner.addListener(listener);
+ runner.run(ExampleTest.class);
+ assertEquals(1, listener.testCount);
+ }
+
+ public static class NewExample {
+ @Test public void empty() {
+ }
+ }
+
+ @Test public void testFinished() {
+ JUnitCore runner= new JUnitCore();
+ wasRun= false;
+ RunListener listener= new MyListener() {
+ @Override
+ public void testFinished(Description description) {
+ wasRun= true;
+ }
+ };
+ runner.addListener(listener);
+ runner.run(NewExample.class);
+ assertTrue(wasRun);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/listening/TestListenerTest.java b/junit4/src/test/java/org/junit/tests/listening/TestListenerTest.java
new file mode 100644
index 0000000..35c0c75
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/listening/TestListenerTest.java
@@ -0,0 +1,63 @@
+package org.junit.tests.listening;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+
+public class TestListenerTest {
+
+ int count;
+
+ class ErrorListener extends RunListener {
+ @Override
+ public void testRunStarted(Description description) throws Exception {
+ throw new Error();
+ }
+ }
+
+ public static class OneTest {
+ @Test public void nothing() {}
+ }
+
+ @Test(expected=Error.class) public void failingListener() {
+ JUnitCore runner= new JUnitCore();
+ runner.addListener(new ErrorListener());
+ runner.run(OneTest.class);
+ }
+
+ class ExceptionListener extends ErrorListener {
+ @Override
+ public void testRunStarted(Description description) throws Exception {
+ count++;
+ throw new Exception();
+ }
+ }
+
+ @Test public void removeFailingListeners() {
+ JUnitCore core= new JUnitCore();
+ core.addListener(new ExceptionListener());
+
+ count= 0;
+ Result result= core.run(OneTest.class);
+ assertEquals(1, count);
+ assertEquals(1, result.getFailureCount());
+ Failure testFailure= result.getFailures().get(0);
+ assertEquals(Description.TEST_MECHANISM, testFailure.getDescription());
+
+ count= 0;
+ core.run(OneTest.class);
+ assertEquals(0, count); // Doesn't change because listener was removed
+ }
+
+ @Test public void freshResultEachTime() {
+ JUnitCore core= new JUnitCore();
+ Result first= core.run(OneTest.class);
+ Result second= core.run(OneTest.class);
+ assertNotSame(first, second);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/listening/TextListenerTest.java b/junit4/src/test/java/org/junit/tests/listening/TextListenerTest.java
new file mode 100644
index 0000000..b9684a6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/listening/TextListenerTest.java
@@ -0,0 +1,65 @@
+package org.junit.tests.listening;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+import junit.framework.TestCase;
+import org.junit.Test;
+import org.junit.internal.TextListener;
+import org.junit.runner.JUnitCore;
+import org.junit.tests.TestSystem;
+
+public class TextListenerTest extends TestCase {
+
+ private JUnitCore runner;
+ private OutputStream results;
+ private TextListener listener;
+
+ @Override
+ public void setUp() {
+ runner= new JUnitCore();
+ TestSystem system= new TestSystem();
+ results= system.outContents();
+ listener= new TextListener(system);
+ runner.addListener(listener);
+ }
+
+ public static class OneTest {
+ @Test public void one() {}
+ }
+
+ public void testSuccess() throws Exception {
+ runner.run(OneTest.class);
+ assertTrue(results.toString().startsWith(convert(".\nTime: ")));
+ assertTrue(results.toString().endsWith(convert("\n\nOK (1 test)\n\n")));
+ }
+
+ public static class ErrorTest {
+ @Test public void error() throws Exception {throw new Exception();}
+ }
+
+ public void testError() throws Exception {
+ runner.run(ErrorTest.class);
+ assertTrue(results.toString().startsWith(convert(".E\nTime: ")));
+ assertTrue(results.toString().indexOf(convert("\nThere was 1 failure:\n1) error(org.junit.tests.listening.TextListenerTest$ErrorTest)\njava.lang.Exception")) != -1);
+ }
+
+ public static class Slow {
+ @Test public void pause() throws InterruptedException {
+ Thread.sleep(1000);
+ }
+ }
+
+ public void testTime() {
+ runner.run(Slow.class);
+ assertFalse(results.toString().contains("Time: 0"));
+ }
+
+ private String convert(String string) {
+ OutputStream resultsStream= new ByteArrayOutputStream();
+ PrintStream writer= new PrintStream(resultsStream);
+ writer.println();
+ return string.replace("\n", resultsStream.toString());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/listening/UserStopTest.java b/junit4/src/test/java/org/junit/tests/listening/UserStopTest.java
new file mode 100644
index 0000000..822e203
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/listening/UserStopTest.java
@@ -0,0 +1,28 @@
+package org.junit.tests.listening;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.Request;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runner.notification.StoppedByUserException;
+
+public class UserStopTest {
+ private RunNotifier fNotifier;
+
+ @Before public void createNotifier() {
+ fNotifier= new RunNotifier();
+ fNotifier.pleaseStop();
+ }
+
+ @Test(expected=StoppedByUserException.class) public void userStop() {
+ fNotifier.fireTestStarted(null);
+ }
+
+ public static class OneTest {
+ @Test public void foo() {}
+ }
+
+ @Test(expected=StoppedByUserException.class) public void stopClassRunner() throws Exception {
+ Request.aClass(OneTest.class).getRunner().run(fNotifier);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/manipulation/FilterTest.java b/junit4/src/test/java/org/junit/tests/manipulation/FilterTest.java
new file mode 100644
index 0000000..242e990
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/manipulation/FilterTest.java
@@ -0,0 +1,49 @@
+package org.junit.tests.manipulation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.manipulation.Filter;
+
+public class FilterTest {
+ public static class NamedFilter extends Filter {
+ private final String fName;
+
+ public NamedFilter(String name) {
+ fName= name;
+ }
+
+ @Override
+ public boolean shouldRun(Description description) {
+ return false;
+ }
+
+ @Override
+ public String describe() {
+ return fName;
+ }
+ }
+
+ @Test
+ public void intersectionText() {
+ NamedFilter a= new NamedFilter("a");
+ NamedFilter b= new NamedFilter("b");
+ assertEquals("a and b", a.intersect(b).describe());
+ assertEquals("b and a", b.intersect(a).describe());
+ }
+
+ @Test
+ public void intersectSelf() {
+ NamedFilter a= new NamedFilter("a");
+ assertSame(a, a.intersect(a));
+ }
+
+ @Test
+ public void intersectAll() {
+ NamedFilter a= new NamedFilter("a");
+ assertSame(a, a.intersect(Filter.ALL));
+ assertSame(a, Filter.ALL.intersect(a));
+ assertSame(Filter.ALL, Filter.ALL.intersect(Filter.ALL));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/manipulation/FilterableTest.java b/junit4/src/test/java/org/junit/tests/manipulation/FilterableTest.java
new file mode 100644
index 0000000..3d35169
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/manipulation/FilterableTest.java
@@ -0,0 +1,62 @@
+package org.junit.tests.manipulation;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+public class FilterableTest {
+ public static class FilteredRunner extends Parameterized {
+ public FilteredRunner(Class<?> klass) throws Throwable {
+ super(klass);
+ filter(new Filter() {
+
+ @Override
+ public boolean shouldRun(Description description) {
+ return !description.getDisplayName().contains("skip");
+ }
+
+ @Override
+ public String describe() {
+ return "skip methods containing the word 'skip'";
+ }
+ });
+ }
+ }
+
+ @RunWith(FilteredRunner.class)
+ public static class FilteredTest {
+ @Parameters
+ public static List<Object[]> parameters() {
+ return Arrays.asList(new Object[] { 3 }, new Object[] { 4 });
+ }
+
+ public FilteredTest(int x) {
+ }
+
+ @Test
+ public void skipThis() {
+ Assert.fail();
+ }
+
+ @Test
+ public void runThis() {
+ }
+ }
+
+ @Test
+ public void testFilterInRunnerConstructor() {
+ Result result= JUnitCore.runClasses(FilteredTest.class);
+ assertTrue(result.wasSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java b/junit4/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java
new file mode 100644
index 0000000..393a844
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java
@@ -0,0 +1,168 @@
+package org.junit.tests.manipulation;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.JUnit4TestAdapter;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.Filterable;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Suite;
+import org.junit.runners.Parameterized.Parameters;
+import org.junit.runners.Suite.SuiteClasses;
+
+public class SingleMethodTest {
+ public static int count;
+
+ static public class OneTimeSetup {
+ @BeforeClass public static void once() {
+ count++;
+ }
+
+ @Test public void one() {
+ }
+
+ @Test public void two() {
+ }
+ }
+
+ @Test public void oneTimeSetup() throws Exception {
+ count = 0;
+ Runner runner = Request.method(OneTimeSetup.class, "one").getRunner();
+ Result result = new JUnitCore().run(runner);
+
+ assertEquals(1, count);
+ assertEquals(1, result.getRunCount());
+ }
+
+ @RunWith(Parameterized.class)
+ static public class ParameterizedOneTimeSetup {
+ @Parameters
+ public static List<Object[]> params() {
+ return Arrays.asList(new Object[] {1}, new Object[] {2});
+ }
+
+ public ParameterizedOneTimeSetup(int x) {
+ }
+
+ @Test public void one() {
+ }
+ }
+
+ @Test public void parameterizedFilterToSingleMethod() throws Exception {
+ count = 0;
+ Runner runner = Request.method(ParameterizedOneTimeSetup.class,
+ "one[0]").getRunner();
+ Result result = new JUnitCore().run(runner);
+
+ assertEquals(1, result.getRunCount());
+ }
+
+ @RunWith(Parameterized.class)
+ static public class ParameterizedOneTimeBeforeClass {
+ @Parameters
+ public static List<Object[]> params() {
+ return Arrays.asList(new Object[] {1}, new Object[] {2});
+ }
+
+ public ParameterizedOneTimeBeforeClass(int x) {
+ }
+
+ @BeforeClass public static void once() {
+ count++;
+ }
+
+ @Test public void one() {
+ }
+ }
+
+
+ @Test public void parameterizedBeforeClass() throws Exception {
+ count = 0;
+ JUnitCore.runClasses(ParameterizedOneTimeBeforeClass.class);
+ assertEquals(1, count);
+ }
+
+ @Test public void filteringAffectsPlan() throws Exception {
+ Runner runner = Request.method(OneTimeSetup.class, "one").getRunner();
+ assertEquals(1, runner.testCount());
+ }
+
+ @Test public void nonexistentMethodCreatesFailure() throws Exception {
+ assertEquals(1, new JUnitCore().run(
+ Request.method(OneTimeSetup.class, "thisMethodDontExist"))
+ .getFailureCount());
+ }
+
+ @Test(expected = NoTestsRemainException.class)
+ public void filteringAwayEverythingThrowsException() throws NoTestsRemainException {
+ Filterable runner = (Filterable) Request.aClass(OneTimeSetup.class).getRunner();
+ runner.filter(new Filter() {
+ @Override
+ public boolean shouldRun(Description description) {
+ return false;
+ }
+
+ @Override
+ public String describe() {
+ return null;
+ }
+ });
+ }
+
+ public static class TestOne {
+ @Test public void a() {
+ }
+
+ @Test public void b() {
+ }
+ }
+
+ public static class TestTwo {
+ @Test public void a() {
+ }
+
+ @Test public void b() {
+ }
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses( { TestOne.class, TestTwo.class })
+ public static class OneTwoSuite {
+ }
+
+ @Test public void eliminateUnnecessaryTreeBranches() throws Exception {
+ Runner runner = Request.aClass(OneTwoSuite.class).filterWith(
+ Description.createTestDescription(TestOne.class, "a"))
+ .getRunner();
+ Description description = runner.getDescription();
+ assertEquals(1, description.getChildren().size());
+ }
+
+ public static class HasSuiteMethod {
+ @Test public void a() {}
+ @Test public void b() {}
+
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(HasSuiteMethod.class);
+ }
+ }
+
+ @Test public void classesWithSuiteMethodsAreFiltered() {
+ int testCount= Request.method(HasSuiteMethod.class, "a").getRunner().getDescription().testCount();
+ assertThat(testCount, is(1));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/manipulation/SortableTest.java b/junit4/src/test/java/org/junit/tests/manipulation/SortableTest.java
new file mode 100644
index 0000000..eac7aa8
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/manipulation/SortableTest.java
@@ -0,0 +1,149 @@
+package org.junit.tests.manipulation;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Comparator;
+
+import junit.framework.JUnit4TestAdapter;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.runners.Enclosed;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.notification.RunNotifier;
+
+@RunWith(Enclosed.class)
+public class SortableTest {
+ private static Comparator<Description> forward() {
+ return new Comparator<Description>() {
+ public int compare(Description o1, Description o2) {
+ return o1.getDisplayName().compareTo(o2.getDisplayName());
+ }
+ };
+ }
+
+ private static Comparator<Description> backward() {
+ return new Comparator<Description>() {
+ public int compare(Description o1, Description o2) {
+ return o2.getDisplayName().compareTo(o1.getDisplayName());
+ }
+ };
+ }
+
+ public static class TestClassRunnerIsSortable {
+ private static String log= "";
+
+ public static class SortMe {
+ @Test public void a() { log+= "a"; }
+ @Test public void b() { log+= "b"; }
+ @Test public void c() { log+= "c"; }
+ }
+
+ @Before public void resetLog() {
+ log= "";
+ }
+
+ @Test public void sortingForwardWorksOnTestClassRunner() {
+ Request forward= Request.aClass(SortMe.class).sortWith(forward());
+
+ new JUnitCore().run(forward);
+ assertEquals("abc", log);
+ }
+
+ @Test public void sortingBackwardWorksOnTestClassRunner() {
+ Request backward= Request.aClass(SortMe.class).sortWith(backward());
+
+ new JUnitCore().run(backward);
+ assertEquals("cba", log);
+ }
+
+ @RunWith(Enclosed.class)
+ public static class Enclosing {
+ public static class A {
+ @Test public void a() { log+= "Aa"; }
+ @Test public void b() { log+= "Ab"; }
+ @Test public void c() { log+= "Ac"; }
+ }
+ public static class B {
+ @Test public void a() { log+= "Ba"; }
+ @Test public void b() { log+= "Bb"; }
+ @Test public void c() { log+= "Bc"; }
+ }
+ }
+
+ @Test public void sortingForwardWorksOnSuite() {
+ Request forward= Request.aClass(Enclosing.class).sortWith(forward());
+
+ new JUnitCore().run(forward);
+ assertEquals("AaAbAcBaBbBc", log);
+ }
+
+ @Test public void sortingBackwardWorksOnSuite() {
+ Request backward= Request.aClass(Enclosing.class).sortWith(backward());
+
+ new JUnitCore().run(backward);
+ assertEquals("BcBbBaAcAbAa", log);
+ }
+ }
+
+ public static class TestClassRunnerIsSortableWithSuiteMethod {
+ private static String log= "";
+
+ public static class SortMe {
+ @Test public void a() { log+= "a"; }
+ @Test public void b() { log+= "b"; }
+ @Test public void c() { log+= "c"; }
+
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(SortMe.class);
+ }
+ }
+
+ @Before public void resetLog() {
+ log= "";
+ }
+
+ @Test public void sortingForwardWorksOnTestClassRunner() {
+ Request forward= Request.aClass(SortMe.class).sortWith(forward());
+
+ new JUnitCore().run(forward);
+ assertEquals("abc", log);
+ }
+
+ @Test public void sortingBackwardWorksOnTestClassRunner() {
+ Request backward= Request.aClass(SortMe.class).sortWith(backward());
+
+ new JUnitCore().run(backward);
+ assertEquals("cba", log);
+ }
+ }
+
+ public static class UnsortableRunnersAreHandledWithoutCrashing {
+ public static class UnsortableRunner extends Runner {
+ public UnsortableRunner(Class<?> klass) {
+ }
+
+ @Override
+ public Description getDescription() {
+ return Description.EMPTY;
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+ }
+ }
+
+ @RunWith(UnsortableRunner.class)
+ public static class Unsortable {
+ @Test public void a() {}
+ }
+
+ @Test public void unsortablesAreHandledWithoutCrashing() {
+ Request unsorted= Request.aClass(Unsortable.class).sortWith(forward());
+ new JUnitCore().run(unsorted);
+ }
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/package-info.java b/junit4/src/test/java/org/junit/tests/package-info.java
new file mode 100644
index 0000000..21d611c
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/package-info.java
@@ -0,0 +1,8 @@
+/**
+ * Tests the JUnit functionality.
+ *
+ * Corresponds to {@link junit.tests.AllTests} in Junit 3.x.
+ *
+ * @since 4.0
+ */
+package org.junit.tests; \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java b/junit4/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java
new file mode 100644
index 0000000..a19cd94
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java
@@ -0,0 +1,33 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.InitializationError;
+
+public class BlockJUnit4ClassRunnerTest {
+ public static class OuterClass {
+ public class Enclosed {
+ @Test
+ public void test() {
+ }
+ }
+ }
+
+ @Test
+ public void detectNonStaticEnclosedClass() throws Exception {
+ try {
+ new BlockJUnit4ClassRunner(OuterClass.Enclosed.class);
+ } catch (InitializationError e) {
+ List<Throwable> causes= e.getCauses();
+ assertEquals("Wrong number of causes.", 1, causes.size());
+ assertEquals(
+ "Wrong exception.",
+ "The inner class org.junit.tests.running.classes.BlockJUnit4ClassRunnerTest$OuterClass$Enclosed is not static.",
+ causes.get(0).getMessage());
+ }
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/EnclosedTest.java b/junit4/src/test/java/org/junit/tests/running/classes/EnclosedTest.java
new file mode 100644
index 0000000..8a6973a
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/EnclosedTest.java
@@ -0,0 +1,40 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.junit.experimental.runners.Enclosed;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+
+public class EnclosedTest {
+ @RunWith(Enclosed.class)
+ public static class Enclosing {
+ public static class A {
+ @Test public void a() {}
+ @Test public void b() {}
+ }
+ public static class B {
+ @Test public void a() {}
+ @Test public void b() {}
+ @Test public void c() {}
+ }
+ }
+
+ @Test public void enclosedRunnerPlansEnclosedClasses() throws Exception {
+ Runner runner= Request.aClass(Enclosing.class).getRunner();
+ assertEquals(5, runner.testCount());
+ }
+
+ @Test public void enclosedRunnerRunsEnclosedClasses() throws Exception {
+ Result result= JUnitCore.runClasses(Enclosing.class);
+ assertEquals(5, result.getRunCount());
+ }
+
+ @Test public void enclosedRunnerIsNamedForEnclosingClass() throws Exception {
+ assertEquals(Enclosing.class.getName(), Request.aClass(Enclosing.class)
+ .getRunner().getDescription().getDisplayName());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java b/junit4/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java
new file mode 100644
index 0000000..e193712
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java
@@ -0,0 +1,26 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+
+public class IgnoreClassTest {
+ @Ignore("For a good reason") public static class IgnoreMe {
+ @Test public void iFail() {
+ fail();
+ }
+
+ @Test public void iFailToo() {
+ fail();
+ }
+ }
+
+ @Test public void ignoreClass() {
+ Result result= JUnitCore.runClasses(IgnoreMe.class);
+ assertEquals(0, result.getFailureCount());
+ assertEquals(1, result.getIgnoreCount());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java b/junit4/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java
new file mode 100644
index 0000000..d48433f
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java
@@ -0,0 +1,216 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.matchers.JUnitMatchers.containsString;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+import org.junit.runners.model.InitializationError;
+
+public class ParameterizedTestTest {
+ @RunWith(Parameterized.class)
+ static public class FibonacciTest {
+ @Parameters
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
+ { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
+ }
+
+ private int fInput;
+
+ private int fExpected;
+
+ public FibonacciTest(int input, int expected) {
+ fInput= input;
+ fExpected= expected;
+ }
+
+ @Test
+ public void test() {
+ assertEquals(fExpected, fib(fInput));
+ }
+
+ private int fib(int x) {
+ return 0;
+ }
+ }
+
+ @Test
+ public void count() {
+ Result result= JUnitCore.runClasses(FibonacciTest.class);
+ assertEquals(7, result.getRunCount());
+ assertEquals(6, result.getFailureCount());
+ }
+
+ @Test
+ public void failuresNamedCorrectly() {
+ Result result= JUnitCore.runClasses(FibonacciTest.class);
+ assertEquals(String
+ .format("test[1](%s)", FibonacciTest.class.getName()), result
+ .getFailures().get(0).getTestHeader());
+ }
+
+ @Test
+ public void countBeforeRun() throws Exception {
+ Runner runner= Request.aClass(FibonacciTest.class).getRunner();
+ assertEquals(7, runner.testCount());
+ }
+
+ @Test
+ public void plansNamedCorrectly() throws Exception {
+ Runner runner= Request.aClass(FibonacciTest.class).getRunner();
+ Description description= runner.getDescription();
+ assertEquals("[0]", description.getChildren().get(0).getDisplayName());
+ }
+
+ private static String fLog;
+
+ @RunWith(Parameterized.class)
+ static public class BeforeAndAfter {
+ @BeforeClass
+ public static void before() {
+ fLog+= "before ";
+ }
+
+ @AfterClass
+ public static void after() {
+ fLog+= "after ";
+ }
+
+ public BeforeAndAfter(int x) {
+
+ }
+
+ @Parameters
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] { { 3 } });
+ }
+
+ @Test
+ public void aTest() {
+ }
+ }
+
+ @Test
+ public void beforeAndAfterClassAreRun() {
+ fLog= "";
+ JUnitCore.runClasses(BeforeAndAfter.class);
+ assertEquals("before after ", fLog);
+ }
+
+ @RunWith(Parameterized.class)
+ static public class EmptyTest {
+ @BeforeClass
+ public static void before() {
+ fLog+= "before ";
+ }
+
+ @AfterClass
+ public static void after() {
+ fLog+= "after ";
+ }
+ }
+
+ @Test
+ public void validateClassCatchesNoParameters() {
+ Result result= JUnitCore.runClasses(EmptyTest.class);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ @RunWith(Parameterized.class)
+ static public class IncorrectTest {
+ @Test
+ public int test() {
+ return 0;
+ }
+
+ @Parameters
+ public static Collection<Object[]> data() {
+ return Collections.singletonList(new Object[] {1});
+ }
+ }
+
+ @Test
+ public void failuresAddedForBadTestMethod() throws Exception {
+ Result result= JUnitCore.runClasses(IncorrectTest.class);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ @RunWith(Parameterized.class)
+ static public class ProtectedParametersTest {
+ @Parameters
+ protected static Collection<Object[]> data() {
+ return Collections.emptyList();
+ }
+
+ @Test
+ public void aTest() {
+ }
+ }
+
+ @Test
+ public void meaningfulFailureWhenParametersNotPublic() throws Exception {
+ Result result= JUnitCore.runClasses(ProtectedParametersTest.class);
+ String expected= String.format(
+ "No public static parameters method on class %s",
+ ProtectedParametersTest.class.getName());
+ assertEquals(expected, result.getFailures().get(0).getMessage());
+ }
+
+ @RunWith(Parameterized.class)
+ static public class WrongElementType {
+ @Parameters
+ public static Collection<String> data() {
+ return Arrays.asList("a", "b", "c");
+ }
+
+ @Test
+ public void aTest() {
+ }
+ }
+
+ @Test
+ public void meaningfulFailureWhenParameterListsAreNotArrays() {
+ String expected= String.format(
+ "%s.data() must return a Collection of arrays.",
+ WrongElementType.class.getName());
+ assertThat(testResult(WrongElementType.class).toString(),
+ containsString(expected));
+ }
+
+ @RunWith(Parameterized.class)
+ static public class PrivateConstructor {
+ private PrivateConstructor(int x) {
+
+ }
+
+ @Parameters
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] { { 3 } });
+ }
+
+ @Test
+ public void aTest() {
+ }
+ }
+
+ @Test(expected=InitializationError.class)
+ public void exceptionWhenPrivateConstructor() throws Throwable {
+ new Parameterized(PrivateConstructor.class);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java b/junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java
new file mode 100644
index 0000000..9bf542f
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java
@@ -0,0 +1,171 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;
+import static org.junit.runner.Description.createSuiteDescription;
+import static org.junit.runner.Description.createTestDescription;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+import org.junit.runners.model.InitializationError;
+import org.junit.runners.model.RunnerBuilder;
+
+public class ParentRunnerFilteringTest {
+ private static Filter notThisMethodName(final String methodName) {
+ return new Filter() {
+ @Override
+ public boolean shouldRun(Description description) {
+ return description.getMethodName() == null
+ || !description.getMethodName().equals(methodName);
+ }
+
+ @Override
+ public String describe() {
+ return "don't run method name: " + methodName;
+ }
+ };
+ }
+
+ private static class CountingFilter extends Filter {
+ private final Map<Description, Integer> countMap= new HashMap<Description, Integer>();
+
+ @Override
+ public boolean shouldRun(Description description) {
+ Integer count= countMap.get(description);
+ if (count == null) {
+ countMap.put(description, 1);
+ } else {
+ countMap.put(description, count + 1);
+ }
+ return true;
+ }
+
+ @Override
+ public String describe() {
+ return "filter counter";
+ }
+
+ public int getCount(final Description desc) {
+ if (!countMap.containsKey(desc)) {
+ throw new IllegalArgumentException("Looking for " + desc
+ + ", but only contains: " + countMap.keySet());
+ }
+ return countMap.get(desc);
+ }
+ }
+
+ public static class ExampleTest {
+ @Test
+ public void test1() throws Exception {
+ // passes
+ }
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses({ ExampleTest.class })
+ public static class ExampleSuite {
+ }
+
+ @Test
+ public void testSuiteFiltering() throws Exception {
+ Runner runner= Request.aClass(ExampleSuite.class).getRunner();
+ Filter filter= notThisMethodName("test1");
+ try {
+ filter.apply(runner);
+ } catch (NoTestsRemainException e) {
+ return;
+ }
+ fail("Expected 'NoTestsRemainException' due to complete filtering");
+ }
+
+ public static class SuiteWithUnmodifyableChildList extends Suite {
+
+ public SuiteWithUnmodifyableChildList(
+ Class<?> klass, RunnerBuilder builder)
+ throws InitializationError {
+ super(klass, builder);
+ }
+
+ @Override
+ protected List<Runner> getChildren() {
+ return Collections.unmodifiableList(super.getChildren());
+ }
+ }
+
+ @RunWith(SuiteWithUnmodifyableChildList.class)
+ @SuiteClasses({ ExampleTest.class })
+ public static class ExampleSuiteWithUnmodifyableChildList {
+ }
+
+ @Test
+ public void testSuiteFilteringWithUnmodifyableChildList() throws Exception {
+ Runner runner= Request.aClass(ExampleSuiteWithUnmodifyableChildList.class)
+ .getRunner();
+ Filter filter= notThisMethodName("test1");
+ try {
+ filter.apply(runner);
+ } catch (NoTestsRemainException e) {
+ return;
+ }
+ fail("Expected 'NoTestsRemainException' due to complete filtering");
+ }
+
+ @Test
+ public void testRunSuiteFiltering() throws Exception {
+ Request request= Request.aClass(ExampleSuite.class);
+ Request requestFiltered= request.filterWith(notThisMethodName("test1"));
+ assertThat(testResult(requestFiltered),
+ hasSingleFailureContaining("don't run method name: test1"));
+ }
+
+ @Test
+ public void testCountClassFiltering() throws Exception {
+ JUnitCore junitCore= new JUnitCore();
+ Request request= Request.aClass(ExampleTest.class);
+ CountingFilter countingFilter= new CountingFilter();
+ Request requestFiltered= request.filterWith(countingFilter);
+ Result result= junitCore.run(requestFiltered);
+ assertEquals(1, result.getRunCount());
+ assertEquals(0, result.getFailureCount());
+
+ Description desc= createTestDescription(ExampleTest.class, "test1");
+ assertEquals(1, countingFilter.getCount(desc));
+ }
+
+ @Test
+ public void testCountSuiteFiltering() throws Exception {
+ Class<ExampleSuite> suiteClazz= ExampleSuite.class;
+ Class<ExampleTest> clazz= ExampleTest.class;
+
+ JUnitCore junitCore= new JUnitCore();
+ Request request= Request.aClass(suiteClazz);
+ CountingFilter countingFilter= new CountingFilter();
+ Request requestFiltered= request.filterWith(countingFilter);
+ Result result= junitCore.run(requestFiltered);
+ assertEquals(1, result.getRunCount());
+ assertEquals(0, result.getFailureCount());
+
+ Description suiteDesc= createSuiteDescription(clazz);
+ assertEquals(1, countingFilter.getCount(suiteDesc));
+
+ Description desc= createTestDescription(ExampleTest.class, "test1");
+ assertEquals(1, countingFilter.getCount(desc));
+ }
+} \ No newline at end of file
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java b/junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java
new file mode 100644
index 0000000..21c22b8
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java
@@ -0,0 +1,139 @@
+package org.junit.tests.running.classes;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import java.util.List;
+
+import org.hamcrest.Matcher;
+import org.junit.Test;
+import org.junit.internal.matchers.TypeSafeMatcher;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.ParentRunner;
+import org.junit.runners.model.InitializationError;
+import org.junit.runners.model.RunnerScheduler;
+import org.junit.tests.experimental.rules.RuleFieldValidatorTest.TestWithNonStaticClassRule;
+import org.junit.tests.experimental.rules.RuleFieldValidatorTest.TestWithProtectedClassRule;
+
+public class ParentRunnerTest {
+ public static String log= "";
+
+ public static class FruitTest {
+ @Test
+ public void apple() {
+ log+= "apple ";
+ }
+
+ @Test
+ public void banana() {
+ log+= "banana ";
+ }
+ }
+
+ @Test
+ public void useChildHarvester() throws InitializationError {
+ log= "";
+ ParentRunner<?> runner= new BlockJUnit4ClassRunner(FruitTest.class);
+ runner.setScheduler(new RunnerScheduler() {
+ public void schedule(Runnable childStatement) {
+ log+= "before ";
+ childStatement.run();
+ log+= "after ";
+ }
+
+ public void finished() {
+ log+= "afterAll ";
+ }
+ });
+
+ runner.run(new RunNotifier());
+ assertEquals("before apple after before banana after afterAll ", log);
+ }
+
+ @Test
+ public void testMultipleFilters() throws Exception {
+ JUnitCore junitCore= new JUnitCore();
+ Request request= Request.aClass(ExampleTest.class);
+ Request requestFiltered= request.filterWith(new Exclude("test1"));
+ Request requestFilteredFiltered= requestFiltered
+ .filterWith(new Exclude("test2"));
+ Result result= junitCore.run(requestFilteredFiltered);
+ assertThat(result.getFailures(), isEmpty());
+ assertEquals(1, result.getRunCount());
+ }
+
+ private Matcher<List<?>> isEmpty() {
+ return new TypeSafeMatcher<List<?>>() {
+ public void describeTo(org.hamcrest.Description description) {
+ description.appendText("is empty");
+ }
+
+ @Override
+ public boolean matchesSafely(List<?> item) {
+ return item.size() == 0;
+ }
+ };
+ }
+
+ private static class Exclude extends Filter {
+ private String methodName;
+
+ public Exclude(String methodName) {
+ this.methodName= methodName;
+ }
+
+ @Override
+ public boolean shouldRun(Description description) {
+ return !description.getMethodName().equals(methodName);
+ }
+
+ @Override
+ public String describe() {
+ return "filter method name: " + methodName;
+ }
+ }
+
+ public static class ExampleTest {
+ @Test
+ public void test1() throws Exception {
+ }
+
+ @Test
+ public void test2() throws Exception {
+ }
+
+ @Test
+ public void test3() throws Exception {
+ }
+ }
+
+ @Test
+ public void failWithHelpfulMessageForProtectedClassRule() {
+ assertClassHasFailureMessage(TestWithProtectedClassRule.class,
+ "The @ClassRule 'temporaryFolder' must be public.");
+ }
+
+ @Test
+ public void failWithHelpfulMessageForNonStaticClassRule() {
+ assertClassHasFailureMessage(TestWithNonStaticClassRule.class,
+ "The @ClassRule 'temporaryFolder' must be static.");
+ }
+
+ private void assertClassHasFailureMessage(Class<?> klass, String message) {
+ JUnitCore junitCore= new JUnitCore();
+ Request request= Request.aClass(klass);
+ Result result= junitCore.run(request);
+ assertThat(result.getFailureCount(), is(2)); //the second failure is no runnable methods
+ assertThat(result.getFailures().get(0).getMessage(),
+ is(equalTo(message)));
+
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/RunWithTest.java b/junit4/src/test/java/org/junit/tests/running/classes/RunWithTest.java
new file mode 100644
index 0000000..1df0167
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/RunWithTest.java
@@ -0,0 +1,85 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.notification.RunNotifier;
+
+public class RunWithTest {
+
+ private static String log;
+
+ public static class ExampleRunner extends Runner {
+ public ExampleRunner(Class<?> klass) {
+ log+= "initialize";
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+ log+= "run";
+ }
+
+ @Override
+ public int testCount() {
+ log+= "count";
+ return 0;
+ }
+
+ @Override
+ public Description getDescription() {
+ log+= "plan";
+ return Description.createSuiteDescription("example");
+ }
+ }
+
+ @RunWith(ExampleRunner.class)
+ public static class ExampleTest {
+ }
+
+ @Test public void run() {
+ log= "";
+
+ JUnitCore.runClasses(ExampleTest.class);
+ assertTrue(log.contains("plan"));
+ assertTrue(log.contains("initialize"));
+ assertTrue(log.contains("run"));
+ }
+
+ public static class SubExampleTest extends ExampleTest {
+ }
+
+ @Test public void runWithExtendsToSubclasses() {
+ log= "";
+
+ JUnitCore.runClasses(SubExampleTest.class);
+ assertTrue(log.contains("run"));
+ }
+
+ public static class BadRunner extends Runner {
+ @Override
+ public Description getDescription() {
+ return null;
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+ // do nothing
+ }
+ }
+
+ @RunWith(BadRunner.class)
+ public static class Empty {
+ }
+
+ @Test
+ public void characterizeErrorMessageFromBadRunner() {
+ assertEquals(
+ "Custom runner class BadRunner should have a public constructor with signature BadRunner(Class testClass)",
+ JUnitCore.runClasses(Empty.class).getFailures().get(0)
+ .getMessage());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/SuiteTest.java b/junit4/src/test/java/org/junit/tests/running/classes/SuiteTest.java
new file mode 100644
index 0000000..bda24fd
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/SuiteTest.java
@@ -0,0 +1,167 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.experimental.results.PrintableResult.testResult;
+import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;
+
+import java.util.List;
+
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestResult;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+public class SuiteTest {
+ public static class TestA {
+ @Test public void pass() {
+ }
+ }
+
+ public static class TestB {
+ @Test public void fail() {
+ Assert.fail();
+ }
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses({TestA.class, TestB.class})
+ public static class All {
+ }
+
+ public static class InheritsAll extends All {
+ }
+
+ @Test public void ensureTestIsRun() {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(All.class);
+ assertEquals(2, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ }
+
+ @Test public void ensureInheritedTestIsRun() {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(InheritsAll.class);
+ assertEquals(2, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ }
+
+ @Test public void suiteTestCountIsCorrect() throws Exception {
+ Runner runner= Request.aClass(All.class).getRunner();
+ assertEquals(2, runner.testCount());
+ }
+
+ @Test public void ensureSuitesWorkWithForwardCompatibility() {
+ junit.framework.Test test= new JUnit4TestAdapter(All.class);
+ TestResult result= new TestResult();
+ test.run(result);
+ assertEquals(2, result.runCount());
+ }
+
+ @Test public void forwardCompatibilityWorksWithGetTests() {
+ JUnit4TestAdapter adapter= new JUnit4TestAdapter(All.class);
+ List<? extends junit.framework.Test> tests= adapter.getTests();
+ assertEquals(2, tests.size());
+ }
+
+ @Test public void forwardCompatibilityWorksWithTestCount() {
+ JUnit4TestAdapter adapter= new JUnit4TestAdapter(All.class);
+ assertEquals(2, adapter.countTestCases());
+ }
+
+
+ private static String log= "";
+ @RunWith(Suite.class)
+ @SuiteClasses({TestA.class, TestB.class})
+ public static class AllWithBeforeAndAfterClass {
+ @BeforeClass public static void before() { log+= "before "; }
+ @AfterClass public static void after() { log+= "after "; }
+ }
+
+ @Test public void beforeAndAfterClassRunOnSuite() {
+ log= "";
+ JUnitCore.runClasses(AllWithBeforeAndAfterClass.class);
+ assertEquals("before after ", log);
+ }
+
+ @RunWith(Suite.class)
+ public static class AllWithOutAnnotation {
+ }
+
+ @Test public void withoutSuiteClassAnnotationProducesFailure() {
+ Result result= JUnitCore.runClasses(AllWithOutAnnotation.class);
+ assertEquals(1, result.getFailureCount());
+ String expected= String.format(
+ "class '%s' must have a SuiteClasses annotation",
+ AllWithOutAnnotation.class.getName());
+ assertEquals(expected, result.getFailures().get(0).getMessage());
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses(InfiniteLoop.class)
+ static public class InfiniteLoop { }
+
+ @Test public void whatHappensWhenASuiteHasACycle() {
+ Result result= JUnitCore.runClasses(InfiniteLoop.class);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses({BiInfiniteLoop.class, BiInfiniteLoop.class})
+ static public class BiInfiniteLoop { }
+
+ @Test public void whatHappensWhenASuiteHasAForkingCycle() {
+ Result result= JUnitCore.runClasses(BiInfiniteLoop.class);
+ assertEquals(2, result.getFailureCount());
+ }
+
+ // The interesting case here is that Hydra indirectly contains two copies of
+ // itself (if it only contains one, Java's StackOverflowError eventually
+ // bails us out)
+
+ @RunWith(Suite.class)
+ @SuiteClasses({Hercules.class})
+ static public class Hydra { }
+
+ @RunWith(Suite.class)
+ @SuiteClasses({Hydra.class, Hydra.class})
+ static public class Hercules { }
+
+ @Test public void whatHappensWhenASuiteContainsItselfIndirectly() {
+ Result result= JUnitCore.runClasses(Hydra.class);
+ assertEquals(2, result.getFailureCount());
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses( {})
+ public class WithoutDefaultConstructor {
+ public WithoutDefaultConstructor(int i) {
+
+ }
+ }
+
+ @Test
+ public void suiteShouldBeOKwithNonDefaultConstructor() throws Exception {
+ Result result= JUnitCore.runClasses(WithoutDefaultConstructor.class);
+ assertTrue(result.wasSuccessful());
+ }
+
+ @RunWith(Suite.class)
+ public class NoSuiteClassesAnnotation {
+ }
+
+ @Test
+ public void suiteShouldComplainAboutNoSuiteClassesAnnotation() {
+ assertThat(testResult(NoSuiteClassesAnnotation.class), hasSingleFailureContaining("SuiteClasses"));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/TestClassTest.java b/junit4/src/test/java/org/junit/tests/running/classes/TestClassTest.java
new file mode 100644
index 0000000..7b738d9
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/TestClassTest.java
@@ -0,0 +1,121 @@
+package org.junit.tests.running.classes;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runners.model.TestClass;
+
+public class TestClassTest {
+ public static class TwoConstructors {
+ public TwoConstructors() {
+ }
+
+ public TwoConstructors(int x) {
+ }
+ }
+
+ @Test(expected= IllegalArgumentException.class)
+ public void complainIfMultipleConstructors() {
+ new TestClass(TwoConstructors.class);
+ }
+
+ public static class ManyMethods {
+ @Test
+ public void a() {
+ }
+
+ @Before
+ public void b() {
+ }
+
+ @Ignore
+ @Test
+ public void c() {
+ }
+
+ @Ignore
+ @After
+ public void d() {
+ }
+
+ public void e() {
+ }
+
+ @BeforeClass
+ public void f() {
+ }
+
+ public void g() {
+ }
+
+ @AfterClass
+ public void h() {
+ }
+
+ @Test
+ public void i() {
+ }
+
+ @Test
+ public void j() {
+ }
+ }
+
+ public static class SuperclassWithField {
+ @Rule
+ public TestRule x;
+ }
+
+ public static class SubclassWithField extends SuperclassWithField {
+ @Rule
+ public TestRule x;
+ }
+
+ @Test
+ public void fieldsOnSubclassesShadowSuperclasses() {
+ assertThat(new TestClass(SubclassWithField.class).getAnnotatedFields(
+ Rule.class).size(), is(1));
+ }
+
+ public static class OuterClass {
+ public class NonStaticInnerClass {
+ }
+ }
+
+ @Test
+ public void identifyNonStaticInnerClass() {
+ assertThat(
+ new TestClass(OuterClass.NonStaticInnerClass.class)
+ .isANonStaticInnerClass(),
+ is(true));
+ }
+
+ public static class OuterClass2 {
+ public static class StaticInnerClass {
+ }
+ }
+
+ @Test
+ public void dontMarkStaticInnerClassAsNonStatic() {
+ assertThat(
+ new TestClass(OuterClass2.StaticInnerClass.class)
+ .isANonStaticInnerClass(),
+ is(false));
+ }
+
+ public static class SimpleClass {
+ }
+
+ @Test
+ public void dontMarkNonInnerClassAsInnerClass() {
+ assertThat(new TestClass(SimpleClass.class).isANonStaticInnerClass(),
+ is(false));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java b/junit4/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java
new file mode 100644
index 0000000..2917181
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java
@@ -0,0 +1,44 @@
+package org.junit.tests.running.classes;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.model.InitializationError;
+
+public class UseSuiteAsASuperclassTest {
+
+ public static class TestA {
+ @Test
+ public void pass() {
+ }
+ }
+
+ public static class TestB {
+ @Test
+ public void dontPass() {
+ fail();
+ }
+ }
+
+ public static class MySuite extends Suite {
+ public MySuite(Class<?> klass) throws InitializationError {
+ super(klass, new Class[] { TestA.class, TestB.class });
+ }
+ }
+
+ @RunWith(MySuite.class)
+ public static class AllWithMySuite {
+ }
+
+ @Test
+ public void ensureTestsAreRun() {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(AllWithMySuite.class);
+ assertEquals(2, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/core/CommandLineTest.java b/junit4/src/test/java/org/junit/tests/running/core/CommandLineTest.java
new file mode 100644
index 0000000..cdf8b55
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/core/CommandLineTest.java
@@ -0,0 +1,67 @@
+package org.junit.tests.running.core;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.internal.RealSystem;
+import org.junit.runner.JUnitCore;
+
+public class CommandLineTest {
+ private ByteArrayOutputStream results;
+ private PrintStream oldOut;
+ private static boolean testWasRun;
+
+ @Before public void before() {
+ oldOut= System.out;
+ results= new ByteArrayOutputStream();
+ System.setOut(new PrintStream(results));
+ }
+
+ @After public void after() {
+ System.setOut(oldOut);
+ }
+
+ static public class Example {
+ @Test public void test() {
+ testWasRun= true;
+ }
+ }
+
+ @Test public void runATest() {
+ testWasRun= false; // todo create a TestSystem instead
+ new JUnitCore().runMain(new RealSystem(), new String[]{"org.junit.tests.running.core.CommandLineTest$Example"});
+ assertTrue(testWasRun);
+ }
+
+ @Test public void runAClass() {
+ testWasRun= false;
+ JUnitCore.runClasses(Example.class);
+ assertTrue(testWasRun);
+ }
+
+ private static int fCount;
+
+ static public class Count {
+ @Test public void increment() {
+ fCount++;
+ }
+ }
+
+ @Test public void runTwoClassesAsArray() {
+ fCount= 0;
+ JUnitCore.runClasses(new Class[] {Count.class, Count.class});
+ assertEquals(2, fCount);
+ }
+
+ @Test public void runTwoClasses() {
+ fCount= 0;
+ JUnitCore.runClasses(Count.class, Count.class);
+ assertEquals(2, fCount);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java b/junit4/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java
new file mode 100644
index 0000000..0d8bb37
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java
@@ -0,0 +1,39 @@
+package org.junit.tests.running.core;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.tests.TestSystem;
+
+public class JUnitCoreReturnsCorrectExitCodeTest {
+
+ static public class Fail {
+ @Test public void kaboom() {
+ fail();
+ }
+ }
+
+ @Test public void failureCausesExitCodeOf1() throws Exception {
+ runClass(getClass().getName() + "$Fail", 1);
+ }
+
+ @Test public void missingClassCausesExitCodeOf1() throws Exception {
+ runClass("Foo", 1);
+ }
+
+ static public class Succeed {
+ @Test public void peacefulSilence() {
+ }
+ }
+
+ @Test public void successCausesExitCodeOf0() throws Exception {
+ runClass(getClass().getName() + "$Succeed", 0);
+ }
+
+ private void runClass(String className, int returnCode) {
+ TestSystem system= new TestSystem();
+ JUnitCore.runMainAndExit(system, className);
+ assertEquals(returnCode, system.fCode);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/core/SystemExitTest.java b/junit4/src/test/java/org/junit/tests/running/core/SystemExitTest.java
new file mode 100644
index 0000000..1460119
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/core/SystemExitTest.java
@@ -0,0 +1,30 @@
+package org.junit.tests.running.core;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+import java.io.InputStream;
+
+import org.junit.Test;
+
+// Make sure System.exit works as expected. We've had problems with this on some platforms.
+public class SystemExitTest {
+
+ private static final int EXIT_CODE= 5;
+
+ static public class Exit {
+ public static void main(String[] args) {
+ System.exit(EXIT_CODE);
+ }
+ }
+
+ @Test public void failureCausesExitCodeOf1() throws Exception {
+ String java= System.getProperty("java.home")+File.separator+"bin"+File.separator+"java";
+ String classPath= getClass().getClassLoader().getResource(".").getFile() + File.pathSeparator + System.getProperty("java.class.path");
+ String [] cmd= { java, "-cp", classPath, getClass().getName() + "$Exit"};
+ Process process= Runtime.getRuntime().exec(cmd);
+ InputStream input= process.getInputStream();
+ while((input.read()) != -1);
+ assertEquals(EXIT_CODE, process.waitFor());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/methods/AnnotationTest.java b/junit4/src/test/java/org/junit/tests/running/methods/AnnotationTest.java
new file mode 100644
index 0000000..2eb496a
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/methods/AnnotationTest.java
@@ -0,0 +1,520 @@
+package org.junit.tests.running.methods;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.matchers.JUnitMatchers.both;
+import static org.junit.matchers.JUnitMatchers.containsString;
+
+import java.util.Collection;
+import java.util.HashSet;
+
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+public class AnnotationTest extends TestCase {
+ static boolean run;
+
+ @Override
+ public void setUp() {
+ run= false;
+ }
+
+ static public class SimpleTest {
+ @Test public void success() {
+ run= true;
+ }
+ }
+
+ public void testAnnotatedMethod() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ runner.run(SimpleTest.class);
+ assertTrue(run);
+ }
+
+ @RunWith(JUnit4.class)
+ static public class SimpleTestWithFutureProofExplicitRunner {
+ @Test public void success() {
+ run= true;
+ }
+ }
+
+ public void testAnnotatedMethodWithFutureProofExplicitRunner() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ runner.run(SimpleTestWithFutureProofExplicitRunner.class);
+ assertTrue(run);
+ }
+
+ static public class SetupTest {
+ @Before public void before() {
+ run= true;
+ }
+ @Test public void success() {
+ }
+ }
+
+ public void testSetup() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ runner.run(SetupTest.class);
+ assertTrue(run);
+ }
+
+ static public class TeardownTest {
+ @After public void after() {
+ run= true;
+ }
+ @Test public void success() {
+ }
+ }
+
+ public void testTeardown() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ runner.run(TeardownTest.class);
+ assertTrue(run);
+ }
+
+ static public class FailureTest {
+ @Test public void error() throws Exception {
+ org.junit.Assert.fail();
+ }
+ }
+
+ public void testRunFailure() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ Result result= runner.run(FailureTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ assertEquals(AssertionError.class, result.getFailures().get(0).getException().getClass());
+ }
+
+ static public class SetupFailureTest {
+ @Before public void before() {
+ throw new Error();
+ }
+ @Test public void test() {
+ run= true;
+ }
+ }
+
+ public void testSetupFailure() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result runner= core.run(SetupFailureTest.class);
+ assertEquals(1, runner.getRunCount());
+ assertEquals(1, runner.getFailureCount());
+ assertEquals(Error.class, runner.getFailures().get(0).getException().getClass());
+ assertFalse(run);
+ }
+
+ static public class TeardownFailureTest {
+ @After public void after() {
+ throw new Error();
+ }
+ @Test public void test() {
+ }
+ }
+
+ public void testTeardownFailure() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result runner= core.run(TeardownFailureTest.class);
+ assertEquals(1, runner.getRunCount());
+ assertEquals(1, runner.getFailureCount());
+ assertEquals(Error.class, runner.getFailures().get(0).getException().getClass());
+ }
+
+ static public class TestAndTeardownFailureTest {
+ @After public void after() {
+ throw new Error("hereAfter");
+ }
+ @Test public void test() throws Exception {
+ throw new Exception("inTest");
+ }
+ }
+
+ public void testTestAndTeardownFailure() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result runner= core.run(TestAndTeardownFailureTest.class);
+ assertEquals(1, runner.getRunCount());
+ assertEquals(2, runner.getFailureCount());
+ assertThat(runner.getFailures().toString(), both(containsString("hereAfter")).and(containsString("inTest")));
+ }
+
+ static public class TeardownAfterFailureTest {
+ @After public void after() {
+ run= true;
+ }
+ @Test public void test() throws Exception {
+ throw new Exception();
+ }
+ }
+
+ public void testTeardownAfterFailure() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ runner.run(TeardownAfterFailureTest.class);
+ assertTrue(run);
+ }
+
+ static int count;
+ static Collection<Object> tests;
+ static public class TwoTests {
+ @Test public void one() {
+ count++;
+ tests.add(this);
+ }
+ @Test public void two() {
+ count++;
+ tests.add(this);
+ }
+ }
+
+ public void testTwoTests() throws Exception {
+ count= 0;
+ tests= new HashSet<Object>();
+ JUnitCore runner= new JUnitCore();
+ runner.run(TwoTests.class);
+ assertEquals(2, count);
+ assertEquals(2, tests.size());
+ }
+
+ static public class OldTest extends TestCase {
+ public void test() {
+ run= true;
+ }
+ }
+ public void testOldTest() throws Exception {
+ JUnitCore runner= new JUnitCore();
+ runner.run(OldTest.class);
+ assertTrue(run);
+ }
+
+ static public class OldSuiteTest extends TestCase {
+ public void testOne() {
+ run= true;
+ }
+ }
+
+ public void testOldSuiteTest() throws Exception {
+ TestSuite suite= new TestSuite(OldSuiteTest.class);
+ JUnitCore runner= new JUnitCore();
+ runner.run(suite);
+ assertTrue(run);
+ }
+
+ static public class ExceptionTest {
+ @Test(expected= Error.class) public void expectedException() {
+ throw new Error();
+ }
+ }
+
+ public void testException() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(ExceptionTest.class);
+ assertEquals(0, result.getFailureCount());
+ }
+
+ static public class NoExceptionTest {
+ @Test(expected= Error.class)
+ public void expectedException() {
+ }
+ }
+
+ public void testExceptionNotThrown() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(NoExceptionTest.class);
+ assertEquals(1, result.getFailureCount());
+ assertEquals("Expected exception: java.lang.Error", result.getFailures().get(0).getMessage());
+ }
+
+ static public class OneTimeSetup {
+ @BeforeClass public static void once() {
+ count++;
+ }
+ @Test public void one() {}
+ @Test public void two() {}
+ }
+
+ public void testOneTimeSetup() throws Exception {
+ count= 0;
+ JUnitCore core= new JUnitCore();
+ core.run(OneTimeSetup.class);
+ assertEquals(1, count);
+ }
+
+ static public class OneTimeTeardown {
+ @AfterClass public static void once() {
+ count++;
+ }
+ @Test public void one() {}
+ @Test public void two() {}
+ }
+
+ public void testOneTimeTeardown() throws Exception {
+ count= 0;
+ JUnitCore core= new JUnitCore();
+ core.run(OneTimeTeardown.class);
+ assertEquals(1, count);
+ }
+
+ static String log;
+
+ public static class OrderTest {
+ @BeforeClass public static void onceBefore() { log+= "beforeClass "; }
+ @Before public void before() { log+= "before "; }
+ @Test public void test() { log+= "test "; }
+ @After public void after() { log+= "after "; }
+ @AfterClass public static void onceAfter() { log+= "afterClass "; }
+ }
+
+ public void testOrder() throws Exception {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ core.run(OrderTest.class);
+ assertEquals("beforeClass before test after afterClass ", log);
+ }
+
+ static public class NonStaticOneTimeSetup {
+ @BeforeClass public void once() {
+ }
+
+ @Test public void aTest() {
+ }
+ }
+
+ public void testNonStaticOneTimeSetup() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(NonStaticOneTimeSetup.class);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ static public class ErrorInBeforeClass {
+ @BeforeClass public static void before() throws Exception {
+ throw new Exception();
+ }
+ @Test public void test() {
+ run= true;
+ }
+ }
+
+ public void testErrorInBeforeClass() throws Exception {
+ run= false;
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(ErrorInBeforeClass.class);
+ assertFalse(run);
+ assertEquals(1, result.getFailureCount());
+ Description description= result.getFailures().get(0).getDescription();
+ assertEquals(ErrorInBeforeClass.class.getName(), description.getDisplayName());
+ }
+
+ static public class ErrorInAfterClass {
+ @Test public void test() {
+ run= true;
+ }
+ @AfterClass public static void after() throws Exception {
+ throw new Exception();
+ }
+ }
+
+ public void testErrorInAfterClass() throws Exception {
+ run= false;
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(ErrorInAfterClass.class);
+ assertTrue(run);
+ assertEquals(1, result.getFailureCount());
+ }
+
+ static public class SuperInheritance {
+ @BeforeClass static public void beforeClassSuper() {
+ log+= "Before class super ";
+ }
+ @AfterClass static public void afterClassSuper() {
+ log+= "After class super ";
+ }
+ @Before public void beforeSuper() {
+ log+= "Before super ";
+ }
+ @After public void afterSuper() {
+ log+= "After super ";
+ }
+ }
+
+ static public class SubInheritance extends SuperInheritance {
+ @BeforeClass static public void beforeClassSub() {
+ log+= "Before class sub ";
+ }
+ @AfterClass static public void afterClassSub() {
+ log+= "After class sub ";
+ }
+ @Before public void beforeSub() {
+ log+= "Before sub ";
+ }
+ @After public void afterSub() {
+ log+= "After sub ";
+ }
+ @Test public void test() {
+ log+= "Test ";
+ }
+ }
+
+ public void testOrderingOfInheritance() throws Exception {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ core.run(SubInheritance.class);
+ assertEquals("Before class super Before class sub Before super Before sub Test After sub After super After class sub After class super ", log);
+ }
+
+ static public class SuperShadowing {
+ @Before public void before() {
+ log+= "Before super ";
+ }
+ @After public void after() {
+ log+= "After super ";
+ }
+ }
+
+ static public class SubShadowing extends SuperShadowing {
+ @Override
+ @Before public void before() {
+ log+= "Before sub ";
+ }
+ @Override
+ @After public void after() {
+ log+= "After sub ";
+ }
+ @Test public void test() {
+ log+= "Test ";
+ }
+ }
+
+ public void testShadowing() throws Exception {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ core.run(SubShadowing.class);
+ assertEquals("Before sub Test After sub ", log);
+ }
+
+ static public class SuperTest {
+ @Test public void one() {
+ log+= "Super";
+ }
+
+ @Test public void two() {
+ log+= "Two";
+ }
+ }
+
+ static public class SubTest extends SuperTest {
+ @Override
+ @Test public void one() {
+ log+= "Sub";
+ }
+ }
+
+ public void testTestInheritance() throws Exception {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ core.run(SubTest.class);
+ // The order in which the test methods are called is unspecified
+ assertTrue(log.contains("Sub"));
+ assertTrue(log.contains("Two"));
+ assertFalse(log.contains("Super"));
+ }
+
+ static public class RunAllAfters {
+ @Before public void good() {
+ }
+ @Before public void bad() {
+ throw new Error();
+ }
+ @Test public void empty() {
+ }
+ @After public void one() {
+ log+= "one";
+ }
+ @After public void two() {
+ log+= "two";
+ }
+ }
+
+ public void testRunAllAfters() {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ core.run(RunAllAfters.class);
+ assertTrue(log.contains("one"));
+ assertTrue(log.contains("two"));
+ }
+
+ static public class RunAllAftersRegardless {
+ @Test public void empty() {
+ }
+ @After public void one() {
+ log+= "one";
+ throw new Error();
+ }
+ @After public void two() {
+ log+= "two";
+ throw new Error();
+ }
+ }
+
+ public void testRunAllAftersRegardless() {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(RunAllAftersRegardless.class);
+ assertTrue(log.contains("one"));
+ assertTrue(log.contains("two"));
+ assertEquals(2, result.getFailureCount());
+ }
+
+ static public class RunAllAfterClasses {
+ @Before public void good() {
+ }
+ @BeforeClass public static void bad() {
+ throw new Error();
+ }
+ @Test public void empty() {
+ }
+ @AfterClass public static void one() {
+ log+= "one";
+ }
+ @AfterClass public static void two() {
+ log+= "two";
+ }
+ }
+
+ public void testRunAllAfterClasses() {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ core.run(RunAllAfterClasses.class);
+ assertTrue(log.contains("one"));
+ assertTrue(log.contains("two"));
+ }
+
+ static public class RunAllAfterClassesRegardless {
+ @Test public void empty() {
+ }
+ @AfterClass static public void one() {
+ log+= "one";
+ throw new Error();
+ }
+ @AfterClass static public void two() {
+ log+= "two";
+ throw new Error();
+ }
+ }
+
+ public void testRunAllAfterClassesRegardless() {
+ log= "";
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(RunAllAfterClassesRegardless.class);
+ assertTrue(log.contains("one"));
+ assertTrue(log.contains("two"));
+ assertEquals(2, result.getFailureCount());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/methods/ExpectedTest.java b/junit4/src/test/java/org/junit/tests/running/methods/ExpectedTest.java
new file mode 100644
index 0000000..d16e689
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/methods/ExpectedTest.java
@@ -0,0 +1,58 @@
+package org.junit.tests.running.methods;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.notification.Failure;
+
+public class ExpectedTest {
+
+ public static class Expected {
+ @Test(expected= Exception.class) public void expected() throws Exception {
+ throw new Exception();
+ }
+ }
+
+ @Test public void expected() {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(Expected.class);
+ assertTrue(result.wasSuccessful());
+ }
+
+ public static class Unexpected {
+ @Test(expected= Exception.class) public void expected() throws Exception {
+ throw new Error();
+ }
+ }
+ @Test public void unexpected() {
+ Result result= JUnitCore.runClasses(Unexpected.class);
+ Failure failure= result.getFailures().get(0);
+ String message= failure.getMessage();
+ assertTrue(message.contains("expected<java.lang.Exception> but was<java.lang.Error>"));
+ assertEquals(Error.class, failure.getException().getCause().getClass());
+ }
+
+ public static class NoneThrown {
+ @Test(expected= Exception.class) public void nothing() {
+ }
+ }
+ @Test public void noneThrown() {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(NoneThrown.class);
+ assertFalse(result.wasSuccessful());
+ String message= result.getFailures().get(0).getMessage();
+ assertTrue(message.contains("Expected exception: java.lang.Exception"));
+ }
+
+ public static class ExpectSuperclass {
+ @Test(expected= RuntimeException.class) public void throwsSubclass() {
+ throw new ClassCastException();
+ }
+ }
+ @Test public void expectsSuperclass() {
+ assertTrue(new JUnitCore().run(ExpectSuperclass.class).wasSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java b/junit4/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java
new file mode 100644
index 0000000..15f55a6
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java
@@ -0,0 +1,31 @@
+package org.junit.tests.running.methods;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+
+public class InheritedTestTest {
+ public abstract static class Super {
+ @Test public void nothing() {}
+ }
+ public static class Sub extends Super {}
+
+ @Test public void subclassWithOnlyInheritedTestsRuns() {
+ Result result= JUnitCore.runClasses(Sub.class);
+ assertTrue(result.wasSuccessful());
+ }
+
+ public static class SubWithBefore extends Super {
+ @Before public void gack() {
+ fail();
+ }
+ }
+
+ @Test public void subclassWithInheritedTestAndOwnBeforeRunsBefore() {
+ assertFalse(JUnitCore.runClasses(SubWithBefore.class).wasSuccessful());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java b/junit4/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java
new file mode 100644
index 0000000..4d4dcbd
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java
@@ -0,0 +1,102 @@
+package org.junit.tests.running.methods;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import junit.framework.JUnit4TestAdapter;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+import org.junit.runners.model.InitializationError;
+
+@RunWith(Parameterized.class)
+public class ParameterizedTestMethodTest {
+
+ @SuppressWarnings("all")
+ public static class EverythingWrong {
+ private EverythingWrong() {}
+ @BeforeClass public void notStaticBC() {}
+ @BeforeClass static void notPublicBC() {}
+ @BeforeClass public static int nonVoidBC() { return 0; }
+ @BeforeClass public static void argumentsBC(int i) {}
+ @BeforeClass public static void fineBC() {}
+ @AfterClass public void notStaticAC() {}
+ @AfterClass static void notPublicAC() {}
+ @AfterClass public static int nonVoidAC() { return 0; }
+ @AfterClass public static void argumentsAC(int i) {}
+ @AfterClass public static void fineAC() {}
+ @After public static void staticA() {}
+ @After void notPublicA() {}
+ @After public int nonVoidA() { return 0; }
+ @After public void argumentsA(int i) {}
+ @After public void fineA() {}
+ @Before public static void staticB() {}
+ @Before void notPublicB() {}
+ @Before public int nonVoidB() { return 0; }
+ @Before public void argumentsB(int i) {}
+ @Before public void fineB() {}
+ @Test public static void staticT() {}
+ @Test void notPublicT() {}
+ @Test public int nonVoidT() { return 0; }
+ @Test public void argumentsT(int i) {}
+ @Test public void fineT() {}
+ }
+
+ private Class<?> fClass;
+ private int fErrorCount;
+
+ static public class SuperWrong {
+ @Test void notPublic() {
+ }
+ }
+
+ static public class SubWrong extends SuperWrong {
+ @Test public void justFine() {
+ }
+ }
+
+ static public class SubShadows extends SuperWrong {
+ @Override
+ @Test public void notPublic() {
+ }
+ }
+
+ public ParameterizedTestMethodTest(Class<?> class1, int errorCount) {
+ fClass= class1;
+ fErrorCount= errorCount;
+ }
+
+ @Parameters
+ public static Collection<Object[]> params() {
+ return Arrays.asList(new Object[][] {
+ { EverythingWrong.class, 1 + 4 * 5 }, { SubWrong.class, 1 },
+ { SubShadows.class, 0 } });
+ }
+
+ private List<Throwable> validateAllMethods(Class<?> clazz) {
+ try {
+ new BlockJUnit4ClassRunner(clazz);
+ } catch (InitializationError e) {
+ return e.getCauses();
+ }
+ return Collections.emptyList();
+ }
+
+ @Test public void testFailures() throws Exception {
+ List<Throwable> problems= validateAllMethods(fClass);
+ assertEquals(fErrorCount, problems.size());
+ }
+ public static junit.framework.Test suite() {
+ return new JUnit4TestAdapter(ParameterizedTestMethodTest.class);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/methods/TestMethodTest.java b/junit4/src/test/java/org/junit/tests/running/methods/TestMethodTest.java
new file mode 100644
index 0000000..cbabab2
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/methods/TestMethodTest.java
@@ -0,0 +1,147 @@
+package org.junit.tests.running.methods;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.List;
+
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestResult;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.InitializationError;
+
+public class TestMethodTest {
+
+ @SuppressWarnings("all")
+ public static class EverythingWrong {
+ private EverythingWrong() {}
+ @BeforeClass public void notStaticBC() {}
+ @BeforeClass static void notPublicBC() {}
+ @BeforeClass public static int nonVoidBC() { return 0; }
+ @BeforeClass public static void argumentsBC(int i) {}
+ @BeforeClass public static void fineBC() {}
+ @AfterClass public void notStaticAC() {}
+ @AfterClass static void notPublicAC() {}
+ @AfterClass public static int nonVoidAC() { return 0; }
+ @AfterClass public static void argumentsAC(int i) {}
+ @AfterClass public static void fineAC() {}
+ @After public static void staticA() {}
+ @After void notPublicA() {}
+ @After public int nonVoidA() { return 0; }
+ @After public void argumentsA(int i) {}
+ @After public void fineA() {}
+ @Before public static void staticB() {}
+ @Before void notPublicB() {}
+ @Before public int nonVoidB() { return 0; }
+ @Before public void argumentsB(int i) {}
+ @Before public void fineB() {}
+ @Test public static void staticT() {}
+ @Test void notPublicT() {}
+ @Test public int nonVoidT() { return 0; }
+ @Test public void argumentsT(int i) {}
+ @Test public void fineT() {}
+ }
+
+ @Test public void testFailures() throws Exception {
+ List<Throwable> problems= validateAllMethods(EverythingWrong.class);
+ int errorCount= 1 + 4 * 5; // missing constructor plus four invalid methods for each annotation */
+ assertEquals(errorCount, problems.size());
+ }
+
+ static public class SuperWrong {
+ @Test void notPublic() {
+ }
+ }
+
+ static public class SubWrong extends SuperWrong {
+ @Test public void justFine() {
+ }
+ }
+
+ @Test public void validateInheritedMethods() throws Exception {
+ List<Throwable> problems= validateAllMethods(SubWrong.class);
+ assertEquals(1, problems.size());
+ }
+
+ static public class SubShadows extends SuperWrong {
+ @Override
+ @Test public void notPublic() {
+ }
+ }
+
+ @Test public void dontValidateShadowedMethods() throws Exception {
+ List<Throwable> problems= validateAllMethods(SubShadows.class);
+ assertTrue(problems.isEmpty());
+ }
+
+ private List<Throwable> validateAllMethods(Class<?> clazz) {
+ try {
+ new BlockJUnit4ClassRunner(clazz);
+ } catch (InitializationError e) {
+ return e.getCauses();
+ }
+ return Collections.emptyList();
+ }
+
+ static public class IgnoredTest {
+ @Test public void valid() {}
+ @Ignore @Test public void ignored() {}
+ @Ignore("For testing purposes") @Test public void withReason() {}
+ }
+
+ @Test public void ignoreRunner() {
+ JUnitCore runner= new JUnitCore();
+ Result result= runner.run(IgnoredTest.class);
+ assertEquals(2, result.getIgnoreCount());
+ assertEquals(1, result.getRunCount());
+ }
+
+ @Test public void compatibility() {
+ TestResult result= new TestResult();
+ new JUnit4TestAdapter(IgnoredTest.class).run(result);
+ assertEquals(1, result.runCount());
+ }
+
+ public static class Confused {
+ @Test public void a(Object b) {
+ }
+
+ @Test public void a() {
+ }
+ }
+
+ @Test(expected=InitializationError.class) public void overloaded() throws InitializationError {
+ new BlockJUnit4ClassRunner(Confused.class);
+ }
+
+ public static class ConstructorParameter {
+ public ConstructorParameter(Object something) {
+ }
+
+ @Test public void a() {
+ }
+ }
+
+ @Test(expected=InitializationError.class) public void constructorParameter() throws InitializationError {
+ new BlockJUnit4ClassRunner(ConstructorParameter.class);
+ }
+
+ public static class OnlyTestIsIgnored {
+ @Ignore @Test public void ignored() {}
+ }
+
+ @Test public void onlyIgnoredMethodsIsStillFineTestClass() {
+ Result result= JUnitCore.runClasses(OnlyTestIsIgnored.class);
+ assertEquals(0, result.getFailureCount());
+ assertEquals(1, result.getIgnoreCount());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/running/methods/TimeoutTest.java b/junit4/src/test/java/org/junit/tests/running/methods/TimeoutTest.java
new file mode 100644
index 0000000..777b0bd
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/running/methods/TimeoutTest.java
@@ -0,0 +1,170 @@
+package org.junit.tests.running.methods;
+
+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.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import junit.framework.JUnit4TestAdapter;
+import junit.framework.TestResult;
+import org.junit.After;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+
+public class TimeoutTest {
+
+ static public class FailureWithTimeoutTest {
+ @Test(timeout= 1000) public void failure() {
+ fail();
+ }
+ }
+
+ @Test public void failureWithTimeout() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(FailureWithTimeoutTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ assertEquals(AssertionError.class, result.getFailures().get(0).getException().getClass());
+ }
+
+ static public class FailureWithTimeoutRunTimeExceptionTest {
+ @Test(timeout= 1000) public void failure() {
+ throw new NullPointerException();
+ }
+ }
+
+ @Test public void failureWithTimeoutRunTimeException() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(FailureWithTimeoutRunTimeExceptionTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ assertEquals(NullPointerException.class, result.getFailures().get(0).getException().getClass());
+ }
+
+ static public class SuccessWithTimeoutTest {
+ @Test(timeout= 1000) public void success() {
+ }
+ }
+
+ @Test public void successWithTimeout() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(SuccessWithTimeoutTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(0, result.getFailureCount());
+ }
+
+ static public class TimeoutFailureTest {
+ @Test(timeout= 100) public void success() throws InterruptedException {
+ Thread.sleep(40000);
+ }
+ }
+
+ @Ignore("was breaking gump")
+ @Test public void timeoutFailure() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(TimeoutFailureTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ assertEquals(InterruptedException.class, result.getFailures().get(0).getException().getClass());
+ }
+
+ static public class InfiniteLoopTest {
+ @Test(timeout= 100) public void failure() {
+ infiniteLoop();
+ }
+
+ private void infiniteLoop() {
+ for(;;)
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+
+ @Test public void infiniteLoop() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(InfiniteLoopTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ Throwable exception= result.getFailures().get(0).getException();
+ assertTrue(exception.getMessage().contains("test timed out after 100 milliseconds"));
+ }
+
+ static public class ImpatientLoopTest {
+ @Test(timeout= 1) public void failure() {
+ infiniteLoop();
+ }
+
+ private void infiniteLoop() {
+ for(;;);
+ }
+ }
+
+ @Ignore("This breaks sporadically with time differences just slightly more than 200ms")
+ @Test public void infiniteLoopRunsForApproximatelyLengthOfTimeout() throws Exception {
+ // "prime the pump": running these beforehand makes the runtimes more predictable
+ // (because of class loading?)
+ JUnitCore.runClasses(InfiniteLoopTest.class, ImpatientLoopTest.class);
+ long longTime= runAndTime(InfiniteLoopTest.class);
+ long shortTime= runAndTime(ImpatientLoopTest.class);
+ long difference= longTime - shortTime;
+ assertTrue(String.format("Difference was %sms", difference), difference < 200);
+ }
+
+ private long runAndTime(Class<?> clazz) {
+ JUnitCore core= new JUnitCore();
+ long startTime= System.currentTimeMillis();
+ core.run(clazz);
+ long totalTime = System.currentTimeMillis() - startTime;
+ return totalTime;
+ }
+
+ @Test public void stalledThreadAppearsInStackTrace() throws Exception {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(InfiniteLoopTest.class);
+ assertEquals(1, result.getRunCount());
+ assertEquals(1, result.getFailureCount());
+ Throwable exception= result.getFailures().get(0).getException();
+ Writer buffer= new StringWriter();
+ PrintWriter writer= new PrintWriter(buffer);
+ exception.printStackTrace(writer);
+ assertThat(buffer.toString(), containsString("infiniteLoop")); // Make sure we have the stalled frame on the stack somewhere
+ }
+
+ @Test public void compatibility() {
+ TestResult result= new TestResult();
+ new JUnit4TestAdapter(InfiniteLoopTest.class).run(result);
+ assertEquals(1, result.errorCount());
+ }
+
+ public static class WillTimeOut {
+ static boolean afterWasCalled= false;
+
+ @Test(timeout=1) public void test() {
+ for(;;)
+ try {
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ // ok, tests are over
+ }
+ }
+
+ @After public void after() {
+ afterWasCalled= true;
+ }
+ }
+
+ @Test public void makeSureAfterIsCalledAfterATimeout() {
+ JUnitCore.runClasses(WillTimeOut.class);
+ assertThat(WillTimeOut.afterWasCalled, is(true));
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java b/junit4/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java
new file mode 100644
index 0000000..ff61822
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java
@@ -0,0 +1,68 @@
+package org.junit.tests.validation;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.internal.runners.JUnit4ClassRunner;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.notification.Failure;
+
+@SuppressWarnings("deprecation")
+public class BadlyFormedClassesTest {
+ public static class FaultyConstructor {
+ public FaultyConstructor() throws Exception {
+ throw new Exception("Thrown during construction");
+ }
+
+ @Test
+ public void someTest() {
+ /*
+ * Empty test just to fool JUnit and IDEs into running this class as
+ * a JUnit test
+ */
+ }
+ };
+
+ @RunWith(JUnit4ClassRunner.class)
+ public static class BadBeforeMethodWithLegacyRunner {
+ @Before
+ void before() {
+
+ }
+
+ @Test
+ public void someTest() {
+ }
+ };
+
+ public static class NoTests {
+ // class without tests
+ }
+
+ @Test
+ public void constructorException() {
+ String message= exceptionMessageFrom(FaultyConstructor.class);
+ assertEquals("Thrown during construction", message);
+ }
+
+ @Test
+ public void noRunnableMethods() {
+ assertEquals("No runnable methods", exceptionMessageFrom(NoTests.class));
+ }
+
+ @Test
+ public void badBeforeMethodWithLegacyRunner() {
+ assertEquals("Method before should be public",
+ exceptionMessageFrom(BadBeforeMethodWithLegacyRunner.class));
+ }
+
+ private String exceptionMessageFrom(Class<?> testClass) {
+ JUnitCore core= new JUnitCore();
+ Result result= core.run(testClass);
+ Failure failure= result.getFailures().get(0);
+ String message= failure.getException().getMessage();
+ return message;
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/validation/FailedConstructionTest.java b/junit4/src/test/java/org/junit/tests/validation/FailedConstructionTest.java
new file mode 100644
index 0000000..7d2ab1e
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/validation/FailedConstructionTest.java
@@ -0,0 +1,28 @@
+package org.junit.tests.validation;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.notification.Failure;
+
+public class FailedConstructionTest {
+ public static class CantConstruct {
+ public CantConstruct() {
+ throw new RuntimeException();
+ }
+
+ @Test
+ public void foo() {
+ }
+ }
+
+ @Test
+ public void failedConstructionIsTestFailure() {
+ Result result= JUnitCore.runClasses(CantConstruct.class);
+ Failure failure= result.getFailures().get(0);
+ Description expected= Description.createTestDescription(CantConstruct.class, "foo");
+ Assert.assertEquals(expected, failure.getDescription());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/validation/InaccessibleBaseClassTest.java b/junit4/src/test/java/org/junit/tests/validation/InaccessibleBaseClassTest.java
new file mode 100644
index 0000000..0677dd8
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/validation/InaccessibleBaseClassTest.java
@@ -0,0 +1,13 @@
+package org.junit.tests.validation;
+
+import org.junit.Test;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.InitializationError;
+import org.junit.tests.validation.anotherpackage.Sub;
+
+public class InaccessibleBaseClassTest {
+ @Test(expected= InitializationError.class)
+ public void inaccessibleBaseClassIsCaughtAtValidation() throws InitializationError {
+ new BlockJUnit4ClassRunner(Sub.class);
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/validation/ValidationTest.java b/junit4/src/test/java/org/junit/tests/validation/ValidationTest.java
new file mode 100644
index 0000000..3251705
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/validation/ValidationTest.java
@@ -0,0 +1,34 @@
+package org.junit.tests.validation;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+
+public class ValidationTest {
+ public static class WrongBeforeClass {
+ @BeforeClass
+ protected int a() {
+ return 0;
+ }
+ }
+
+ @Test
+ public void initializationErrorIsOnCorrectClass() {
+ assertEquals(WrongBeforeClass.class.getName(),
+ Request.aClass(WrongBeforeClass.class).getRunner().getDescription().getDisplayName());
+ }
+
+ public static class NonStaticBeforeClass {
+ @BeforeClass public void before() {}
+ @Test public void hereBecauseEveryTestClassNeedsATest() {}
+ }
+
+ @Test
+ public void nonStaticBeforeClass() {
+ Result result= JUnitCore.runClasses(NonStaticBeforeClass.class);
+ assertEquals("Method before() should be static", result.getFailures().get(0).getMessage());
+ }
+}
diff --git a/junit4/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java b/junit4/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java
new file mode 100644
index 0000000..44d6c76
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java
@@ -0,0 +1,5 @@
+package org.junit.tests.validation.anotherpackage;
+
+public class Sub extends Super {
+
+}
diff --git a/junit4/src/test/java/org/junit/tests/validation/anotherpackage/Super.java b/junit4/src/test/java/org/junit/tests/validation/anotherpackage/Super.java
new file mode 100644
index 0000000..ba1cfe4
--- /dev/null
+++ b/junit4/src/test/java/org/junit/tests/validation/anotherpackage/Super.java
@@ -0,0 +1,7 @@
+package org.junit.tests.validation.anotherpackage;
+
+import org.junit.Test;
+
+class Super {
+ @Test public void a() {}
+}