From 4eceb95409e844fdc33c9c706e1dc307bfd40303 Mon Sep 17 00:00:00 2001 From: Yohann Roussel Date: Wed, 19 Mar 2014 16:25:37 +0100 Subject: Initial Jack import. Change-Id: I953cf0a520195a7187d791b2885848ad0d5a9b43 --- junit4/src/test/java/junit/samples/AllTests.java | 22 + junit4/src/test/java/junit/samples/ListTest.java | 63 +++ junit4/src/test/java/junit/samples/SimpleTest.java | 68 +++ .../src/test/java/junit/samples/money/IMoney.java | 45 ++ .../src/test/java/junit/samples/money/Money.java | 78 ++++ .../test/java/junit/samples/money/MoneyBag.java | 124 +++++ .../test/java/junit/samples/money/MoneyTest.java | 143 ++++++ .../java/junit/samples/money/package-info.java | 4 + .../src/test/java/junit/samples/package-info.java | 4 + junit4/src/test/java/junit/tests/AllTests.java | 23 + junit4/src/test/java/junit/tests/WasRun.java | 15 + .../junit/tests/extensions/ActiveTestTest.java | 64 +++ .../test/java/junit/tests/extensions/AllTests.java | 23 + .../java/junit/tests/extensions/ExtensionTest.java | 98 ++++ .../junit/tests/extensions/RepeatedTestTest.java | 63 +++ .../java/junit/tests/extensions/package-info.java | 4 + .../test/java/junit/tests/framework/AllTests.java | 32 ++ .../java/junit/tests/framework/AssertTest.java | 171 +++++++ .../tests/framework/AssertionFailedErrorTest.java | 23 + .../tests/framework/ComparisonCompactorTest.java | 102 ++++ .../tests/framework/ComparisonFailureTest.java | 47 ++ .../tests/framework/DoublePrecisionAssertTest.java | 55 +++ .../test/java/junit/tests/framework/Failure.java | 14 + .../junit/tests/framework/FloatAssertTest.java | 63 +++ .../junit/tests/framework/InheritedTestCase.java | 9 + .../junit/tests/framework/NoArgTestCaseTest.java | 9 + .../junit/tests/framework/NoTestCaseClass.java | 10 + .../java/junit/tests/framework/NoTestCases.java | 11 + .../junit/tests/framework/NotPublicTestCase.java | 13 + .../junit/tests/framework/NotVoidTestCase.java | 14 + .../java/junit/tests/framework/OneTestCase.java | 15 + .../junit/tests/framework/OverrideTestCase.java | 10 + .../test/java/junit/tests/framework/Success.java | 17 + .../test/java/junit/tests/framework/SuiteTest.java | 105 +++++ .../java/junit/tests/framework/TestCaseTest.java | 190 ++++++++ .../junit/tests/framework/TestImplementorTest.java | 54 +++ .../junit/tests/framework/TestListenerTest.java | 73 +++ .../java/junit/tests/framework/ThreeTestCases.java | 15 + .../java/junit/tests/framework/package-info.java | 4 + junit4/src/test/java/junit/tests/package-info.java | 4 + .../src/test/java/junit/tests/runner/AllTests.java | 31 ++ .../junit/tests/runner/BaseTestRunnerTest.java | 53 +++ .../test/java/junit/tests/runner/ResultTest.java | 37 ++ .../java/junit/tests/runner/StackFilterTest.java | 46 ++ .../java/junit/tests/runner/TextFeedbackTest.java | 109 +++++ .../tests/runner/TextRunnerSingleMethodTest.java | 39 ++ .../java/junit/tests/runner/TextRunnerTest.java | 61 +++ .../test/java/junit/tests/runner/package-info.java | 4 + .../src/test/java/org/junit/samples/ListTest.java | 77 +++ .../test/java/org/junit/samples/SimpleTest.java | 41 ++ .../java/org/junit/samples/money/MoneyTest.java | 158 +++++++ .../java/org/junit/samples/money/package-info.java | 7 + .../test/java/org/junit/samples/package-info.java | 6 + junit4/src/test/java/org/junit/tests/AllTests.java | 163 +++++++ .../java/org/junit/tests/ObjectContractTest.java | 46 ++ .../src/test/java/org/junit/tests/TestSystem.java | 31 ++ .../org/junit/tests/assertion/AssertionTest.java | 486 +++++++++++++++++++ .../java/org/junit/tests/assertion/BothTest.java | 71 +++ .../java/org/junit/tests/assertion/EachTest.java | 13 + .../assertion/MultipleFailureExceptionTest.java | 60 +++ .../tests/deprecated/JUnit4ClassRunnerTest.java | 54 +++ .../description/AnnotatedDescriptionTest.java | 96 ++++ .../tests/description/SuiteDescriptionTest.java | 35 ++ .../tests/description/TestDescriptionTest.java | 11 + .../junit/tests/experimental/AssumptionTest.java | 177 +++++++ .../AssumptionViolatedExceptionTest.java | 52 +++ .../tests/experimental/ExperimentalTests.java | 28 ++ .../org/junit/tests/experimental/MatcherTest.java | 43 ++ .../categories/CategoriesAndParameterizedTest.java | 123 +++++ .../experimental/categories/CategoryTest.java | 254 ++++++++++ .../tests/experimental/max/DescriptionTest.java | 24 + .../tests/experimental/max/JUnit38SortingTest.java | 53 +++ .../tests/experimental/max/MaxStarterTest.java | 293 ++++++++++++ .../experimental/parallel/ParallelClassTest.java | 54 +++ .../experimental/parallel/ParallelMethodTest.java | 44 ++ .../experimental/results/PrintableResultTest.java | 51 ++ .../experimental/results/ResultMatchersTest.java | 21 + .../rules/BlockJUnit4ClassRunnerOverrideTest.java | 93 ++++ .../tests/experimental/rules/ClassRulesTest.java | 101 ++++ .../rules/ExpectedExceptionRuleTest.java | 232 +++++++++ .../rules/ExternalResourceRuleTest.java | 37 ++ .../experimental/rules/LoggingTestWatcher.java | 32 ++ .../tests/experimental/rules/MethodRulesTest.java | 275 +++++++++++ .../tests/experimental/rules/NameRulesTest.java | 50 ++ .../tests/experimental/rules/RuleChainTest.java | 60 +++ .../experimental/rules/RuleFieldValidatorTest.java | 96 ++++ .../experimental/rules/TempFolderRuleTest.java | 200 ++++++++ .../tests/experimental/rules/TestRuleTest.java | 289 ++++++++++++ .../tests/experimental/rules/TestWatcherTest.java | 52 +++ .../tests/experimental/rules/TestWatchmanTest.java | 72 +++ .../tests/experimental/rules/TimeoutRuleTest.java | 39 ++ .../tests/experimental/rules/VerifierRuleTest.java | 133 ++++++ .../theories/AllMembersSupplierTest.java | 34 ++ .../theories/ParameterSignatureTest.java | 57 +++ .../theories/ParameterizedAssertionErrorTest.java | 75 +++ .../theories/extendingwithstubs/Correspondent.java | 7 + .../theories/extendingwithstubs/Guesser.java | 122 +++++ .../theories/extendingwithstubs/GuesserQueue.java | 57 +++ .../theories/extendingwithstubs/MethodCall.java | 54 +++ .../extendingwithstubs/ReguessableValue.java | 16 + .../extendingwithstubs/StringableObject.java | 27 ++ .../theories/extendingwithstubs/Stub.java | 8 + .../extendingwithstubs/StubbedTheories.java | 65 +++ .../extendingwithstubs/StubbedTheoriesTest.java | 1 + .../runner/SuccessfulWithDataPointFields.java | 204 ++++++++ .../theories/runner/TheoriesPerformanceTest.java | 37 ++ .../runner/UnsuccessfulWithDataPointFields.java | 126 +++++ .../theories/runner/WhenNoParametersMatch.java | 50 ++ .../theories/runner/WithDataPointMethod.java | 152 ++++++ .../runner/WithExtendedParameterSources.java | 146 ++++++ .../theories/runner/WithOnlyTestAnnotations.java | 80 ++++ ...nresolvedGenericTypeVariablesOnTheoryParms.java | 177 +++++++ .../runners/statements/FailOnTimeoutTest.java | 110 +++++ .../tests/junit3compatibility/AllTestsTest.java | 81 ++++ .../junit3compatibility/ClassRequestTest.java | 19 + .../ForwardCompatibilityPrintingTest.java | 89 ++++ .../ForwardCompatibilityTest.java | 222 +++++++++ ...nitializationErrorForwardCompatibilityTest.java | 100 ++++ .../JUnit38ClassRunnerTest.java | 79 ++++ .../OldTestClassAdaptingListenerTest.java | 27 ++ .../junit/tests/junit3compatibility/OldTests.java | 11 + .../tests/junit3compatibility/SuiteMethodTest.java | 123 +++++ .../org/junit/tests/listening/ListenerTest.java | 33 ++ .../java/org/junit/tests/listening/RunnerTest.java | 69 +++ .../junit/tests/listening/TestListenerTest.java | 63 +++ .../junit/tests/listening/TextListenerTest.java | 65 +++ .../org/junit/tests/listening/UserStopTest.java | 28 ++ .../org/junit/tests/manipulation/FilterTest.java | 49 ++ .../junit/tests/manipulation/FilterableTest.java | 62 +++ .../junit/tests/manipulation/SingleMethodTest.java | 168 +++++++ .../org/junit/tests/manipulation/SortableTest.java | 149 ++++++ .../test/java/org/junit/tests/package-info.java | 8 + .../classes/BlockJUnit4ClassRunnerTest.java | 33 ++ .../junit/tests/running/classes/EnclosedTest.java | 40 ++ .../tests/running/classes/IgnoreClassTest.java | 26 ++ .../running/classes/ParameterizedTestTest.java | 216 +++++++++ .../running/classes/ParentRunnerFilteringTest.java | 171 +++++++ .../tests/running/classes/ParentRunnerTest.java | 139 ++++++ .../junit/tests/running/classes/RunWithTest.java | 85 ++++ .../org/junit/tests/running/classes/SuiteTest.java | 167 +++++++ .../junit/tests/running/classes/TestClassTest.java | 121 +++++ .../running/classes/UseSuiteAsASuperclassTest.java | 44 ++ .../junit/tests/running/core/CommandLineTest.java | 67 +++ .../core/JUnitCoreReturnsCorrectExitCodeTest.java | 39 ++ .../junit/tests/running/core/SystemExitTest.java | 30 ++ .../tests/running/methods/AnnotationTest.java | 520 +++++++++++++++++++++ .../junit/tests/running/methods/ExpectedTest.java | 58 +++ .../tests/running/methods/InheritedTestTest.java | 31 ++ .../methods/ParameterizedTestMethodTest.java | 102 ++++ .../tests/running/methods/TestMethodTest.java | 147 ++++++ .../junit/tests/running/methods/TimeoutTest.java | 170 +++++++ .../tests/validation/BadlyFormedClassesTest.java | 68 +++ .../tests/validation/FailedConstructionTest.java | 28 ++ .../validation/InaccessibleBaseClassTest.java | 13 + .../org/junit/tests/validation/ValidationTest.java | 34 ++ .../junit/tests/validation/anotherpackage/Sub.java | 5 + .../tests/validation/anotherpackage/Super.java | 7 + 157 files changed, 12025 insertions(+) create mode 100644 junit4/src/test/java/junit/samples/AllTests.java create mode 100644 junit4/src/test/java/junit/samples/ListTest.java create mode 100644 junit4/src/test/java/junit/samples/SimpleTest.java create mode 100644 junit4/src/test/java/junit/samples/money/IMoney.java create mode 100644 junit4/src/test/java/junit/samples/money/Money.java create mode 100644 junit4/src/test/java/junit/samples/money/MoneyBag.java create mode 100644 junit4/src/test/java/junit/samples/money/MoneyTest.java create mode 100644 junit4/src/test/java/junit/samples/money/package-info.java create mode 100644 junit4/src/test/java/junit/samples/package-info.java create mode 100644 junit4/src/test/java/junit/tests/AllTests.java create mode 100644 junit4/src/test/java/junit/tests/WasRun.java create mode 100644 junit4/src/test/java/junit/tests/extensions/ActiveTestTest.java create mode 100644 junit4/src/test/java/junit/tests/extensions/AllTests.java create mode 100644 junit4/src/test/java/junit/tests/extensions/ExtensionTest.java create mode 100644 junit4/src/test/java/junit/tests/extensions/RepeatedTestTest.java create mode 100644 junit4/src/test/java/junit/tests/extensions/package-info.java create mode 100644 junit4/src/test/java/junit/tests/framework/AllTests.java create mode 100644 junit4/src/test/java/junit/tests/framework/AssertTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/ComparisonCompactorTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/ComparisonFailureTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/Failure.java create mode 100644 junit4/src/test/java/junit/tests/framework/FloatAssertTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/InheritedTestCase.java create mode 100644 junit4/src/test/java/junit/tests/framework/NoArgTestCaseTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/NoTestCaseClass.java create mode 100644 junit4/src/test/java/junit/tests/framework/NoTestCases.java create mode 100644 junit4/src/test/java/junit/tests/framework/NotPublicTestCase.java create mode 100644 junit4/src/test/java/junit/tests/framework/NotVoidTestCase.java create mode 100644 junit4/src/test/java/junit/tests/framework/OneTestCase.java create mode 100644 junit4/src/test/java/junit/tests/framework/OverrideTestCase.java create mode 100644 junit4/src/test/java/junit/tests/framework/Success.java create mode 100644 junit4/src/test/java/junit/tests/framework/SuiteTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/TestCaseTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/TestImplementorTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/TestListenerTest.java create mode 100644 junit4/src/test/java/junit/tests/framework/ThreeTestCases.java create mode 100644 junit4/src/test/java/junit/tests/framework/package-info.java create mode 100644 junit4/src/test/java/junit/tests/package-info.java create mode 100644 junit4/src/test/java/junit/tests/runner/AllTests.java create mode 100644 junit4/src/test/java/junit/tests/runner/BaseTestRunnerTest.java create mode 100644 junit4/src/test/java/junit/tests/runner/ResultTest.java create mode 100644 junit4/src/test/java/junit/tests/runner/StackFilterTest.java create mode 100644 junit4/src/test/java/junit/tests/runner/TextFeedbackTest.java create mode 100644 junit4/src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java create mode 100644 junit4/src/test/java/junit/tests/runner/TextRunnerTest.java create mode 100644 junit4/src/test/java/junit/tests/runner/package-info.java create mode 100644 junit4/src/test/java/org/junit/samples/ListTest.java create mode 100644 junit4/src/test/java/org/junit/samples/SimpleTest.java create mode 100644 junit4/src/test/java/org/junit/samples/money/MoneyTest.java create mode 100644 junit4/src/test/java/org/junit/samples/money/package-info.java create mode 100644 junit4/src/test/java/org/junit/samples/package-info.java create mode 100644 junit4/src/test/java/org/junit/tests/AllTests.java create mode 100644 junit4/src/test/java/org/junit/tests/ObjectContractTest.java create mode 100644 junit4/src/test/java/org/junit/tests/TestSystem.java create mode 100644 junit4/src/test/java/org/junit/tests/assertion/AssertionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/assertion/BothTest.java create mode 100644 junit4/src/test/java/org/junit/tests/assertion/EachTest.java create mode 100644 junit4/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/description/TestDescriptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/AssumptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/ExperimentalTests.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/MatcherTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/categories/CategoryTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/BlockJUnit4ClassRunnerOverrideTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/ClassRulesTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionRuleTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/ExternalResourceRuleTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/LoggingTestWatcher.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/NameRulesTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/RuleFieldValidatorTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/TestWatchmanTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/AllMembersSupplierTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java create mode 100644 junit4/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java create mode 100644 junit4/src/test/java/org/junit/tests/internal/runners/statements/FailOnTimeoutTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/OldTests.java create mode 100644 junit4/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java create mode 100644 junit4/src/test/java/org/junit/tests/listening/ListenerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/listening/RunnerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/listening/TestListenerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/listening/TextListenerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/listening/UserStopTest.java create mode 100644 junit4/src/test/java/org/junit/tests/manipulation/FilterTest.java create mode 100644 junit4/src/test/java/org/junit/tests/manipulation/FilterableTest.java create mode 100644 junit4/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java create mode 100644 junit4/src/test/java/org/junit/tests/manipulation/SortableTest.java create mode 100644 junit4/src/test/java/org/junit/tests/package-info.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/EnclosedTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/RunWithTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/SuiteTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/TestClassTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/core/CommandLineTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/core/SystemExitTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/methods/AnnotationTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/methods/ExpectedTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/methods/TestMethodTest.java create mode 100644 junit4/src/test/java/org/junit/tests/running/methods/TimeoutTest.java create mode 100644 junit4/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java create mode 100644 junit4/src/test/java/org/junit/tests/validation/FailedConstructionTest.java create mode 100644 junit4/src/test/java/org/junit/tests/validation/InaccessibleBaseClassTest.java create mode 100644 junit4/src/test/java/org/junit/tests/validation/ValidationTest.java create mode 100644 junit4/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java create mode 100644 junit4/src/test/java/org/junit/tests/validation/anotherpackage/Super.java (limited to 'junit4/src/test') diff --git a/junit4/src/test/java/junit/samples/AllTests.java b/junit4/src/test/java/junit/samples/AllTests.java new file mode 100644 index 0000000..2fb7628 --- /dev/null +++ b/junit4/src/test/java/junit/samples/AllTests.java @@ -0,0 +1,22 @@ +package junit.samples; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * TestSuite that runs all the sample tests + * + */ +public class AllTests { + + public static void main (String[] args) { + junit.textui.TestRunner.run (suite()); + } + public static Test suite ( ) { + TestSuite suite= new TestSuite("All JUnit Tests"); + suite.addTest(ListTest.suite()); + suite.addTest(new TestSuite(junit.samples.money.MoneyTest.class)); + suite.addTest(junit.tests.AllTests.suite()); + return suite; + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/ListTest.java b/junit4/src/test/java/junit/samples/ListTest.java new file mode 100644 index 0000000..eac850d --- /dev/null +++ b/junit4/src/test/java/junit/samples/ListTest.java @@ -0,0 +1,63 @@ +package junit.samples; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * A sample test case, testing {@link java.util.Vector}. + * + */ +public class ListTest extends TestCase { + protected List fEmpty; + protected List fFull; + + public static void main (String[] args) { + junit.textui.TestRunner.run (suite()); + } + @Override + protected void setUp() { + fEmpty= new ArrayList(); + fFull= new ArrayList(); + fFull.add(1); + fFull.add(2); + fFull.add(3); + } + public static Test suite() { + return new TestSuite(ListTest.class); + } + public void testCapacity() { + int size= fFull.size(); + for (int i= 0; i < 100; i++) + fFull.add(new Integer(i)); + assertTrue(fFull.size() == 100+size); + } + public void testContains() { + assertTrue(fFull.contains(1)); + assertTrue(!fEmpty.contains(1)); + } + public void testElementAt() { + int i= fFull.get(0); + assertTrue(i == 1); + + try { + fFull.get(fFull.size()); + } catch (IndexOutOfBoundsException e) { + return; + } + fail("Should raise an ArrayIndexOutOfBoundsException"); + } + public void testRemoveAll() { + fFull.removeAll(fFull); + fEmpty.removeAll(fEmpty); + assertTrue(fFull.isEmpty()); + assertTrue(fEmpty.isEmpty()); + } + public void testRemoveElement() { + fFull.remove(new Integer(3)); + assertTrue(!fFull.contains(3) ); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/SimpleTest.java b/junit4/src/test/java/junit/samples/SimpleTest.java new file mode 100644 index 0000000..f745021 --- /dev/null +++ b/junit4/src/test/java/junit/samples/SimpleTest.java @@ -0,0 +1,68 @@ +package junit.samples; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Some simple tests. + * + */ +public class SimpleTest extends TestCase { + protected int fValue1; + protected int fValue2; + + @Override + protected void setUp() { + fValue1= 2; + fValue2= 3; + } + public static Test suite() { + + /* + * the type safe way + * + TestSuite suite= new TestSuite(); + suite.addTest( + new SimpleTest("add") { + protected void runTest() { testAdd(); } + } + ); + + suite.addTest( + new SimpleTest("testDivideByZero") { + protected void runTest() { testDivideByZero(); } + } + ); + return suite; + */ + + /* + * the dynamic way + */ + return new TestSuite(SimpleTest.class); + } + public void testAdd() { + double result= fValue1 + fValue2; + // forced failure result == 5 + assertTrue(result == 6); + } + + public int unused; + public void testDivideByZero() { + int zero= 0; + int result= 8/zero; + unused= result; // avoid warning for not using result + } + public void testEquals() { + assertEquals(12, 12); + assertEquals(12L, 12L); + assertEquals(new Long(12), new Long(12)); + + assertEquals("Size", 12, 13); + assertEquals("Capacity", 12.0, 11.99, 0.0); + } + public static void main (String[] args) { + junit.textui.TestRunner.run(suite()); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/money/IMoney.java b/junit4/src/test/java/junit/samples/money/IMoney.java new file mode 100644 index 0000000..b8f9496 --- /dev/null +++ b/junit4/src/test/java/junit/samples/money/IMoney.java @@ -0,0 +1,45 @@ +package junit.samples.money; + +/** + * The common interface for simple Monies and MoneyBags + * + */ +public interface IMoney { + /** + * Adds a money to this money. + */ + public abstract IMoney add(IMoney m); + /** + * Adds a simple Money to this money. This is a helper method for + * implementing double dispatch + */ + public abstract IMoney addMoney(Money m); + /** + * Adds a MoneyBag to this money. This is a helper method for + * implementing double dispatch + */ + public abstract IMoney addMoneyBag(MoneyBag s); + /** + * Tests whether this money is zero + */ + public abstract boolean isZero(); + /** + * Multiplies a money by the given factor. + */ + public abstract IMoney multiply(int factor); + /** + * Negates this money. + */ + public abstract IMoney negate(); + /** + * Subtracts a money from this money. + */ + public abstract IMoney subtract(IMoney m); + /** + * Append this to a MoneyBag m. + * appendTo() needs to be public because it is used + * polymorphically, but it should not be used by clients + * because it modifies the argument m. + */ + public abstract void appendTo(MoneyBag m); +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/money/Money.java b/junit4/src/test/java/junit/samples/money/Money.java new file mode 100644 index 0000000..3d8c2fd --- /dev/null +++ b/junit4/src/test/java/junit/samples/money/Money.java @@ -0,0 +1,78 @@ +package junit.samples.money; + +/** + * A simple Money. + * + */ +public class Money implements IMoney { + + private int fAmount; + private String fCurrency; + + /** + * Constructs a money from the given amount and currency. + */ + public Money(int amount, String currency) { + fAmount= amount; + fCurrency= currency; + } + /** + * Adds a money to this money. Forwards the request to the addMoney helper. + */ + public IMoney add(IMoney m) { + return m.addMoney(this); + } + public IMoney addMoney(Money m) { + if (m.currency().equals(currency()) ) + return new Money(amount()+m.amount(), currency()); + return MoneyBag.create(this, m); + } + public IMoney addMoneyBag(MoneyBag s) { + return s.addMoney(this); + } + public int amount() { + return fAmount; + } + public String currency() { + return fCurrency; + } + @Override + public boolean equals(Object anObject) { + if (isZero()) + if (anObject instanceof IMoney) + return ((IMoney)anObject).isZero(); + if (anObject instanceof Money) { + Money aMoney= (Money)anObject; + return aMoney.currency().equals(currency()) + && amount() == aMoney.amount(); + } + return false; + } + @Override + public int hashCode() { + if (fAmount == 0) + return 0; + return fCurrency.hashCode()+fAmount; + } + public boolean isZero() { + return amount() == 0; + } + public IMoney multiply(int factor) { + return new Money(amount()*factor, currency()); + } + public IMoney negate() { + return new Money(-amount(), currency()); + } + public IMoney subtract(IMoney m) { + return add(m.negate()); + } + @Override + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("["+amount()+" "+currency()+"]"); + return buffer.toString(); + } + public /*this makes no sense*/ void appendTo(MoneyBag m) { + m.appendMoney(this); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/money/MoneyBag.java b/junit4/src/test/java/junit/samples/money/MoneyBag.java new file mode 100644 index 0000000..edc73b5 --- /dev/null +++ b/junit4/src/test/java/junit/samples/money/MoneyBag.java @@ -0,0 +1,124 @@ +package junit.samples.money; + +import java.util.ArrayList; +import java.util.List; + +/** + * A MoneyBag defers exchange rate conversions. For example adding + * 12 Swiss Francs to 14 US Dollars is represented as a bag + * containing the two Monies 12 CHF and 14 USD. Adding another + * 10 Swiss francs gives a bag with 22 CHF and 14 USD. Due to + * the deferred exchange rate conversion we can later value a + * MoneyBag with different exchange rates. + * + * A MoneyBag is represented as a list of Monies and provides + * different constructors to create a MoneyBag. + */ +public class MoneyBag implements IMoney { + private List fMonies= new ArrayList(5); + + public static IMoney create(IMoney m1, IMoney m2) { + MoneyBag result= new MoneyBag(); + m1.appendTo(result); + m2.appendTo(result); + return result.simplify(); + } + public IMoney add(IMoney m) { + return m.addMoneyBag(this); + } + public IMoney addMoney(Money m) { + return MoneyBag.create(m, this); + } + public IMoney addMoneyBag(MoneyBag s) { + return MoneyBag.create(s, this); + } + void appendBag(MoneyBag aBag) { + for (Money each : aBag.fMonies) + appendMoney(each); + } + void appendMoney(Money aMoney) { + if (aMoney.isZero()) return; + IMoney old= findMoney(aMoney.currency()); + if (old == null) { + fMonies.add(aMoney); + return; + } + fMonies.remove(old); + Money sum= (Money) old.add(aMoney); + if (sum.isZero()) + return; + fMonies.add(sum); + } + @Override + public boolean equals(Object anObject) { + if (isZero()) + if (anObject instanceof IMoney) + return ((IMoney)anObject).isZero(); + + if (anObject instanceof MoneyBag) { + MoneyBag aMoneyBag= (MoneyBag)anObject; + if (aMoneyBag.fMonies.size() != fMonies.size()) + return false; + + for (Money each : fMonies) + if (! aMoneyBag.contains(each)) + return false; + return true; + } + return false; + } + private Money findMoney(String currency) { + for (Money each : fMonies) + if (each.currency().equals(currency)) + return each; + return null; + } + private boolean contains(Money m) { + Money found= findMoney(m.currency()); + if (found == null) return false; + return found.amount() == m.amount(); + } + @Override + public int hashCode() { + int hash= 0; + for (Money each : fMonies) + hash^= each.hashCode(); + return hash; + } + public boolean isZero() { + return fMonies.size() == 0; + } + public IMoney multiply(int factor) { + MoneyBag result= new MoneyBag(); + if (factor != 0) + for (Money each : fMonies) + result.appendMoney((Money) each.multiply(factor)); + return result; + } + public IMoney negate() { + MoneyBag result= new MoneyBag(); + for (Money each : fMonies) + result.appendMoney((Money) each.negate()); + return result; + } + private IMoney simplify() { + if (fMonies.size() == 1) + return fMonies.iterator().next(); + return this; + } + public IMoney subtract(IMoney m) { + return add(m.negate()); + } + @Override + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("{"); + for (Money each : fMonies) + buffer.append(each); + buffer.append("}"); + return buffer.toString(); + } + public void appendTo(MoneyBag m) { + m.appendBag(this); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/money/MoneyTest.java b/junit4/src/test/java/junit/samples/money/MoneyTest.java new file mode 100644 index 0000000..043798d --- /dev/null +++ b/junit4/src/test/java/junit/samples/money/MoneyTest.java @@ -0,0 +1,143 @@ +package junit.samples.money; + +import junit.framework.TestCase; + +public class MoneyTest extends TestCase { + private Money f12CHF; + private Money f14CHF; + private Money f7USD; + private Money f21USD; + + private IMoney fMB1; + private IMoney fMB2; + + public static void main(String args[]) { + junit.textui.TestRunner.run(MoneyTest.class); + } + @Override + protected void setUp() { + f12CHF= new Money(12, "CHF"); + f14CHF= new Money(14, "CHF"); + f7USD= new Money( 7, "USD"); + f21USD= new Money(21, "USD"); + + fMB1= MoneyBag.create(f12CHF, f7USD); + fMB2= MoneyBag.create(f14CHF, f21USD); + } + public void testBagMultiply() { + // {[12 CHF][7 USD]} *2 == {[24 CHF][14 USD]} + IMoney expected= MoneyBag.create(new Money(24, "CHF"), new Money(14, "USD")); + assertEquals(expected, fMB1.multiply(2)); + assertEquals(fMB1, fMB1.multiply(1)); + assertTrue(fMB1.multiply(0).isZero()); + } + public void testBagNegate() { + // {[12 CHF][7 USD]} negate == {[-12 CHF][-7 USD]} + IMoney expected= MoneyBag.create(new Money(-12, "CHF"), new Money(-7, "USD")); + assertEquals(expected, fMB1.negate()); + } + public void testBagSimpleAdd() { + // {[12 CHF][7 USD]} + [14 CHF] == {[26 CHF][7 USD]} + IMoney expected= MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); + assertEquals(expected, fMB1.add(f14CHF)); + } + public void testBagSubtract() { + // {[12 CHF][7 USD]} - {[14 CHF][21 USD] == {[-2 CHF][-14 USD]} + IMoney expected= MoneyBag.create(new Money(-2, "CHF"), new Money(-14, "USD")); + assertEquals(expected, fMB1.subtract(fMB2)); + } + public void testBagSumAdd() { + // {[12 CHF][7 USD]} + {[14 CHF][21 USD]} == {[26 CHF][28 USD]} + IMoney expected= MoneyBag.create(new Money(26, "CHF"), new Money(28, "USD")); + assertEquals(expected, fMB1.add(fMB2)); + } + public void testIsZero() { + assertTrue(fMB1.subtract(fMB1).isZero()); + assertTrue(MoneyBag.create(new Money (0, "CHF"), new Money (0, "USD")).isZero()); + } + public void testMixedSimpleAdd() { + // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} + IMoney expected= MoneyBag.create(f12CHF, f7USD); + assertEquals(expected, f12CHF.add(f7USD)); + } + public void testBagNotEquals() { + IMoney bag= MoneyBag.create(f12CHF, f7USD); + assertFalse(bag.equals(new Money(12, "DEM").add(f7USD))); + } + public void testMoneyBagEquals() { + assertTrue(!fMB1.equals(null)); + + assertEquals(fMB1, fMB1); + IMoney equal= MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); + assertTrue(fMB1.equals(equal)); + assertTrue(!fMB1.equals(f12CHF)); + assertTrue(!f12CHF.equals(fMB1)); + assertTrue(!fMB1.equals(fMB2)); + } + public void testMoneyBagHash() { + IMoney equal= MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); + assertEquals(fMB1.hashCode(), equal.hashCode()); + } + public void testMoneyEquals() { + assertTrue(!f12CHF.equals(null)); + Money equalMoney= new Money(12, "CHF"); + assertEquals(f12CHF, f12CHF); + assertEquals(f12CHF, equalMoney); + assertEquals(f12CHF.hashCode(), equalMoney.hashCode()); + assertTrue(!f12CHF.equals(f14CHF)); + } + public void testMoneyHash() { + assertTrue(!f12CHF.equals(null)); + Money equal= new Money(12, "CHF"); + assertEquals(f12CHF.hashCode(), equal.hashCode()); + } + public void testSimplify() { + IMoney money= MoneyBag.create(new Money(26, "CHF"), new Money(28, "CHF")); + assertEquals(new Money(54, "CHF"), money); + } + public void testNormalize2() { + // {[12 CHF][7 USD]} - [12 CHF] == [7 USD] + Money expected= new Money(7, "USD"); + assertEquals(expected, fMB1.subtract(f12CHF)); + } + public void testNormalize3() { + // {[12 CHF][7 USD]} - {[12 CHF][3 USD]} == [4 USD] + IMoney ms1= MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); + Money expected= new Money(4, "USD"); + assertEquals(expected, fMB1.subtract(ms1)); + } + public void testNormalize4() { + // [12 CHF] - {[12 CHF][3 USD]} == [-3 USD] + IMoney ms1= MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); + Money expected= new Money(-3, "USD"); + assertEquals(expected, f12CHF.subtract(ms1)); + } + public void testPrint() { + assertEquals("[12 CHF]", f12CHF.toString()); + } + public void testSimpleAdd() { + // [12 CHF] + [14 CHF] == [26 CHF] + Money expected= new Money(26, "CHF"); + assertEquals(expected, f12CHF.add(f14CHF)); + } + public void testSimpleBagAdd() { + // [14 CHF] + {[12 CHF][7 USD]} == {[26 CHF][7 USD]} + IMoney expected= MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); + assertEquals(expected, f14CHF.add(fMB1)); + } + public void testSimpleMultiply() { + // [14 CHF] *2 == [28 CHF] + Money expected= new Money(28, "CHF"); + assertEquals(expected, f14CHF.multiply(2)); + } + public void testSimpleNegate() { + // [14 CHF] negate == [-14 CHF] + Money expected= new Money(-14, "CHF"); + assertEquals(expected, f14CHF.negate()); + } + public void testSimpleSubtract() { + // [14 CHF] - [12 CHF] == [2 CHF] + Money expected= new Money(2, "CHF"); + assertEquals(expected, f14CHF.subtract(f12CHF)); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/money/package-info.java b/junit4/src/test/java/junit/samples/money/package-info.java new file mode 100644 index 0000000..eb37dd8 --- /dev/null +++ b/junit4/src/test/java/junit/samples/money/package-info.java @@ -0,0 +1,4 @@ +/** + * Example "Money" for JUnit v3.x. + */ +package junit.samples.money; \ No newline at end of file diff --git a/junit4/src/test/java/junit/samples/package-info.java b/junit4/src/test/java/junit/samples/package-info.java new file mode 100644 index 0000000..7b9ea8f --- /dev/null +++ b/junit4/src/test/java/junit/samples/package-info.java @@ -0,0 +1,4 @@ +/** + * JUnit v3.x examples. + */ +package junit.samples; \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/AllTests.java b/junit4/src/test/java/junit/tests/AllTests.java new file mode 100644 index 0000000..00bbe56 --- /dev/null +++ b/junit4/src/test/java/junit/tests/AllTests.java @@ -0,0 +1,23 @@ +package junit.tests; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * TestSuite that runs all the JUnit tests + * + */ +public class AllTests { + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + + public static Test suite() { + TestSuite suite= new TestSuite("Framework Tests"); + suite.addTest(junit.tests.framework.AllTests.suite()); + suite.addTest(junit.tests.runner.AllTests.suite()); + suite.addTest(junit.tests.extensions.AllTests.suite()); + return suite; + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/WasRun.java b/junit4/src/test/java/junit/tests/WasRun.java new file mode 100644 index 0000000..98b83bb --- /dev/null +++ b/junit4/src/test/java/junit/tests/WasRun.java @@ -0,0 +1,15 @@ +package junit.tests; + +import junit.framework.TestCase; + +/** + * A helper test case for testing whether the testing method + * is run. + */ +public class WasRun extends TestCase { + public boolean fWasRun= false; + @Override + protected void runTest() { + fWasRun= true; + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/extensions/ActiveTestTest.java b/junit4/src/test/java/junit/tests/extensions/ActiveTestTest.java new file mode 100644 index 0000000..48987dd --- /dev/null +++ b/junit4/src/test/java/junit/tests/extensions/ActiveTestTest.java @@ -0,0 +1,64 @@ +package junit.tests.extensions; + +import junit.extensions.ActiveTestSuite; +import junit.extensions.RepeatedTest; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; + +/** + * Testing the ActiveTest support + */ + +public class ActiveTestTest extends TestCase { + + public static class SuccessTest extends TestCase { + @Override + public void runTest() { + } + } + + public void testActiveTest() { + Test test= createActiveTestSuite(); + TestResult result= new TestResult(); + test.run(result); + assertEquals(100, result.runCount()); + assertEquals(0, result.failureCount()); + assertEquals(0, result.errorCount()); + } + + public void testActiveRepeatedTest() { + Test test= new RepeatedTest(createActiveTestSuite(), 5); + TestResult result= new TestResult(); + test.run(result); + assertEquals(500, result.runCount()); + assertEquals(0, result.failureCount()); + assertEquals(0, result.errorCount()); + } + + public void testActiveRepeatedTest0() { + Test test= new RepeatedTest(createActiveTestSuite(), 0); + TestResult result= new TestResult(); + test.run(result); + assertEquals(0, result.runCount()); + assertEquals(0, result.failureCount()); + assertEquals(0, result.errorCount()); + } + + public void testActiveRepeatedTest1() { + Test test= new RepeatedTest(createActiveTestSuite(), 1); + TestResult result= new TestResult(); + test.run(result); + assertEquals(100, result.runCount()); + assertEquals(0, result.failureCount()); + assertEquals(0, result.errorCount()); + } + + ActiveTestSuite createActiveTestSuite() { + ActiveTestSuite suite= new ActiveTestSuite(); + for (int i= 0; i < 100; i++) + suite.addTest(new SuccessTest()); + return suite; + } + +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/extensions/AllTests.java b/junit4/src/test/java/junit/tests/extensions/AllTests.java new file mode 100644 index 0000000..92de10b --- /dev/null +++ b/junit4/src/test/java/junit/tests/extensions/AllTests.java @@ -0,0 +1,23 @@ +package junit.tests.extensions; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * TestSuite that runs all the extension tests + * + */ +public class AllTests { + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + + public static Test suite() { // Collect tests manually because we have to test class collection code + TestSuite suite= new TestSuite("Framework Tests"); + suite.addTestSuite(ExtensionTest.class); + suite.addTestSuite(ActiveTestTest.class); + suite.addTestSuite(RepeatedTestTest.class); + return suite; + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/extensions/ExtensionTest.java b/junit4/src/test/java/junit/tests/extensions/ExtensionTest.java new file mode 100644 index 0000000..d8a5c09 --- /dev/null +++ b/junit4/src/test/java/junit/tests/extensions/ExtensionTest.java @@ -0,0 +1,98 @@ +package junit.tests.extensions; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; +import junit.tests.WasRun; + +/** + * A test case testing the extensions to the testing framework. + * + */ +public class ExtensionTest extends TestCase { + static class TornDown extends TestSetup { + boolean fTornDown= false; + + TornDown(Test test) { + super(test); + } + @Override + protected void tearDown() { + fTornDown= true; + } + } + public void testRunningErrorInTestSetup() { + TestCase test= new TestCase("failure") { + @Override + public void runTest() { + fail(); + } + }; + + TestSetup wrapper= new TestSetup(test); + + TestResult result= new TestResult(); + wrapper.run(result); + assertTrue(!result.wasSuccessful()); + } + public void testRunningErrorsInTestSetup() { + TestCase failure= new TestCase("failure") { + @Override + public void runTest() { + fail(); + } + }; + + TestCase error= new TestCase("error") { + @Override + public void runTest() { + throw new Error(); + } + }; + + TestSuite suite= new TestSuite(); + suite.addTest(failure); + suite.addTest(error); + + TestSetup wrapper= new TestSetup(suite); + + TestResult result= new TestResult(); + wrapper.run(result); + + assertEquals(1, result.failureCount()); + assertEquals(1, result.errorCount()); + } + public void testSetupErrorDontTearDown() { + WasRun test= new WasRun(); + + TornDown wrapper= new TornDown(test) { + @Override + public void setUp() { + fail(); + } + }; + + TestResult result= new TestResult(); + wrapper.run(result); + + assertTrue(!wrapper.fTornDown); + } + public void testSetupErrorInTestSetup() { + WasRun test= new WasRun(); + + TestSetup wrapper= new TestSetup(test) { + @Override + public void setUp() { + fail(); + } + }; + + TestResult result= new TestResult(); + wrapper.run(result); + + assertTrue(!test.fWasRun); + assertTrue(!result.wasSuccessful()); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/extensions/RepeatedTestTest.java b/junit4/src/test/java/junit/tests/extensions/RepeatedTestTest.java new file mode 100644 index 0000000..9e53bfa --- /dev/null +++ b/junit4/src/test/java/junit/tests/extensions/RepeatedTestTest.java @@ -0,0 +1,63 @@ +package junit.tests.extensions; + +import junit.extensions.RepeatedTest; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; + +/** + * Testing the RepeatedTest support. + */ + +public class RepeatedTestTest extends TestCase { + private TestSuite fSuite; + + public static class SuccessTest extends TestCase { + + @Override + public void runTest() { + } + } + + public RepeatedTestTest(String name) { + super(name); + fSuite= new TestSuite(); + fSuite.addTest(new SuccessTest()); + fSuite.addTest(new SuccessTest()); + } + + public void testRepeatedOnce() { + Test test= new RepeatedTest(fSuite, 1); + assertEquals(2, test.countTestCases()); + TestResult result= new TestResult(); + test.run(result); + assertEquals(2, result.runCount()); + } + + public void testRepeatedMoreThanOnce() { + Test test= new RepeatedTest(fSuite, 3); + assertEquals(6, test.countTestCases()); + TestResult result= new TestResult(); + test.run(result); + assertEquals(6, result.runCount()); + } + + public void testRepeatedZero() { + Test test= new RepeatedTest(fSuite, 0); + assertEquals(0, test.countTestCases()); + TestResult result= new TestResult(); + test.run(result); + assertEquals(0, result.runCount()); + } + + public void testRepeatedNegative() { + try { + new RepeatedTest(fSuite, -1); + } catch (IllegalArgumentException e) { + assertTrue(e.getMessage().contains(">=")); + return; + } + fail("Should throw an IllegalArgumentException"); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/extensions/package-info.java b/junit4/src/test/java/junit/tests/extensions/package-info.java new file mode 100644 index 0000000..acc0194 --- /dev/null +++ b/junit4/src/test/java/junit/tests/extensions/package-info.java @@ -0,0 +1,4 @@ +/** + * Tests for the JUnit v3.x extension functionality. + */ +package junit.tests.extensions; \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/AllTests.java b/junit4/src/test/java/junit/tests/framework/AllTests.java new file mode 100644 index 0000000..6ec9891 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/AllTests.java @@ -0,0 +1,32 @@ +package junit.tests.framework; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * TestSuite that runs all the sample tests + * + */ +public class AllTests { + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + + public static Test suite() { + TestSuite suite= new TestSuite("Framework Tests"); + suite.addTestSuite(TestCaseTest.class); + suite.addTest(SuiteTest.suite()); // Tests suite building, so can't use automatic test extraction + suite.addTestSuite(TestListenerTest.class); + suite.addTestSuite(AssertionFailedErrorTest.class); + suite.addTestSuite(AssertTest.class); + suite.addTestSuite(TestImplementorTest.class); + suite.addTestSuite(NoArgTestCaseTest.class); + suite.addTestSuite(ComparisonCompactorTest.class); + suite.addTestSuite(ComparisonFailureTest.class); + suite.addTestSuite(DoublePrecisionAssertTest.class); + suite.addTestSuite(FloatAssertTest.class); + return suite; + } + +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/AssertTest.java b/junit4/src/test/java/junit/tests/framework/AssertTest.java new file mode 100644 index 0000000..de33ff6 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/AssertTest.java @@ -0,0 +1,171 @@ +package junit.tests.framework; + +import junit.framework.AssertionFailedError; +import junit.framework.ComparisonFailure; +import junit.framework.TestCase; + +public class AssertTest extends TestCase { + + /* In the tests that follow, we can't use standard formatting + * for exception tests: + * try { + * somethingThatShouldThrow(); + * fail(); + * catch (AssertionFailedError e) { + * } + * because fail() would never be reported. + */ + public void testFail() { + // Also, we are testing fail, so we can't rely on fail() working. + // We have to throw the exception manually. + try { + fail(); + } catch (AssertionFailedError e) { + return; + } + throw new AssertionFailedError(); + } + + public void testAssertionFailedErrorToStringWithNoMessage() { + // Also, we are testing fail, so we can't rely on fail() working. + // We have to throw the exception manually. + try { + fail(); + } catch (AssertionFailedError e) { + assertEquals("junit.framework.AssertionFailedError", e.toString()); + return; + } + throw new AssertionFailedError(); + } + + public void testAssertionFailedErrorToStringWithMessage() { + // Also, we are testing fail, so we can't rely on fail() working. + // We have to throw the exception manually. + try { + fail("woops!"); + } catch (AssertionFailedError e) { + assertEquals("junit.framework.AssertionFailedError: woops!", e.toString()); + return; + } + throw new AssertionFailedError(); + } + + public void testAssertEquals() { + Object o= new Object(); + assertEquals(o, o); + try { + assertEquals(new Object(), new Object()); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertEqualsNull() { + assertEquals((Object) null, (Object) null); + } + + public void testAssertStringEquals() { + assertEquals("a", "a"); + } + + public void testAssertNullNotEqualsString() { + try { + assertEquals(null, "foo"); + fail(); + } catch (ComparisonFailure e) { + } + } + + public void testAssertStringNotEqualsNull() { + try { + assertEquals("foo", null); + fail(); + } catch (ComparisonFailure e) { + e.getMessage(); // why no assertion? + } + } + + public void testAssertNullNotEqualsNull() { + try { + assertEquals(null, new Object()); + } catch (AssertionFailedError e) { + e.getMessage(); // why no assertion? + return; + } + fail(); + } + + public void testAssertNull() { + assertNull(null); + try { + assertNull(new Object()); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertNotNull() { + assertNotNull(new Object()); + try { + assertNotNull(null); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertTrue() { + assertTrue(true); + try { + assertTrue(false); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertFalse() { + assertFalse(false); + try { + assertFalse(true); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertSame() { + Object o= new Object(); + assertSame(o, o); + try { + assertSame(new Integer(1), new Integer(1)); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertNotSame() { + assertNotSame(new Integer(1), null); + assertNotSame(null, new Integer(1)); + assertNotSame(new Integer(1), new Integer(1)); + try { + Integer obj= new Integer(1); + assertNotSame(obj, obj); + } catch (AssertionFailedError e) { + return; + } + fail(); + } + + public void testAssertNotSameFailsNull() { + try { + assertNotSame(null, null); + } catch (AssertionFailedError e) { + return; + } + fail(); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java b/junit4/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java new file mode 100644 index 0000000..3dd6b1f --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java @@ -0,0 +1,23 @@ +package junit.tests.framework; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +public class AssertionFailedErrorTest extends TestCase { + private static final String ARBITRARY_MESSAGE= "arbitrary message"; + + public void testCreateErrorWithoutMessage() throws Exception { + AssertionFailedError error= new AssertionFailedError(); + assertNull(error.getMessage()); + } + + public void testCreateErrorWithMessage() throws Exception { + AssertionFailedError error= new AssertionFailedError(ARBITRARY_MESSAGE); + assertEquals(ARBITRARY_MESSAGE, error.getMessage()); + } + + public void testCreateErrorWithoutMessageInsteadOfNull() throws Exception { + AssertionFailedError error= new AssertionFailedError(null); + assertEquals("", error.getMessage()); + } +} diff --git a/junit4/src/test/java/junit/tests/framework/ComparisonCompactorTest.java b/junit4/src/test/java/junit/tests/framework/ComparisonCompactorTest.java new file mode 100644 index 0000000..6edaefe --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/ComparisonCompactorTest.java @@ -0,0 +1,102 @@ +package junit.tests.framework; + +import junit.framework.ComparisonCompactor; +import junit.framework.TestCase; + +public class ComparisonCompactorTest extends TestCase { + + public void testMessage() { + String failure= new ComparisonCompactor(0, "b", "c").compact("a"); + assertTrue("a expected:<[b]> but was:<[c]>".equals(failure)); + } + + public void testStartSame() { + String failure= new ComparisonCompactor(1, "ba", "bc").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testEndSame() { + String failure= new ComparisonCompactor(1, "ab", "cb").compact(null); + assertEquals("expected:<[a]b> but was:<[c]b>", failure); + } + + public void testSame() { + String failure= new ComparisonCompactor(1, "ab", "ab").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testNoContextStartAndEndSame() { + String failure= new ComparisonCompactor(0, "abc", "adc").compact(null); + assertEquals("expected:<...[b]...> but was:<...[d]...>", failure); + } + + public void testStartAndEndContext() { + String failure= new ComparisonCompactor(1, "abc", "adc").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testStartAndEndContextWithEllipses() { + String failure= new ComparisonCompactor(1, "abcde", "abfde").compact(null); + assertEquals("expected:<...b[c]d...> but was:<...b[f]d...>", failure); + } + + public void testComparisonErrorStartSameComplete() { + String failure= new ComparisonCompactor(2, "ab", "abc").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testComparisonErrorEndSameComplete() { + String failure= new ComparisonCompactor(0, "bc", "abc").compact(null); + assertEquals("expected:<[]...> but was:<[a]...>", failure); + } + + public void testComparisonErrorEndSameCompleteContext() { + String failure= new ComparisonCompactor(2, "bc", "abc").compact(null); + assertEquals("expected:<[]bc> but was:<[a]bc>", failure); + } + + public void testComparisonErrorOverlapingMatches() { + String failure= new ComparisonCompactor(0, "abc", "abbc").compact(null); + assertEquals("expected:<...[]...> but was:<...[b]...>", failure); + } + + public void testComparisonErrorOverlapingMatchesContext() { + String failure= new ComparisonCompactor(2, "abc", "abbc").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testComparisonErrorOverlapingMatches2() { + String failure= new ComparisonCompactor(0, "abcdde", "abcde").compact(null); + assertEquals("expected:<...[d]...> but was:<...[]...>", failure); + } + + public void testComparisonErrorOverlapingMatches2Context() { + String failure= new ComparisonCompactor(2, "abcdde", "abcde").compact(null); + assertEquals("expected:<...cd[d]e> but was:<...cd[]e>", failure); + } + + public void testComparisonErrorWithActualNull() { + String failure= new ComparisonCompactor(0, "a", null).compact(null); + assertEquals("expected: but was:", failure); + } + + public void testComparisonErrorWithActualNullContext() { + String failure= new ComparisonCompactor(2, "a", null).compact(null); + assertEquals("expected: but was:", failure); + } + + public void testComparisonErrorWithExpectedNull() { + String failure= new ComparisonCompactor(0, null, "a").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testComparisonErrorWithExpectedNullContext() { + String failure= new ComparisonCompactor(2, null, "a").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testBug609972() { + String failure= new ComparisonCompactor(10, "S&P500", "0").compact(null); + assertEquals("expected:<[S&P50]0> but was:<[]0>", failure); + } +} diff --git a/junit4/src/test/java/junit/tests/framework/ComparisonFailureTest.java b/junit4/src/test/java/junit/tests/framework/ComparisonFailureTest.java new file mode 100644 index 0000000..8a1e5f2 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/ComparisonFailureTest.java @@ -0,0 +1,47 @@ +package junit.tests.framework; + +import junit.framework.ComparisonFailure; +import junit.framework.TestCase; + +public class ComparisonFailureTest extends TestCase { + + // Most of the tests are in ComparisonCompactorTest + public void testConnection() { + ComparisonFailure failure= new ComparisonFailure("warning", "Mary had a little lamb", "Mary had the little lamb"); + assertEquals("warning expected: but was:", failure.getMessage()); + } + + // This is like an instanceof test. + public void testThrowing() { + try { + assertEquals("a", "b"); + } catch (ComparisonFailure e) { + return; + } + fail(); + } + + public void testExceptionToStringWithMessage() { + try { + assertEquals("woops!", "a", "b"); + } catch (ComparisonFailure e) { + if (!e.toString().startsWith("junit.framework.ComparisonFailure: woops! expected:<")) { + fail("Unexpected message: " + e); + } + return; + } + fail(); + } + + public void testExceptionToStringWithoutMessage() { + try { + assertEquals("a", "b"); + } catch (ComparisonFailure e) { + if (!e.toString().startsWith("junit.framework.ComparisonFailure: expected:<")) { + fail("Unexpected message: " + e); + } + return; + } + fail(); + } +} diff --git a/junit4/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java b/junit4/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java new file mode 100644 index 0000000..9df3560 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java @@ -0,0 +1,55 @@ +package junit.tests.framework; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +public class DoublePrecisionAssertTest extends TestCase { + + /** + * Test for the special Double.NaN value. + */ + public void testAssertEqualsNaNFails() { + try { + assertEquals(1.234, Double.NaN, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertNaNEqualsFails() { + try { + assertEquals(Double.NaN, 1.234, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertNaNEqualsNaN() { + assertEquals(Double.NaN, Double.NaN, 0.0); + } + + public void testAssertPosInfinityNotEqualsNegInfinity() { + try { + assertEquals(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertPosInfinityNotEquals() { + try { + assertEquals(Double.POSITIVE_INFINITY, 1.23, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertPosInfinityEqualsInfinity() { + assertEquals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0.0); + } + + public void testAssertNegInfinityEqualsInfinity() { + assertEquals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0); + } + +} diff --git a/junit4/src/test/java/junit/tests/framework/Failure.java b/junit4/src/test/java/junit/tests/framework/Failure.java new file mode 100644 index 0000000..4dd9c8c --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/Failure.java @@ -0,0 +1,14 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * A test case testing the testing framework. + * + */ +public class Failure extends TestCase { + @Override + public void runTest() { + fail(); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/FloatAssertTest.java b/junit4/src/test/java/junit/tests/framework/FloatAssertTest.java new file mode 100644 index 0000000..2d22549 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/FloatAssertTest.java @@ -0,0 +1,63 @@ +package junit.tests.framework; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +public class FloatAssertTest extends TestCase { + + /** + * Test for the special Double.NaN value. + */ + public void testAssertEqualsNaNFails() { + try { + assertEquals(1.234f, Float.NaN, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertNaNEqualsFails() { + try { + assertEquals(Float.NaN, 1.234f, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertNaNEqualsNaN() { + assertEquals(Float.NaN, Float.NaN, 0.0); + } + + public void testAssertPosInfinityNotEqualsNegInfinity() { + try { + assertEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertPosInfinityNotEquals() { + try { + assertEquals(Float.POSITIVE_INFINITY, 1.23f, 0.0); + fail(); + } catch (AssertionFailedError e) { + } + } + + public void testAssertPosInfinityEqualsInfinity() { + assertEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, 0.0); + } + + public void testAssertNegInfinityEqualsInfinity() { + assertEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.0); + } + + public void testAllInfinities() { + try { + assertEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY); + fail(); + } catch (AssertionFailedError e) { + } + } + +} diff --git a/junit4/src/test/java/junit/tests/framework/InheritedTestCase.java b/junit4/src/test/java/junit/tests/framework/InheritedTestCase.java new file mode 100644 index 0000000..f272d77 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/InheritedTestCase.java @@ -0,0 +1,9 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +public class InheritedTestCase extends OneTestCase { + public void test2() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/NoArgTestCaseTest.java b/junit4/src/test/java/junit/tests/framework/NoArgTestCaseTest.java new file mode 100644 index 0000000..70281e6 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/NoArgTestCaseTest.java @@ -0,0 +1,9 @@ + +package junit.tests.framework; + +import junit.framework.TestCase; + +public class NoArgTestCaseTest extends TestCase { + public void testNothing() { // If this compiles, the no arg ctor is there + } +} diff --git a/junit4/src/test/java/junit/tests/framework/NoTestCaseClass.java b/junit4/src/test/java/junit/tests/framework/NoTestCaseClass.java new file mode 100644 index 0000000..5fea04d --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/NoTestCaseClass.java @@ -0,0 +1,10 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ + +public class NoTestCaseClass extends Object { + public void testSuccess() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/NoTestCases.java b/junit4/src/test/java/junit/tests/framework/NoTestCases.java new file mode 100644 index 0000000..fec60d0 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/NoTestCases.java @@ -0,0 +1,11 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +import junit.framework.TestCase; + +public class NoTestCases extends TestCase { + public void noTestCase() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/NotPublicTestCase.java b/junit4/src/test/java/junit/tests/framework/NotPublicTestCase.java new file mode 100644 index 0000000..085f985 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/NotPublicTestCase.java @@ -0,0 +1,13 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +import junit.framework.TestCase; + +public class NotPublicTestCase extends TestCase { + protected void testNotPublic() { + } + public void testPublic() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/NotVoidTestCase.java b/junit4/src/test/java/junit/tests/framework/NotVoidTestCase.java new file mode 100644 index 0000000..eca1a63 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/NotVoidTestCase.java @@ -0,0 +1,14 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +import junit.framework.TestCase; + +public class NotVoidTestCase extends TestCase { + public int testNotVoid() { + return 1; + } + public void testVoid() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/OneTestCase.java b/junit4/src/test/java/junit/tests/framework/OneTestCase.java new file mode 100644 index 0000000..b4ca560 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/OneTestCase.java @@ -0,0 +1,15 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +import junit.framework.TestCase; + +public class OneTestCase extends TestCase { + public void noTestCase() { + } + public void testCase() { + } + public void testCase(int arg) { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/OverrideTestCase.java b/junit4/src/test/java/junit/tests/framework/OverrideTestCase.java new file mode 100644 index 0000000..043ef81 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/OverrideTestCase.java @@ -0,0 +1,10 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +public class OverrideTestCase extends OneTestCase { + @Override + public void testCase() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/Success.java b/junit4/src/test/java/junit/tests/framework/Success.java new file mode 100644 index 0000000..ed4d1b6 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/Success.java @@ -0,0 +1,17 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * A test case testing the testing framework. + * + */ +public class Success extends TestCase { + + @Override + public void runTest() { + } + + public void testSuccess() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/SuiteTest.java b/junit4/src/test/java/junit/tests/framework/SuiteTest.java new file mode 100644 index 0000000..3953f4f --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/SuiteTest.java @@ -0,0 +1,105 @@ +package junit.tests.framework; + +import java.util.Collections; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; + +/** + * A fixture for testing the "auto" test suite feature. + * + */ +public class SuiteTest extends TestCase { + protected TestResult fResult; + public SuiteTest(String name) { + super(name); + } + @Override + protected void setUp() { + fResult= new TestResult(); + } + public static Test suite() { + TestSuite suite= new TestSuite("Suite Tests"); + // build the suite manually, because some of the suites are testing + // the functionality that automatically builds suites + suite.addTest(new SuiteTest("testNoTestCases")); + suite.addTest(new SuiteTest("testOneTestCase")); + suite.addTest(new SuiteTest("testNotPublicTestCase")); + suite.addTest(new SuiteTest("testNotVoidTestCase")); + suite.addTest(new SuiteTest("testNotExistingTestCase")); + suite.addTest(new SuiteTest("testInheritedTests")); + suite.addTest(new SuiteTest("testOneTestCaseEclipseSeesSameStructureAs381")); + suite.addTest(new SuiteTest("testNoTestCaseClass")); + suite.addTest(new SuiteTest("testShadowedTests")); + suite.addTest(new SuiteTest("testAddTestSuite")); + suite.addTest(new SuiteTest("testCreateSuiteFromArray")); + + return suite; + } + public void testInheritedTests() { + TestSuite suite= new TestSuite(InheritedTestCase.class); + suite.run(fResult); + assertTrue(fResult.wasSuccessful()); + assertEquals(2, fResult.runCount()); + } + public void testNoTestCaseClass() { + Test t= new TestSuite(NoTestCaseClass.class); + t.run(fResult); + assertEquals(1, fResult.runCount()); // warning test + assertTrue(! fResult.wasSuccessful()); + } + public void testNoTestCases() { + Test t= new TestSuite(NoTestCases.class); + t.run(fResult); + assertTrue(fResult.runCount() == 1); // warning test + assertTrue(fResult.failureCount() == 1); + assertTrue(! fResult.wasSuccessful()); + } + public void testNotExistingTestCase() { + Test t= new SuiteTest("notExistingMethod"); + t.run(fResult); + assertTrue(fResult.runCount() == 1); + assertTrue(fResult.failureCount() == 1); + assertTrue(fResult.errorCount() == 0); + } + public void testNotPublicTestCase() { + TestSuite suite= new TestSuite(NotPublicTestCase.class); + // 1 public test case + 1 warning for the non-public test case + assertEquals(2, suite.countTestCases()); + } + public void testNotVoidTestCase() { + TestSuite suite= new TestSuite(NotVoidTestCase.class); + assertTrue(suite.countTestCases() == 1); + } + public void testOneTestCase() { + TestSuite t= new TestSuite(OneTestCase.class); + t.run(fResult); + assertTrue(fResult.runCount() == 1); + assertTrue(fResult.failureCount() == 0); + assertTrue(fResult.errorCount() == 0); + assertTrue(fResult.wasSuccessful()); + } + public void testOneTestCaseEclipseSeesSameStructureAs381() { + TestSuite t= new TestSuite(ThreeTestCases.class); + assertEquals(3, Collections.list(t.tests()).size()); + } + public void testShadowedTests() { + TestSuite suite= new TestSuite(OverrideTestCase.class); + suite.run(fResult); + assertEquals(1, fResult.runCount()); + } + public void testAddTestSuite() { + TestSuite suite= new TestSuite(); + suite.addTestSuite(OneTestCase.class); + suite.run(fResult); + assertEquals(1, fResult.runCount()); + } + public void testCreateSuiteFromArray() { + TestSuite suite = new TestSuite(OneTestCase.class, DoublePrecisionAssertTest.class); + assertEquals(2, suite.testCount()); + assertEquals("junit.tests.framework.DoublePrecisionAssertTest" , ((TestSuite)suite.testAt(1)).getName()); + assertEquals("junit.tests.framework.OneTestCase" , ((TestSuite)suite.testAt(0)).getName()); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/TestCaseTest.java b/junit4/src/test/java/junit/tests/framework/TestCaseTest.java new file mode 100644 index 0000000..91b91e6 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/TestCaseTest.java @@ -0,0 +1,190 @@ +package junit.tests.framework; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestFailure; +import junit.framework.TestResult; +import junit.framework.TestSuite; +import junit.tests.WasRun; + +/** + * A test case testing the testing framework. + * + */ +public class TestCaseTest extends TestCase { + + static class TornDown extends TestCase { + boolean fTornDown= false; + + @Override + protected void tearDown() { + fTornDown= true; + } + @Override + protected void runTest() { + throw new Error("running"); + } + } + + public void testCaseToString() { + // This test wins the award for twisted snake tail eating while + // writing self tests. And you thought those weird anonymous + // inner classes were bad... + assertEquals("testCaseToString(junit.tests.framework.TestCaseTest)", toString()); + } + public void testError() { + TestCase error= new TestCase("error") { + @Override + protected void runTest() { + throw new Error(); + } + }; + verifyError(error); + } + public void testRunAndTearDownFails() { + TornDown fails= new TornDown() { + @Override + protected void tearDown() { + super.tearDown(); + throw new Error(); + } + @Override + protected void runTest() { + throw new Error(); + } + }; + verifyError(fails); + assertTrue(fails.fTornDown); + } + public void testSetupFails() { + TestCase fails= new TestCase("success") { + @Override + protected void setUp() { + throw new Error(); + } + @Override + protected void runTest() { + } + }; + verifyError(fails); + } + public void testSuccess() { + TestCase success= new TestCase("success") { + @Override + protected void runTest() { + } + }; + verifySuccess(success); + } + public void testFailure() { + TestCase failure= new TestCase("failure") { + @Override + protected void runTest() { + fail(); + } + }; + verifyFailure(failure); + } + + public void testTearDownAfterError() { + TornDown fails= new TornDown(); + verifyError(fails); + assertTrue(fails.fTornDown); + } + + public void testTearDownFails() { + TestCase fails= new TestCase("success") { + @Override + protected void tearDown() { + throw new Error(); + } + @Override + protected void runTest() { + } + }; + verifyError(fails); + } + public void testTearDownSetupFails() { + TornDown fails= new TornDown() { + @Override + protected void setUp() { + throw new Error(); + } + }; + verifyError(fails); + assertTrue(!fails.fTornDown); + } + public void testWasRun() { + WasRun test= new WasRun(); + test.run(); + assertTrue(test.fWasRun); + } + public void testExceptionRunningAndTearDown() { + // With 1.4, we should + // wrap the exception thrown while running with the exception thrown + // while tearing down + Test t= new TornDown() { + @Override + public void tearDown() { + throw new Error("tearingDown"); + } + }; + TestResult result= new TestResult(); + t.run(result); + TestFailure failure= result.errors().nextElement(); + assertEquals("running", failure.thrownException().getMessage()); + } + + public void testErrorTearingDownDoesntMaskErrorRunning() { + final Exception running= new Exception("Running"); + TestCase t= new TestCase() { + @Override + protected void runTest() throws Throwable { + throw running; + } + @Override + protected void tearDown() throws Exception { + throw new Error("Tearing down"); + } + }; + try { + t.runBare(); + } catch (Throwable thrown) { + assertSame(running, thrown); + } + } + + public void testNoArgTestCasePasses() { + Test t= new TestSuite(NoArgTestCaseTest.class); + TestResult result= new TestResult(); + t.run(result); + assertTrue(result.runCount() == 1); + assertTrue(result.failureCount() == 0); + assertTrue(result.errorCount() == 0); + } + + public void testNamelessTestCase() { + TestCase t= new TestCase() {}; + TestResult result = t.run(); + assertEquals(1, result.failureCount()); + } + + void verifyError(TestCase test) { + TestResult result= test.run(); + assertTrue(result.runCount() == 1); + assertTrue(result.failureCount() == 0); + assertTrue(result.errorCount() == 1); + } + void verifyFailure(TestCase test) { + TestResult result= test.run(); + assertTrue(result.runCount() == 1); + assertTrue(result.failureCount() == 1); + assertTrue(result.errorCount() == 0); + } + void verifySuccess(TestCase test) { + TestResult result= test.run(); + assertTrue(result.runCount() == 1); + assertTrue(result.failureCount() == 0); + assertTrue(result.errorCount() == 0); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/TestImplementorTest.java b/junit4/src/test/java/junit/tests/framework/TestImplementorTest.java new file mode 100644 index 0000000..a5f0962 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/TestImplementorTest.java @@ -0,0 +1,54 @@ +package junit.tests.framework; + +import junit.framework.Protectable; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; + +/** + * Test an implementor of junit.framework.Test other than TestCase or TestSuite + */ +public class TestImplementorTest extends TestCase { + public static class DoubleTestCase implements Test { + private TestCase fTestCase; + + public DoubleTestCase(TestCase testCase) { + fTestCase= testCase; + } + + public int countTestCases() { + return 2; + } + + public void run(TestResult result) { + result.startTest(this); + Protectable p= new Protectable() { + public void protect() throws Throwable { + fTestCase.runBare(); + fTestCase.runBare(); + } + }; + result.runProtected(this, p); + result.endTest(this); + } + } + + private DoubleTestCase fTest; + + public TestImplementorTest() { + TestCase testCase= new TestCase() { + @Override + public void runTest() { + } + }; + fTest= new DoubleTestCase(testCase); + } + + public void testSuccessfulRun() { + TestResult result= new TestResult(); + fTest.run(result); + assertEquals(fTest.countTestCases(), result.runCount()); + assertEquals(0, result.errorCount()); + assertEquals(0, result.failureCount()); + } +} diff --git a/junit4/src/test/java/junit/tests/framework/TestListenerTest.java b/junit4/src/test/java/junit/tests/framework/TestListenerTest.java new file mode 100644 index 0000000..1da2af5 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/TestListenerTest.java @@ -0,0 +1,73 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +import junit.framework.AssertionFailedError; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestListener; +import junit.framework.TestResult; + +public class TestListenerTest extends TestCase implements TestListener { + private TestResult fResult; + private int fStartCount; + private int fEndCount; + private int fFailureCount; + private int fErrorCount; + + public void addError(Test test, Throwable t) { + fErrorCount++; + } + public void addFailure(Test test, AssertionFailedError t) { + fFailureCount++; + } + public void endTest(Test test) { + fEndCount++; + } + @Override + protected void setUp() { + fResult= new TestResult(); + fResult.addListener(this); + + fStartCount= 0; + fEndCount= 0; + fFailureCount= 0; + fErrorCount= 0; + } + public void startTest(Test test) { + fStartCount++; + } + public void testError() { + TestCase test= new TestCase("noop") { + @Override + public void runTest() { + throw new Error(); + } + }; + test.run(fResult); + assertEquals(1, fErrorCount); + assertEquals(1, fEndCount); + } + public void testFailure() { + TestCase test= new TestCase("noop") { + @Override + public void runTest() { + fail(); + } + }; + test.run(fResult); + assertEquals(1, fFailureCount); + assertEquals(1, fEndCount); + } + public void testStartStop() { + TestCase test= new TestCase("noop") { + @Override + public void runTest() { + } + }; + test.run(fResult); + assertEquals(1, fStartCount); + assertEquals(1, fEndCount); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/ThreeTestCases.java b/junit4/src/test/java/junit/tests/framework/ThreeTestCases.java new file mode 100644 index 0000000..c58bece --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/ThreeTestCases.java @@ -0,0 +1,15 @@ +package junit.tests.framework; + +/** + * Test class used in SuiteTest + */ +import junit.framework.TestCase; + +public class ThreeTestCases extends TestCase { + public void testCase() { + } + public void testCase2() { + } + public void testCase3thisTimeItsPersonal() { + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/framework/package-info.java b/junit4/src/test/java/junit/tests/framework/package-info.java new file mode 100644 index 0000000..9cc0024 --- /dev/null +++ b/junit4/src/test/java/junit/tests/framework/package-info.java @@ -0,0 +1,4 @@ +/** + * Tests the JUnit v3.x core classes. + */ +package junit.tests.framework; \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/package-info.java b/junit4/src/test/java/junit/tests/package-info.java new file mode 100644 index 0000000..d23121b --- /dev/null +++ b/junit4/src/test/java/junit/tests/package-info.java @@ -0,0 +1,4 @@ +/** + * Tests the JUnit v3.x framework. + */ +package junit.tests; \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/runner/AllTests.java b/junit4/src/test/java/junit/tests/runner/AllTests.java new file mode 100644 index 0000000..a0aa116 --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/AllTests.java @@ -0,0 +1,31 @@ +package junit.tests.runner; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * TestSuite that runs all the sample tests + * + */ +public class AllTests { + + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); + } + + public static Test suite() { // Collect tests manually because we have to test class collection code + TestSuite suite= new TestSuite("Framework Tests"); + suite.addTestSuite(StackFilterTest.class); + suite.addTestSuite(ResultTest.class); + suite.addTestSuite(BaseTestRunnerTest.class); + suite.addTestSuite(TextFeedbackTest.class); + suite.addTestSuite(TextRunnerSingleMethodTest.class); + suite.addTestSuite(TextRunnerTest.class); + return suite; + } + + static boolean isJDK11() { + String version= System.getProperty("java.version"); + return version.startsWith("1.1"); + } +} diff --git a/junit4/src/test/java/junit/tests/runner/BaseTestRunnerTest.java b/junit4/src/test/java/junit/tests/runner/BaseTestRunnerTest.java new file mode 100644 index 0000000..8943da9 --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/BaseTestRunnerTest.java @@ -0,0 +1,53 @@ + +package junit.tests.runner; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import junit.runner.BaseTestRunner; + +public class BaseTestRunnerTest extends TestCase { + public static class MockRunner extends BaseTestRunner { + private boolean fRunFailed = false; + + @Override + protected void runFailed(String message) { + fRunFailed = true; + } + + @Override + public void testEnded(String testName) { + } + + @Override + public void testFailed(int status, Test test, Throwable t) { + } + + @Override + public void testStarted(String testName) { + } + } + + public static class NonStatic { + public Test suite() { + return null; + } + } + + public void testInvokeNonStaticSuite() { + BaseTestRunner runner= new MockRunner(); + runner.getTest("junit.tests.runner.BaseTestRunnerTest$NonStatic"); // Used to throw NullPointerException + } + + public static class DoesntExtendTestCase { + public static Test suite() { + return new TestSuite(); + } + } + + public void testInvokeSuiteOnNonSubclassOfTestCase() { + MockRunner runner= new MockRunner(); + runner.getTest(DoesntExtendTestCase.class.getName()); + assertFalse(runner.fRunFailed); + } +} diff --git a/junit4/src/test/java/junit/tests/runner/ResultTest.java b/junit4/src/test/java/junit/tests/runner/ResultTest.java new file mode 100644 index 0000000..ba3b509 --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/ResultTest.java @@ -0,0 +1,37 @@ +package junit.tests.runner; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import junit.framework.TestCase; +import junit.tests.framework.Success; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.tests.running.methods.AnnotationTest; + +public class ResultTest extends TestCase { + + public void testRunFailureResultCanBeSerialised() throws Exception { + JUnitCore runner = new JUnitCore(); + Result result = runner.run(AnnotationTest.FailureTest.class); + assertResultSerializable(result); + } + + public void testRunSuccessResultCanBeSerialised() throws Exception { + JUnitCore runner = new JUnitCore(); + Result result = runner.run(Success.class); + assertResultSerializable(result); + } + + private void assertResultSerializable(Result result) throws IOException, ClassNotFoundException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + new ObjectOutputStream(byteArrayOutputStream).writeObject(result); + byte[] bytes = byteArrayOutputStream.toByteArray(); + ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); + Result fromStream = (Result) objectInputStream.readObject(); + assertNotNull(fromStream); + } +} diff --git a/junit4/src/test/java/junit/tests/runner/StackFilterTest.java b/junit4/src/test/java/junit/tests/runner/StackFilterTest.java new file mode 100644 index 0000000..e70ea23 --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/StackFilterTest.java @@ -0,0 +1,46 @@ +package junit.tests.runner; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import junit.framework.TestCase; +import junit.runner.BaseTestRunner; + +public class StackFilterTest extends TestCase { + String fFiltered; + String fUnfiltered; + + @Override + protected void setUp() { + StringWriter swin= new StringWriter(); + PrintWriter pwin= new PrintWriter(swin); + pwin.println("junit.framework.AssertionFailedError"); + pwin.println(" at junit.framework.Assert.fail(Assert.java:144)"); + pwin.println(" at junit.framework.Assert.assert(Assert.java:19)"); + pwin.println(" at junit.framework.Assert.assert(Assert.java:26)"); + pwin.println(" at MyTest.f(MyTest.java:13)"); + pwin.println(" at MyTest.testStackTrace(MyTest.java:8)"); + pwin.println(" at java.lang.reflect.Method.invoke(Native Method)"); + pwin.println(" at junit.framework.TestCase.runTest(TestCase.java:156)"); + pwin.println(" at junit.framework.TestCase.runBare(TestCase.java:130)"); + pwin.println(" at junit.framework.TestResult$1.protect(TestResult.java:100)"); + pwin.println(" at junit.framework.TestResult.runProtected(TestResult.java:118)"); + pwin.println(" at junit.framework.TestResult.run(TestResult.java:103)"); + pwin.println(" at junit.framework.TestCase.run(TestCase.java:121)"); + pwin.println(" at junit.framework.TestSuite.runTest(TestSuite.java:157)"); + pwin.println(" at junit.framework.TestSuite.run(TestSuite.java, Compiled Code)"); + pwin.println(" at junit.swingui.TestRunner$17.run(TestRunner.java:669)"); + fUnfiltered= swin.toString(); + + StringWriter swout= new StringWriter(); + PrintWriter pwout= new PrintWriter(swout); + pwout.println("junit.framework.AssertionFailedError"); + pwout.println(" at MyTest.f(MyTest.java:13)"); + pwout.println(" at MyTest.testStackTrace(MyTest.java:8)"); + fFiltered= swout.toString(); + } + + public void testFilter() { + assertEquals(fFiltered, BaseTestRunner.getFilteredTrace(fUnfiltered)); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/runner/TextFeedbackTest.java b/junit4/src/test/java/junit/tests/runner/TextFeedbackTest.java new file mode 100644 index 0000000..fa2dbb2 --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/TextFeedbackTest.java @@ -0,0 +1,109 @@ + +package junit.tests.runner; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; +import junit.textui.ResultPrinter; +import junit.textui.TestRunner; + +public class TextFeedbackTest extends TestCase { + OutputStream output; + TestRunner runner; + + 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 static void main(String[] args) { + TestRunner.run(TextFeedbackTest.class); + } + + @Override + public void setUp() { + output= new ByteArrayOutputStream(); + runner= new TestRunner(new TestResultPrinter(new PrintStream(output))); + } + + public void testEmptySuite() { + String expected= expected(new String[]{"", "Time: 0", "", "OK (0 tests)", ""}); + runner.doRun(new TestSuite()); + assertEquals(expected, output.toString()); + } + + + public void testOneTest() { + String expected= expected(new String[]{".", "Time: 0", "", "OK (1 test)", ""}); + TestSuite suite = new TestSuite(); + suite.addTest(new TestCase() { @Override + public void runTest() {}}); + runner.doRun(suite); + assertEquals(expected, output.toString()); + } + + public void testTwoTests() { + String expected= expected(new String[]{"..", "Time: 0", "", "OK (2 tests)", ""}); + TestSuite suite = new TestSuite(); + suite.addTest(new TestCase() { @Override + public void runTest() {}}); + suite.addTest(new TestCase() { @Override + public void runTest() {}}); + runner.doRun(suite); + assertEquals(expected, output.toString()); + } + + public void testFailure() { + String expected= expected(new String[]{".F", "Time: 0", "Failures here", "", "FAILURES!!!", "Tests run: 1, Failures: 1, Errors: 0", ""}); + ResultPrinter printer= new TestResultPrinter(new PrintStream(output)) { + @Override + public void printFailures(TestResult result) { + getWriter().println("Failures here"); + } + }; + runner.setPrinter(printer); + TestSuite suite = new TestSuite(); + suite.addTest(new TestCase() { @Override + public void runTest() {throw new AssertionFailedError();}}); + runner.doRun(suite); + assertEquals(expected, output.toString()); + } + + public void testError() { + 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()); + } + + 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/junit/tests/runner/TextRunnerSingleMethodTest.java b/junit4/src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java new file mode 100644 index 0000000..1034fdd --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java @@ -0,0 +1,39 @@ +package junit.tests.runner; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import junit.framework.TestCase; +import junit.textui.ResultPrinter; +import junit.textui.TestRunner; + +/** + * Test invoking a single test method of a TestCase. + */ +public class TextRunnerSingleMethodTest extends TestCase { + + static boolean fgWasInvoked; + + public static class InvocationTest extends TestCase { + + public void testWasInvoked() { + TextRunnerSingleMethodTest.fgWasInvoked= true; + } + + public void testNotInvoked() { + fail("Shouldn't get here."); + } + } + + public void testSingle() throws Exception { + TestRunner t= new TestRunner(); + t.setPrinter(new ResultPrinter(new PrintStream(new ByteArrayOutputStream()))); + String[] args= { + "-m", "junit.tests.runner.TextRunnerSingleMethodTest$InvocationTest.testWasInvoked" + }; + fgWasInvoked= false; + t.start(args); + assertTrue(fgWasInvoked); + } + +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/runner/TextRunnerTest.java b/junit4/src/test/java/junit/tests/runner/TextRunnerTest.java new file mode 100644 index 0000000..d7b5941 --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/TextRunnerTest.java @@ -0,0 +1,61 @@ +package junit.tests.runner; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; + +public class TextRunnerTest extends TestCase { + + public void testFailure() throws Exception { + execTest("junit.tests.framework.Failure", false); + } + + public void testSuccess() throws Exception { + execTest("junit.tests.framework.Success", true); + } + + public void testError() throws Exception { + execTest("junit.tests.BogusDude", false); + } + + void execTest(String testClass, boolean success) throws Exception { + String java= System.getProperty("java.home")+File.separator+"bin"+File.separator+"java"; + String cp= System.getProperty("java.class.path"); + //use -classpath for JDK 1.1.7 compatibility + String [] cmd= { java, "-classpath", cp, "junit.textui.TestRunner", testClass}; + Process p= Runtime.getRuntime().exec(cmd); + InputStream i= p.getInputStream(); + while((i.read()) != -1) + ; //System.out.write(b); + assertTrue((p.waitFor() == 0) == success); + if (success) + assertTrue(p.exitValue() == 0); + else + assertFalse(p.exitValue() == 0); + } + + public void testRunReturnsResult() { + PrintStream oldOut= System.out; + System.setOut(new PrintStream ( + new OutputStream() { + @Override + public void write(int arg0) throws IOException { + } + } + )); + try { + TestResult result= junit.textui.TestRunner.run(new TestSuite()); + assertTrue(result.wasSuccessful()); + } finally { + System.setOut(oldOut); + } + } + + +} \ No newline at end of file diff --git a/junit4/src/test/java/junit/tests/runner/package-info.java b/junit4/src/test/java/junit/tests/runner/package-info.java new file mode 100644 index 0000000..fc44e8a --- /dev/null +++ b/junit4/src/test/java/junit/tests/runner/package-info.java @@ -0,0 +1,4 @@ +/** + * Tests for the JUnit v3.x runner functionality. + */ +package junit.tests.runner; \ No newline at end of file diff --git a/junit4/src/test/java/org/junit/samples/ListTest.java b/junit4/src/test/java/org/junit/samples/ListTest.java new file mode 100644 index 0000000..732037d --- /dev/null +++ b/junit4/src/test/java/org/junit/samples/ListTest.java @@ -0,0 +1,77 @@ +package org.junit.samples; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.JUnit4TestAdapter; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +/** + * A sample test case, testing {@link java.util.Vector}. + * + */ +public class ListTest { + protected List fEmpty; + protected List fFull; + protected static List fgHeavy; + + public static void main (String... args) { + junit.textui.TestRunner.run (suite()); + } + + @BeforeClass public static void setUpOnce() { + fgHeavy= new ArrayList(); + for(int i= 0; i < 1000; i++) + fgHeavy.add(i); + } + + @Before public void setUp() { + fEmpty= new ArrayList(); + fFull= new ArrayList(); + fFull.add(1); + fFull.add(2); + fFull.add(3); + } + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(ListTest.class); + } + @Ignore("not today") @Test public void capacity() { + int size= fFull.size(); + for (int i= 0; i < 100; i++) + fFull.add(i); + assertTrue(fFull.size() == 100+size); + } + + @Test public void testCopy() { + List copy= new ArrayList(fFull.size()); + copy.addAll(fFull); + assertTrue(copy.size() == fFull.size()); + assertTrue(copy.contains(1)); + } + + @Test public void contains() { + assertTrue(fFull.contains(1)); + assertTrue(!fEmpty.contains(1)); + } + @Test (expected=IndexOutOfBoundsException.class) public void elementAt() { + int i= fFull.get(0); + assertTrue(i == 1); + fFull.get(fFull.size()); // Should throw IndexOutOfBoundsException + } + + @Test public void removeAll() { + fFull.removeAll(fFull); + fEmpty.removeAll(fEmpty); + assertTrue(fFull.isEmpty()); + assertTrue(fEmpty.isEmpty()); + } + @Test public void removeElement() { + fFull.remove(new Integer(3)); + assertTrue(!fFull.contains(3)); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/org/junit/samples/SimpleTest.java b/junit4/src/test/java/org/junit/samples/SimpleTest.java new file mode 100644 index 0000000..3202a7b --- /dev/null +++ b/junit4/src/test/java/org/junit/samples/SimpleTest.java @@ -0,0 +1,41 @@ +package org.junit.samples; + +import static org.junit.Assert.assertEquals; +import junit.framework.JUnit4TestAdapter; +import org.junit.Before; +import org.junit.Test; + +/** + * Some simple tests. + * + */ +public class SimpleTest { + protected int fValue1; + protected int fValue2; + + @Before public void setUp() { + fValue1= 2; + fValue2= 3; + } + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(SimpleTest.class); + } + + public int unused; + @Test public void divideByZero() { + int zero= 0; + int result= 8/zero; + unused= result; // avoid warning for not using result + } + + @Test public void testEquals() { + assertEquals(12, 12); + assertEquals(12L, 12L); + assertEquals(new Long(12), new Long(12)); + + assertEquals("Size", 12, 13); + assertEquals("Capacity", 12.0, 11.99, 0.0); + } + +} \ No newline at end of file diff --git a/junit4/src/test/java/org/junit/samples/money/MoneyTest.java b/junit4/src/test/java/org/junit/samples/money/MoneyTest.java new file mode 100644 index 0000000..f3f8317 --- /dev/null +++ b/junit4/src/test/java/org/junit/samples/money/MoneyTest.java @@ -0,0 +1,158 @@ +package org.junit.samples.money; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import junit.framework.JUnit4TestAdapter; +import junit.samples.money.IMoney; +import junit.samples.money.Money; +import junit.samples.money.MoneyBag; +import org.junit.Before; +import org.junit.Test; + +public class MoneyTest { + private Money f12CHF; + private Money f14CHF; + private Money f7USD; + private Money f21USD; + + private IMoney fMB1; + private IMoney fMB2; + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(MoneyTest.class); + } + + @Before public void setUp() { + f12CHF= new Money(12, "CHF"); + f14CHF= new Money(14, "CHF"); + f7USD= new Money( 7, "USD"); + f21USD= new Money(21, "USD"); + + fMB1= MoneyBag.create(f12CHF, f7USD); + fMB2= MoneyBag.create(f14CHF, f21USD); + } + + @Test public void testBagMultiply() { + // {[12 CHF][7 USD]} *2 == {[24 CHF][14 USD]} + IMoney expected= MoneyBag.create(new Money(24, "CHF"), new Money(14, "USD")); + assertEquals(expected, fMB1.multiply(2)); + assertEquals(fMB1, fMB1.multiply(1)); + assertTrue(fMB1.multiply(0).isZero()); + } + @Test public void testBagNegate() { + // {[12 CHF][7 USD]} negate == {[-12 CHF][-7 USD]} + IMoney expected= MoneyBag.create(new Money(-12, "CHF"), new Money(-7, "USD")); + assertEquals(expected, fMB1.negate()); + } + @Test public void testBagSimpleAdd() { + // {[12 CHF][7 USD]} + [14 CHF] == {[26 CHF][7 USD]} + IMoney expected= MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); + assertEquals(expected, fMB1.add(f14CHF)); + } + @Test public void testBagSubtract() { + // {[12 CHF][7 USD]} - {[14 CHF][21 USD] == {[-2 CHF][-14 USD]} + IMoney expected= MoneyBag.create(new Money(-2, "CHF"), new Money(-14, "USD")); + assertEquals(expected, fMB1.subtract(fMB2)); + } + @Test public void testBagSumAdd() { + // {[12 CHF][7 USD]} + {[14 CHF][21 USD]} == {[26 CHF][28 USD]} + IMoney expected= MoneyBag.create(new Money(26, "CHF"), new Money(28, "USD")); + assertEquals(expected, fMB1.add(fMB2)); + } + @Test public void testIsZero() { + assertTrue(fMB1.subtract(fMB1).isZero()); + assertTrue(MoneyBag.create(new Money (0, "CHF"), new Money (0, "USD")).isZero()); + } + @Test public void testMixedSimpleAdd() { + // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} + IMoney expected= MoneyBag.create(f12CHF, f7USD); + assertEquals(expected, f12CHF.add(f7USD)); + } + @Test public void testBagNotEquals() { + IMoney bag= MoneyBag.create(f12CHF, f7USD); + assertFalse(bag.equals(new Money(12, "DEM").add(f7USD))); + } + @Test public void testMoneyBagEquals() { + assertTrue(!fMB1.equals(null)); + + assertEquals(fMB1, fMB1); + IMoney equal= MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); + assertTrue(fMB1.equals(equal)); + assertTrue(!fMB1.equals(f12CHF)); + assertTrue(!f12CHF.equals(fMB1)); + assertTrue(!fMB1.equals(fMB2)); + } + @Test public void testMoneyBagHash() { + IMoney equal= MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); + assertEquals(fMB1.hashCode(), equal.hashCode()); + } + @Test public void testMoneyEquals() { + assertTrue(!f12CHF.equals(null)); + Money equalMoney= new Money(12, "CHF"); + assertEquals(f12CHF, f12CHF); + assertEquals(f12CHF, equalMoney); + assertEquals(f12CHF.hashCode(), equalMoney.hashCode()); + assertTrue(!f12CHF.equals(f14CHF)); + } + @Test public void zeroMoniesAreEqualRegardlessOfCurrency() { + Money zeroDollars= new Money(0, "USD"); + Money zeroFrancs= new Money(0, "CHF"); + + assertEquals(zeroDollars, zeroFrancs); + assertEquals(zeroDollars.hashCode(), zeroFrancs.hashCode()); + } + @Test public void testMoneyHash() { + assertTrue(!f12CHF.equals(null)); + Money equal= new Money(12, "CHF"); + assertEquals(f12CHF.hashCode(), equal.hashCode()); + } + @Test public void testSimplify() { + IMoney money= MoneyBag.create(new Money(26, "CHF"), new Money(28, "CHF")); + assertEquals(new Money(54, "CHF"), money); + } + @Test public void testNormalize2() { + // {[12 CHF][7 USD]} - [12 CHF] == [7 USD] + Money expected= new Money(7, "USD"); + assertEquals(expected, fMB1.subtract(f12CHF)); + } + @Test public void testNormalize3() { + // {[12 CHF][7 USD]} - {[12 CHF][3 USD]} == [4 USD] + IMoney ms1= MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); + Money expected= new Money(4, "USD"); + assertEquals(expected, fMB1.subtract(ms1)); + } + @Test public void testNormalize4() { // [12 CHF] - {[12 CHF][3 USD]} == [-3 USD] + IMoney ms1= MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); + Money expected= new Money(-3, "USD"); + assertEquals(expected, f12CHF.subtract(ms1)); + } + @Test public void testPrint() { + assertEquals("[12 CHF]", f12CHF.toString()); + } + @Test public void testSimpleAdd() { + // [12 CHF] + [14 CHF] == [26 CHF] + Money expected= new Money(26, "CHF"); + assertEquals(expected, f12CHF.add(f14CHF)); + } + @Test public void testSimpleBagAdd() { + // [14 CHF] + {[12 CHF][7 USD]} == {[26 CHF][7 USD]} + IMoney expected= MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); + assertEquals(expected, f14CHF.add(fMB1)); + } + @Test public void testSimpleMultiply() { + // [14 CHF] *2 == [28 CHF] + Money expected= new Money(28, "CHF"); + assertEquals(expected, f14CHF.multiply(2)); + } + @Test public void testSimpleNegate() { + // [14 CHF] negate == [-14 CHF] + Money expected= new Money(-14, "CHF"); + assertEquals(expected, f14CHF.negate()); + } + @Test public void testSimpleSubtract() { + // [14 CHF] - [12 CHF] == [2 CHF] + Money expected= new Money(2, "CHF"); + assertEquals(expected, f14CHF.subtract(f12CHF)); + } +} \ No newline at end of file diff --git a/junit4/src/test/java/org/junit/samples/money/package-info.java b/junit4/src/test/java/org/junit/samples/money/package-info.java new file mode 100644 index 0000000..2429514 --- /dev/null +++ b/junit4/src/test/java/org/junit/samples/money/package-info.java @@ -0,0 +1,7 @@ +/** + * JUnit v4.x Test for the Money example. + * + * @since 4.0 + * @see junit.samples.money.Money + */ +package org.junit.samples.money; \ No newline at end of file diff --git a/junit4/src/test/java/org/junit/samples/package-info.java b/junit4/src/test/java/org/junit/samples/package-info.java new file mode 100644 index 0000000..ec52263 --- /dev/null +++ b/junit4/src/test/java/org/junit/samples/package-info.java @@ -0,0 +1,6 @@ +/** + * Provides examples on how to use JUnit 4. + * + * @since 4.0 + */ +package org.junit.samples; \ No newline at end of file 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: but was:", 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: but was:", 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: but was:", 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: but was:", 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: but was:", 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: but was:", 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: 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:", 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: was not:", + exception.getMessage()); + } + } + + @Test public void sameNullMessage() { + try { + assertSame("hello", "good-bye"); + fail(); + } catch (AssertionError exception) { + assertEquals("expected same: was not:", 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 but was: java.lang.String", 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 IS_3= is(3); + + @DataPoint + public static Matcher 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 first, + Matcher second) { + assumeTrue(!(first.matches(value) && second.matches(value))); + assertThat(value, not(both(first).and(second))); + } + + @Theory + public void descriptionIsSensible(Matcher first, Matcher 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 void threeAndsWork(Matcher first, + Matcher second, Matcher third, int value) { + assumeTrue(first.matches(value) && second.matches(value) + && third.matches(value)); + assertThat(value, both(first).and(second).and(third)); + } + + @Theory + public void threeOrsWork(Matcher first, + Matcher second, Matcher 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.emptyList()); + } + + @Test(expected=ExpectedException.class) + public void assertEmptyRethrowsSingleThrowable() throws Throwable { + MultipleFailureException.assertEmpty( + Collections.singletonList(new ExpectedException("pesto"))); + } + + @Test + public void assertEmptyThrowsMutipleFailureExceptionForManyThrowables() throws Throwable { + List errors = new ArrayList(); + 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 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 void differentMatchersHaveDifferentDescriptions( + Matcher matcher1, Matcher 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 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 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 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 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 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 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 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 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 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 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 failures= new ArrayList(); + 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 greaterThan(final long l) { + return new TypeSafeMatcher() { + @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 betweenInclusive(final long min, final long max) { + return new TypeSafeMatcher() { + @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 rules(Object test) { + final LinkedList methodRules= new LinkedList( + 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 getTestRules(final Object test) { + final LinkedList methodRules= new LinkedList( + 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 startsWith(final String prefix) { + return new TypeSafeMatcher() { + 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 LOG= new ArrayList(); + + 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 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 errors = new ArrayList(); + + @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() { + public Object call() throws Exception { + throw new RuntimeException("first!"); + } + }); + collector.checkSucceeds(new Callable() { + 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() { + 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 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 annotations= ParameterSignature.signatures(method) + .get(0).getAnnotations(); + assertThat(new ArrayList(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 extends ReguessableValue { + static class GuessMap extends HashMap 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 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 type; + + public Guesser(Class type) { + this(type, new GuessMap()); + } + + public Guesser(Class 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 reguesses(AssumptionViolatedException e) { + final ArrayList returnThis= new ArrayList(); + 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(getType(), newGuesses)); + } + }); + return returnThis; + } + + @Override + public Object getValue() throws CouldNotGenerateValueException { + return getProxy(); + } + + public Class 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 { + static class ReguessableDecorator extends ReguessableValue { + private final PotentialAssignment delegate; + + public ReguessableDecorator(PotentialAssignment delegate) { + this.delegate= delegate; + } + + @Override + public List 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 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 argList() { + ArrayList list = new ArrayList(); + 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 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 queues= new ArrayList(); + + @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(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 list= new ArrayList(); + + @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 MATCHER= null; + + @Theory + public void nonZeroIntsAreFun(int x) { + assumeThat(x, MATCHER); + } + } + + @Theory + public void showFailedAssumptionsWhenNoParametersFound(int data, + Matcher 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 empty() { + return new ArrayList(); + } + + @DataPoint + public static int ONE= 1; + + @DataPoint + public static int TWO= 2; + + @Theory + public void everythingsEmpty(List 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 potentialValues(Method method) + throws Exception { + return Assignments.allUnassigned(method, + new TestClass(HasDateMethod.class)) + .potentialsForNextUnassigned(); + } + + private List failures(Class type) { + return JUnitCore.runClasses(type).getFailures(); + } + + private Matcher> empty() { + Matcher 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 strings = Arrays.asList("foo", "bar"); + + @Theory + public 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 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 strings = Arrays.asList("foo", "bar"); + + @Theory + public void forItems(Collection 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 strings = Arrays.asList("foo", "bar"); + + @Theory + public void forItems(Collection 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 strings = Arrays.asList("foo", "bar"); + + @Theory + public void forItems(Collection 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 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 void forItems(Collection[] items) { + } + } + + @Test + public void whereTypeVariableIsOnTheoryClass() { + PrintableResult result= testResult(TypeVariableOnTheoryClass.class); + assertThat(result, hasSingleFailureContaining("unresolved type variable T")); + } + + @RunWith(Theories.class) + public static class TypeVariableOnTheoryClass { + @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> { + @Theory + public void forItem(A first, Collection second, + Map third, List fourth, F[] fifth, + Collection[] 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 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 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 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 forward() { + return new Comparator() { + public int compare(Description o1, Description o2) { + return o1.getDisplayName().compareTo(o2.getDisplayName()); + } + }; + } + + private static Comparator backward() { + return new Comparator() { + 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 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 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 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 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 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 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 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 countMap= new HashMap(); + + @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 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 suiteClazz= ExampleSuite.class; + Class 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> isEmpty() { + return new TypeSafeMatcher>() { + 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 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 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(); + 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 but was")); + 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 params() { + return Arrays.asList(new Object[][] { + { EverythingWrong.class, 1 + 4 * 5 }, { SubWrong.class, 1 }, + { SubShadows.class, 0 } }); + } + + private List validateAllMethods(Class clazz) { + try { + new BlockJUnit4ClassRunner(clazz); + } catch (InitializationError e) { + return e.getCauses(); + } + return Collections.emptyList(); + } + + @Test public void testFailures() throws Exception { + List 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 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 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 problems= validateAllMethods(SubShadows.class); + assertTrue(problems.isEmpty()); + } + + private List 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() {} +} -- cgit v1.1