From d74d24d9302f04720f366f46f6c855ba1260972c Mon Sep 17 00:00:00 2001 From: aishahalim Date: Sun, 17 Jul 2016 05:31:03 -0700 Subject: [PATCH] ArrayComparisonFailure serialization incompatibility fix (#1315) * Add back field fCause, initialize and use it in the constructor (via initCause()) to avoid NPE and unused field warnings, respectively. * Override getCause() to allow fallback to the deprecated fCause field. * Run tests around possible forward incompatibility of the class from r4.11, 4.12. Fixes #1178. --- .classpath | 10 + .gitignore | 13 + .project | 18 + .settings/org.eclipse.jdt.core.prefs | 357 ++++ .settings/org.eclipse.jdt.ui.prefs | 13 + .travis.yml | 7 + BUILDING | 14 + CODING_STYLE.txt | 5 + CONTRIBUTING.md | 26 + LEGACY_CODING_STYLE.txt | 132 ++ LICENSE-junit.txt | 214 ++ NOTICE.txt | 5 + README.md | 12 + acknowledgements.txt | 163 ++ doc/ReleaseNotes4.10.html | 93 + doc/ReleaseNotes4.10.md | 86 + doc/ReleaseNotes4.10.txt | 1 + doc/ReleaseNotes4.11.html | 121 ++ doc/ReleaseNotes4.11.md | 116 ++ doc/ReleaseNotes4.11.txt | 1 + doc/ReleaseNotes4.12.md | 732 +++++++ doc/ReleaseNotes4.13.md | 6 + doc/ReleaseNotes4.4.html | 271 +++ doc/ReleaseNotes4.4.md | 319 +++ doc/ReleaseNotes4.4.txt | 1 + doc/ReleaseNotes4.5.html | 320 +++ doc/ReleaseNotes4.5.md | 96 + doc/ReleaseNotes4.5.txt | 1 + doc/ReleaseNotes4.6.html | 106 + doc/ReleaseNotes4.6.md | 106 + doc/ReleaseNotes4.6.txt | 1 + doc/ReleaseNotes4.7.html | 229 +++ doc/ReleaseNotes4.7.md | 210 ++ doc/ReleaseNotes4.7.txt | 1 + doc/ReleaseNotes4.8.1.html | 9 + doc/ReleaseNotes4.8.1.md | 7 + doc/ReleaseNotes4.8.1.txt | 1 + doc/ReleaseNotes4.8.2.html | 10 + doc/ReleaseNotes4.8.2.md | 8 + doc/ReleaseNotes4.8.2.txt | 1 + doc/ReleaseNotes4.8.html | 59 + doc/ReleaseNotes4.8.md | 57 + doc/ReleaseNotes4.8.txt | 1 + doc/ReleaseNotes4.9.1.md | 14 + doc/ReleaseNotes4.9.1.txt | 1 + doc/ReleaseNotes4.9.html | 96 + doc/ReleaseNotes4.9.md | 91 + doc/ReleaseNotes4.9.txt | 1 + doc/building-junit.txt | 98 + doc/cookstour/Image1.gif | Bin 0 -> 1820 bytes doc/cookstour/Image2.gif | Bin 0 -> 2490 bytes doc/cookstour/Image3.gif | Bin 0 -> 2946 bytes doc/cookstour/Image4.gif | Bin 0 -> 3694 bytes doc/cookstour/Image5.gif | Bin 0 -> 4858 bytes doc/cookstour/Image6.gif | Bin 0 -> 8950 bytes doc/cookstour/Image7.gif | Bin 0 -> 5295 bytes doc/cookstour/cookstour.htm | 668 +++++++ doc/homepage.html | 115 ++ doc/index.htm | 21 + doc/markdown.sh | 1 + doc/testinfected/IMG00001.GIF | Bin 0 -> 6426 bytes doc/testinfected/IMG00002.GIF | Bin 0 -> 6934 bytes doc/testinfected/IMG00003.GIF | Bin 0 -> 5992 bytes doc/testinfected/logo.gif | Bin 0 -> 964 bytes doc/testinfected/testing.htm | 617 ++++++ epl-v10.html | 261 +++ lib/hamcrest-core-1.3-sources.jar | Bin 0 -> 32624 bytes lib/hamcrest-core-1.3.jar | Bin 0 -> 45024 bytes pom.xml | 576 ++++++ src/changes/changes.xml | 38 + .../junit/extensions/ActiveTestSuite.java | 70 + .../java/junit/extensions/RepeatedTest.java | 39 + .../java/junit/extensions/TestDecorator.java | 43 + src/main/java/junit/extensions/TestSetup.java | 42 + .../java/junit/extensions/package-info.java | 4 + src/main/java/junit/framework/Assert.java | 339 ++++ .../junit/framework/AssertionFailedError.java | 29 + .../junit/framework/ComparisonCompactor.java | 78 + .../junit/framework/ComparisonFailure.java | 56 + .../junit/framework/JUnit4TestAdapter.java | 86 + .../framework/JUnit4TestAdapterCache.java | 77 + .../junit/framework/JUnit4TestCaseFacade.java | 30 + .../java/junit/framework/Protectable.java | 14 + src/main/java/junit/framework/Test.java | 18 + src/main/java/junit/framework/TestCase.java | 509 +++++ .../java/junit/framework/TestFailure.java | 69 + .../java/junit/framework/TestListener.java | 26 + src/main/java/junit/framework/TestResult.java | 185 ++ src/main/java/junit/framework/TestSuite.java | 308 +++ .../java/junit/framework/package-info.java | 4 + .../java/junit/runner/BaseTestRunner.java | 325 +++ .../java/junit/runner/TestRunListener.java | 25 + src/main/java/junit/runner/Version.java | 18 + .../java/junit/runner/Version.java.template | 18 + src/main/java/junit/runner/package-info.java | 4 + src/main/java/junit/textui/ResultPrinter.java | 137 ++ src/main/java/junit/textui/TestRunner.java | 206 ++ src/main/java/junit/textui/package-info.java | 4 + src/main/java/org/junit/After.java | 41 + src/main/java/org/junit/AfterClass.java | 42 + src/main/java/org/junit/Assert.java | 1012 ++++++++++ src/main/java/org/junit/Assume.java | 171 ++ .../junit/AssumptionViolatedException.java | 48 + src/main/java/org/junit/Before.java | 39 + src/main/java/org/junit/BeforeClass.java | 37 + src/main/java/org/junit/ClassRule.java | 87 + .../java/org/junit/ComparisonFailure.java | 171 ++ src/main/java/org/junit/FixMethodOrder.java | 41 + src/main/java/org/junit/Ignore.java | 40 + src/main/java/org/junit/Rule.java | 70 + src/main/java/org/junit/Test.java | 98 + .../junit/experimental/ParallelComputer.java | 67 + .../experimental/categories/Categories.java | 356 ++++ .../experimental/categories/Category.java | 48 + .../categories/CategoryFilterFactory.java | 47 + .../categories/CategoryValidator.java | 62 + .../categories/ExcludeCategories.java | 52 + .../categories/IncludeCategories.java | 52 + .../max/CouldNotReadCoreException.java | 15 + .../org/junit/experimental/max/MaxCore.java | 181 ++ .../junit/experimental/max/MaxHistory.java | 173 ++ .../experimental/results/FailureList.java | 28 + .../experimental/results/PrintableResult.java | 63 + .../experimental/results/ResultMatchers.java | 79 + .../junit/experimental/runners/Enclosed.java | 45 + .../experimental/theories/DataPoint.java | 56 + .../experimental/theories/DataPoints.java | 64 + .../experimental/theories/FromDataPoints.java | 54 + .../theories/ParameterSignature.java | 134 ++ .../theories/ParameterSupplier.java | 43 + .../theories/ParametersSuppliedBy.java | 48 + .../theories/PotentialAssignment.java | 52 + .../junit/experimental/theories/Theories.java | 305 +++ .../junit/experimental/theories/Theory.java | 18 + .../theories/internal/AllMembersSupplier.java | 204 ++ .../theories/internal/Assignments.java | 153 ++ .../theories/internal/BooleanSupplier.java | 18 + .../theories/internal/EnumSupplier.java | 30 + .../internal/ParameterizedAssertionError.java | 50 + .../internal/SpecificDataPointsSupplier.java | 90 + .../theories/suppliers/TestedOn.java | 31 + .../theories/suppliers/TestedOnSupplier.java | 25 + .../org/junit/function/ThrowingRunnable.java | 12 + .../internal/ArrayComparisonFailure.java | 74 + .../internal/AssumptionViolatedException.java | 111 ++ src/main/java/org/junit/internal/Classes.java | 27 + .../junit/internal/ComparisonCriteria.java | 132 ++ .../internal/ExactComparisonCriteria.java | 10 + .../internal/InexactComparisonCriteria.java | 24 + .../java/org/junit/internal/JUnitSystem.java | 14 + .../java/org/junit/internal/MethodSorter.java | 72 + .../java/org/junit/internal/RealSystem.java | 19 + .../java/org/junit/internal/TextListener.java | 101 + .../java/org/junit/internal/Throwables.java | 57 + .../AllDefaultPossibilitiesBuilder.java | 56 + .../internal/builders/AnnotatedBuilder.java | 116 ++ .../internal/builders/IgnoredBuilder.java | 15 + .../internal/builders/IgnoredClassRunner.java | 23 + .../internal/builders/JUnit3Builder.java | 19 + .../internal/builders/JUnit4Builder.java | 12 + .../junit/internal/builders/NullBuilder.java | 11 + .../internal/builders/SuiteMethodBuilder.java | 24 + .../matchers/StacktracePrintingMatcher.java | 57 + .../matchers/ThrowableCauseMatcher.java | 52 + .../matchers/ThrowableMessageMatcher.java | 37 + .../internal/matchers/TypeSafeMatcher.java | 63 + .../junit/internal/requests/ClassRequest.java | 39 + .../internal/requests/FilterRequest.java | 45 + .../internal/requests/SortingRequest.java | 25 + .../junit/internal/requests/package-info.java | 6 + .../junit/internal/runners/ClassRoadie.java | 81 + .../runners/ErrorReportingRunner.java | 92 + .../junit/internal/runners/FailedBefore.java | 13 + .../internal/runners/InitializationError.java | 37 + .../internal/runners/JUnit38ClassRunner.java | 180 ++ .../internal/runners/JUnit4ClassRunner.java | 147 ++ .../junit/internal/runners/MethodRoadie.java | 163 ++ .../internal/runners/MethodValidator.java | 97 + .../junit/internal/runners/SuiteMethod.java | 41 + .../org/junit/internal/runners/TestClass.java | 109 + .../junit/internal/runners/TestMethod.java | 71 + .../runners/model/EachTestNotifier.java | 71 + .../model/MultipleFailureException.java | 12 + .../runners/model/ReflectiveCallable.java | 19 + .../junit/internal/runners/package-info.java | 6 + .../runners/rules/RuleMemberValidator.java | 279 +++ .../runners/rules/ValidationError.java | 14 + .../runners/statements/ExpectException.java | 36 + .../internal/runners/statements/Fail.java | 16 + .../runners/statements/FailOnTimeout.java | 287 +++ .../runners/statements/InvokeMethod.java | 19 + .../runners/statements/RunAfters.java | 41 + .../runners/statements/RunBefores.java | 28 + .../org/junit/matchers/JUnitMatchers.java | 115 ++ .../java/org/junit/matchers/package-info.java | 9 + src/main/java/org/junit/package-info.java | 8 + .../java/org/junit/rules/DisableOnDebug.java | 127 ++ .../java/org/junit/rules/ErrorCollector.java | 111 ++ .../org/junit/rules/ExpectedException.java | 283 +++ .../ExpectedExceptionMatcherBuilder.java | 46 + .../org/junit/rules/ExternalResource.java | 84 + src/main/java/org/junit/rules/MethodRule.java | 32 + src/main/java/org/junit/rules/RuleChain.java | 113 ++ src/main/java/org/junit/rules/RunRules.java | 30 + src/main/java/org/junit/rules/Stopwatch.java | 183 ++ .../java/org/junit/rules/TemporaryFolder.java | 298 +++ src/main/java/org/junit/rules/TestName.java | 41 + src/main/java/org/junit/rules/TestRule.java | 56 + .../java/org/junit/rules/TestWatcher.java | 164 ++ .../java/org/junit/rules/TestWatchman.java | 91 + src/main/java/org/junit/rules/Timeout.java | 233 +++ src/main/java/org/junit/rules/Verifier.java | 47 + src/main/java/org/junit/runner/Computer.java | 42 + .../java/org/junit/runner/Describable.java | 14 + .../java/org/junit/runner/Description.java | 316 +++ .../org/junit/runner/FilterFactories.java | 82 + .../java/org/junit/runner/FilterFactory.java | 25 + .../org/junit/runner/FilterFactoryParams.java | 23 + .../runner/JUnitCommandLineParseResult.java | 147 ++ src/main/java/org/junit/runner/JUnitCore.java | 167 ++ src/main/java/org/junit/runner/Request.java | 169 ++ src/main/java/org/junit/runner/Result.java | 196 ++ src/main/java/org/junit/runner/RunWith.java | 36 + src/main/java/org/junit/runner/Runner.java | 43 + .../org/junit/runner/manipulation/Filter.java | 122 ++ .../junit/runner/manipulation/Filterable.java | 19 + .../manipulation/NoTestsRemainException.java | 10 + .../junit/runner/manipulation/Sortable.java | 20 + .../org/junit/runner/manipulation/Sorter.java | 48 + .../runner/manipulation/package-info.java | 7 + .../junit/runner/notification/Failure.java | 83 + .../runner/notification/RunListener.java | 168 ++ .../runner/notification/RunNotifier.java | 249 +++ .../notification/StoppedByUserException.java | 12 + .../notification/SynchronizedRunListener.java | 134 ++ .../runner/notification/package-info.java | 6 + .../java/org/junit/runner/package-info.java | 6 + src/main/java/org/junit/runners/AllTests.java | 27 + .../junit/runners/BlockJUnit4ClassRunner.java | 460 +++++ src/main/java/org/junit/runners/JUnit4.java | 24 + .../java/org/junit/runners/MethodSorters.java | 41 + .../java/org/junit/runners/Parameterized.java | 360 ++++ .../java/org/junit/runners/ParentRunner.java | 456 +++++ src/main/java/org/junit/runners/Suite.java | 130 ++ .../org/junit/runners/model/Annotatable.java | 20 + .../junit/runners/model/FrameworkField.java | 80 + .../junit/runners/model/FrameworkMember.java | 45 + .../junit/runners/model/FrameworkMethod.java | 202 ++ .../runners/model/InitializationError.java | 47 + .../runners/model/InvalidTestClassError.java | 39 + .../model/MultipleFailureException.java | 69 + .../NoGenericTypeParametersValidator.java | 58 + .../junit/runners/model/RunnerBuilder.java | 115 ++ .../junit/runners/model/RunnerScheduler.java | 23 + .../org/junit/runners/model/Statement.java | 15 + .../org/junit/runners/model/TestClass.java | 313 +++ .../runners/model/TestTimedOutException.java | 44 + .../java/org/junit/runners/package-info.java | 8 + .../BlockJUnit4ClassRunnerWithParameters.java | 170 ++ ...Unit4ClassRunnerWithParametersFactory.java | 18 + .../ParametersRunnerFactory.java | 21 + .../parameterized/TestWithParameters.java | 82 + .../junit/validator/AnnotationValidator.java | 60 + .../validator/AnnotationValidatorFactory.java | 39 + .../junit/validator/AnnotationsValidator.java | 120 ++ .../junit/validator/PublicClassValidator.java | 33 + .../junit/validator/TestClassValidator.java | 21 + .../org/junit/validator/ValidateWith.java | 19 + src/main/javadoc/stylesheet.css | 1 + src/main/resources/junit/runner/logo.gif | Bin 0 -> 964 bytes src/main/resources/junit/runner/smalllogo.gif | Bin 0 -> 883 bytes src/site/fml/faq.fml | 1746 +++++++++++++++++ src/site/markdown/cookbook.md | 127 ++ .../resources/css/hopscotch-0.1.2.min.css | 17 + src/site/resources/css/plain-links.css | 4 + src/site/resources/images/junit-logo.png | Bin 0 -> 3057 bytes src/site/resources/images/junit-logo.svg | 54 + .../resources/scripts/hopscotch-0.1.2.min.js | 17 + src/site/resources/scripts/index.js | 13 + src/site/site.xml | 53 + src/site/xdoc/index.xml | 178 ++ src/test/java/junit/samples/AllTests.java | 22 + src/test/java/junit/samples/ListTest.java | 70 + src/test/java/junit/samples/SimpleTest.java | 72 + src/test/java/junit/samples/money/IMoney.java | 51 + src/test/java/junit/samples/money/Money.java | 92 + .../java/junit/samples/money/MoneyBag.java | 155 ++ .../java/junit/samples/money/MoneyTest.java | 166 ++ .../junit/samples/money/package-info.java | 4 + src/test/java/junit/samples/package-info.java | 4 + src/test/java/junit/tests/AllTests.java | 22 + src/test/java/junit/tests/WasRun.java | 16 + .../tests/extensions/ActiveTestTest.java | 64 + .../java/junit/tests/extensions/AllTests.java | 22 + .../junit/tests/extensions/ExtensionTest.java | 104 + .../tests/extensions/RepeatedTestTest.java | 62 + .../junit/tests/extensions/package-info.java | 4 + .../java/junit/tests/framework/AllTests.java | 31 + .../junit/tests/framework/AssertTest.java | 171 ++ .../framework/AssertionFailedErrorTest.java | 23 + .../framework/ComparisonCompactorTest.java | 102 + .../framework/ComparisonFailureTest.java | 47 + .../framework/DoublePrecisionAssertTest.java | 55 + .../java/junit/tests/framework/Failure.java | 13 + .../tests/framework/FloatAssertTest.java | 63 + .../tests/framework/InheritedTestCase.java | 9 + .../tests/framework/NoArgTestCaseTest.java | 8 + .../tests/framework/NoTestCaseClass.java | 9 + .../junit/tests/framework/NoTestCases.java | 11 + .../tests/framework/NotPublicTestCase.java | 14 + .../tests/framework/NotVoidTestCase.java | 15 + .../junit/tests/framework/OneTestCase.java | 17 + .../tests/framework/OverrideTestCase.java | 10 + .../java/junit/tests/framework/Success.java | 16 + .../java/junit/tests/framework/SuiteTest.java | 118 ++ .../junit/tests/framework/TestCaseTest.java | 205 ++ .../tests/framework/TestImplementorTest.java | 54 + .../tests/framework/TestListenerTest.java | 80 + .../junit/tests/framework/ThreeTestCases.java | 17 + .../junit/tests/framework/package-info.java | 4 + src/test/java/junit/tests/package-info.java | 4 + .../java/junit/tests/runner/AllTests.java | 30 + .../tests/runner/BaseTestRunnerTest.java | 52 + .../java/junit/tests/runner/ResultTest.java | 112 ++ .../junit/tests/runner/StackFilterTest.java | 46 + .../junit/tests/runner/TextFeedbackTest.java | 126 ++ .../runner/TextRunnerSingleMethodTest.java | 39 + .../junit/tests/runner/TextRunnerTest.java | 62 + .../java/junit/tests/runner/package-info.java | 4 + .../AssumptionViolatedExceptionTest.java | 95 + .../categories/AllCategoriesTests.java | 17 + .../CategoriesAndParameterizedTest.java | 129 ++ .../categories/CategoryFilterFactoryTest.java | 66 + .../experimental/categories/CategoryTest.java | 548 ++++++ .../categories/CategoryValidatorTest.java | 88 + .../experimental/categories/JavadocTest.java | 78 + .../categories/MultiCategoryTest.java | 171 ++ .../org/junit/internal/AllInternalTests.java | 23 + .../internal/ArrayComparisonFailureTest.java | 68 + .../org/junit/internal/MethodSorterTest.java | 182 ++ .../builders/AnnotatedBuilderTest.java | 105 + .../StacktracePrintingMatcherTest.java | 38 + .../matchers/ThrowableCauseMatcherTest.java | 18 + .../runners/ErrorReportingRunnerTest.java | 88 + .../runners/statements/FailOnTimeoutTest.java | 195 ++ .../java/org/junit/rules/AllRulesTests.java | 30 + .../BlockJUnit4ClassRunnerOverrideTest.java | 175 ++ .../java/org/junit/rules/ClassRulesTest.java | 251 +++ .../org/junit/rules/DisableOnDebugTest.java | 164 ++ .../java/org/junit/rules/EventCollector.java | 191 ++ .../junit/rules/ExpectedExceptionTest.java | 367 ++++ .../junit/rules/ExternalResourceRuleTest.java | 75 + .../org/junit/rules/LoggingTestWatcher.java | 37 + .../java/org/junit/rules/MethodRulesTest.java | 404 ++++ .../java/org/junit/rules/NameRulesTest.java | 50 + .../java/org/junit/rules/RuleChainTest.java | 96 + .../junit/rules/RuleMemberValidatorTest.java | 356 ++++ .../java/org/junit/rules/StopwatchTest.java | 212 ++ .../org/junit/rules/TempFolderRuleTest.java | 246 +++ ...emporaryFolderRuleAssuredDeletionTest.java | 77 + .../junit/rules/TemporaryFolderUsageTest.java | 215 ++ .../java/org/junit/rules/TestRuleTest.java | 728 +++++++ .../java/org/junit/rules/TestWatcherTest.java | 192 ++ .../org/junit/rules/TestWatchmanTest.java | 78 + .../java/org/junit/rules/TimeoutRuleTest.java | 162 ++ .../org/junit/rules/VerifierRuleTest.java | 210 ++ .../java/org/junit/runner/AllRunnerTests.java | 17 + .../org/junit/runner/FilterFactoriesTest.java | 137 ++ .../runner/FilterOptionIntegrationTest.java | 190 ++ .../JUnitCommandLineParseResultTest.java | 146 ++ .../java/org/junit/runner/JUnitCoreTest.java | 20 + src/test/java/org/junit/runner/RunnerSpy.java | 37 + .../notification/AllNotificationTests.java | 14 + .../ConcurrentRunNotifierTest.java | 180 ++ .../runner/notification/RunNotifierTest.java | 131 ++ .../SynchronizedRunListenerTest.java | 156 ++ .../org/junit/runners/AllRunnersTests.java | 16 + .../CustomBlockJUnit4ClassRunnerTest.java | 90 + .../junit/runners/model/AllModelTests.java | 15 + .../runners/model/FrameworkFieldTest.java | 58 + .../runners/model/FrameworkMethodTest.java | 60 + .../model/InvalidTestClassErrorTest.java | 23 + .../runners/model/RunnerBuilderStub.java | 11 + .../junit/runners/model/TestClassTest.java | 245 +++ .../parameterized/AllParameterizedTests.java | 14 + ...ckJUnit4ClassRunnerWithParametersTest.java | 45 + .../parameterized/ParameterizedNamesTest.java | 51 + .../parameterized/TestWithParametersTest.java | 137 ++ .../org/junit/samples/AllSamplesTests.java | 14 + src/test/java/org/junit/samples/ListTest.java | 91 + .../java/org/junit/samples/SimpleTest.java | 47 + .../org/junit/samples/money/MoneyTest.java | 205 ++ .../org/junit/samples/money/package-info.java | 7 + .../java/org/junit/samples/package-info.java | 6 + src/test/java/org/junit/tests/AllTests.java | 49 + .../org/junit/tests/ObjectContractTest.java | 46 + src/test/java/org/junit/tests/TestSystem.java | 35 + .../tests/assertion/AllAssertionTests.java | 14 + .../junit/tests/assertion/AssertionTest.java | 874 +++++++++ .../assertion/ComparisonFailureTest.java | 78 + .../MultipleFailureExceptionTest.java | 79 + .../tests/deprecated/AllDeprecatedTests.java | 13 + .../deprecated/JUnit4ClassRunnerTest.java | 64 + .../description/AllDescriptionTests.java | 15 + .../description/AnnotatedDescriptionTest.java | 96 + .../description/SuiteDescriptionTest.java | 38 + .../TestDescriptionMethodNameTest.java | 50 + .../description/TestDescriptionTest.java | 24 + .../experimental/AllExperimentalTests.java | 39 + .../tests/experimental/AssumptionTest.java | 283 +++ .../junit/tests/experimental/MatcherTest.java | 44 + .../tests/experimental/max/AllMaxTests.java | 14 + .../experimental/max/DescriptionTest.java | 123 ++ .../experimental/max/JUnit38SortingTest.java | 62 + .../experimental/max/MaxStarterTest.java | 292 +++ .../parallel/AllParallelTests.java | 13 + .../parallel/ParallelClassTest.java | 79 + .../parallel/ParallelMethodTest.java | 61 + .../experimental/results/AllResultsTests.java | 13 + .../results/PrintableResultTest.java | 50 + .../results/ResultMatchersTest.java | 23 + .../theories/AllTheoriesTests.java | 19 + .../theories/AssumingInTheoriesTest.java | 42 + .../theories/ParameterSignatureTest.java | 92 + .../theories/PotentialAssignmentTest.java | 57 + .../theories/TestedOnSupplierTest.java | 32 + .../theories/TheoryTestUtils.java | 33 + .../extendingwithstubs/Correspondent.java | 7 + .../theories/extendingwithstubs/Guesser.java | 126 ++ .../extendingwithstubs/GuesserQueue.java | 58 + .../extendingwithstubs/MethodCall.java | 55 + .../extendingwithstubs/ReguessableValue.java | 16 + .../extendingwithstubs/StringableObject.java | 29 + .../theories/extendingwithstubs/Stub.java | 8 + .../extendingwithstubs/StubbedTheories.java | 65 + .../StubbedTheoriesTest.java | 16 + .../internal/AllMembersSupplierTest.java | 209 ++ .../internal/AllTheoriesInternalTests.java | 14 + .../ParameterizedAssertionErrorTest.java | 95 + .../SpecificDataPointsSupplierTest.java | 156 ++ .../runner/AllTheoriesRunnerTests.java | 24 + .../runner/FailingDataPointMethods.java | 136 ++ .../runner/SuccessfulWithDataPointFields.java | 211 ++ .../runner/TheoriesPerformanceTest.java | 38 + ...eMatchingBetweenMultiDataPointsMethod.java | 57 + .../UnsuccessfulWithDataPointFields.java | 243 +++ .../runner/WhenNoParametersMatch.java | 51 + .../runner/WithAutoGeneratedDataPoints.java | 71 + .../theories/runner/WithDataPointMethod.java | 114 ++ .../runner/WithExtendedParameterSources.java | 184 ++ .../theories/runner/WithNamedDataPoints.java | 73 + .../runner/WithOnlyTestAnnotations.java | 82 + .../runner/WithParameterSupplier.java | 165 ++ ...lvedGenericTypeVariablesOnTheoryParms.java | 180 ++ .../AllJUnit3CompatibilityTests.java | 20 + .../junit3compatibility/AllTestsTest.java | 87 + .../junit3compatibility/ClassRequestTest.java | 20 + .../ForwardCompatibilityPrintingTest.java | 91 + .../ForwardCompatibilityTest.java | 254 +++ ...lizationErrorForwardCompatibilityTest.java | 102 + .../JUnit38ClassRunnerTest.java | 155 ++ .../OldTestClassAdaptingListenerTest.java | 28 + .../tests/junit3compatibility/OldTests.java | 12 + .../junit3compatibility/SuiteMethodTest.java | 134 ++ .../tests/listening/AllListeningTests.java | 16 + .../junit/tests/listening/ListenerTest.java | 38 + .../org/junit/tests/listening/RunnerTest.java | 75 + .../tests/listening/TestListenerTest.java | 65 + .../tests/listening/TextListenerTest.java | 73 + .../junit/tests/listening/UserStopTest.java | 33 + .../manipulation/AllManipulationTests.java | 15 + .../junit/tests/manipulation/FilterTest.java | 50 + .../tests/manipulation/FilterableTest.java | 62 + .../tests/manipulation/SingleMethodTest.java | 190 ++ .../tests/manipulation/SortableTest.java | 205 ++ .../java/org/junit/tests/package-info.java | 8 + .../junit/tests/running/AllRunningTests.java | 17 + .../running/classes/AllClassesTests.java | 21 + .../classes/BlockJUnit4ClassRunnerTest.java | 33 + ...ClassLevelMethodsWithIgnoredTestsTest.java | 165 ++ .../tests/running/classes/EnclosedTest.java | 55 + .../running/classes/IgnoreClassTest.java | 31 + .../classes/ParameterizedTestTest.java | 496 +++++ .../classes/ParentRunnerFilteringTest.java | 171 ++ .../running/classes/ParentRunnerTest.java | 308 +++ .../tests/running/classes/RunWithTest.java | 88 + .../tests/running/classes/SuiteTest.java | 192 ++ .../classes/UseSuiteAsASuperclassTest.java | 45 + .../tests/running/core/AllCoreTests.java | 14 + .../tests/running/core/CommandLineTest.java | 78 + .../JUnitCoreReturnsCorrectExitCodeTest.java | 47 + .../junit/tests/running/core/MainRunner.java | 293 +++ .../tests/running/core/SystemExitTest.java | 31 + .../running/methods/AllMethodsTests.java | 17 + .../tests/running/methods/AnnotationTest.java | 643 ++++++ .../tests/running/methods/ExpectedTest.java | 70 + .../running/methods/InheritedTestTest.java | 39 + .../methods/ParameterizedTestMethodTest.java | 188 ++ .../tests/running/methods/TestMethodTest.java | 255 +++ .../tests/running/methods/TimeoutTest.java | 334 ++++ .../tests/validation/AllValidationTests.java | 14 + .../validation/BadlyFormedClassesTest.java | 75 + .../validation/FailedConstructionTest.java | 28 + .../tests/validation/ValidationTest.java | 42 + .../tests/validation/anotherpackage/Sub.java | 5 + .../validation/anotherpackage/Super.java | 9 + .../junit/validator/AllValidatorTests.java | 14 + .../AnnotationValidatorFactoryTest.java | 47 + .../validator/AnnotationsValidatorTest.java | 98 + .../validator/PublicClassValidatorTest.java | 41 + .../testRunFailureResultCanBeSerialised | Bin 0 -> 4849 bytes .../testRunSuccessResultCanBeSerialised | Bin 0 -> 550 bytes .../junit/internal/arrayComparisonFailure_411 | Bin 0 -> 2078 bytes .../junit/internal/arrayComparisonFailure_412 | Bin 0 -> 2078 bytes to-do.txt | 27 + 515 files changed, 48534 insertions(+) create mode 100644 .classpath create mode 100644 .gitignore create mode 100644 .project create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.jdt.ui.prefs create mode 100644 .travis.yml create mode 100644 BUILDING create mode 100644 CODING_STYLE.txt create mode 100644 CONTRIBUTING.md create mode 100644 LEGACY_CODING_STYLE.txt create mode 100644 LICENSE-junit.txt create mode 100644 NOTICE.txt create mode 100644 README.md create mode 100644 acknowledgements.txt create mode 100644 doc/ReleaseNotes4.10.html create mode 100644 doc/ReleaseNotes4.10.md create mode 100644 doc/ReleaseNotes4.10.txt create mode 100644 doc/ReleaseNotes4.11.html create mode 100644 doc/ReleaseNotes4.11.md create mode 100644 doc/ReleaseNotes4.11.txt create mode 100644 doc/ReleaseNotes4.12.md create mode 100644 doc/ReleaseNotes4.13.md create mode 100644 doc/ReleaseNotes4.4.html create mode 100644 doc/ReleaseNotes4.4.md create mode 100644 doc/ReleaseNotes4.4.txt create mode 100644 doc/ReleaseNotes4.5.html create mode 100644 doc/ReleaseNotes4.5.md create mode 100644 doc/ReleaseNotes4.5.txt create mode 100644 doc/ReleaseNotes4.6.html create mode 100644 doc/ReleaseNotes4.6.md create mode 100644 doc/ReleaseNotes4.6.txt create mode 100644 doc/ReleaseNotes4.7.html create mode 100644 doc/ReleaseNotes4.7.md create mode 100644 doc/ReleaseNotes4.7.txt create mode 100644 doc/ReleaseNotes4.8.1.html create mode 100644 doc/ReleaseNotes4.8.1.md create mode 100644 doc/ReleaseNotes4.8.1.txt create mode 100644 doc/ReleaseNotes4.8.2.html create mode 100644 doc/ReleaseNotes4.8.2.md create mode 100644 doc/ReleaseNotes4.8.2.txt create mode 100644 doc/ReleaseNotes4.8.html create mode 100644 doc/ReleaseNotes4.8.md create mode 100644 doc/ReleaseNotes4.8.txt create mode 100644 doc/ReleaseNotes4.9.1.md create mode 100644 doc/ReleaseNotes4.9.1.txt create mode 100644 doc/ReleaseNotes4.9.html create mode 100644 doc/ReleaseNotes4.9.md create mode 100644 doc/ReleaseNotes4.9.txt create mode 100644 doc/building-junit.txt create mode 100644 doc/cookstour/Image1.gif create mode 100644 doc/cookstour/Image2.gif create mode 100644 doc/cookstour/Image3.gif create mode 100644 doc/cookstour/Image4.gif create mode 100644 doc/cookstour/Image5.gif create mode 100644 doc/cookstour/Image6.gif create mode 100644 doc/cookstour/Image7.gif create mode 100644 doc/cookstour/cookstour.htm create mode 100644 doc/homepage.html create mode 100644 doc/index.htm create mode 100644 doc/markdown.sh create mode 100644 doc/testinfected/IMG00001.GIF create mode 100644 doc/testinfected/IMG00002.GIF create mode 100644 doc/testinfected/IMG00003.GIF create mode 100644 doc/testinfected/logo.gif create mode 100644 doc/testinfected/testing.htm create mode 100644 epl-v10.html create mode 100644 lib/hamcrest-core-1.3-sources.jar create mode 100644 lib/hamcrest-core-1.3.jar create mode 100644 pom.xml create mode 100644 src/changes/changes.xml create mode 100644 src/main/java/junit/extensions/ActiveTestSuite.java create mode 100644 src/main/java/junit/extensions/RepeatedTest.java create mode 100644 src/main/java/junit/extensions/TestDecorator.java create mode 100644 src/main/java/junit/extensions/TestSetup.java create mode 100644 src/main/java/junit/extensions/package-info.java create mode 100644 src/main/java/junit/framework/Assert.java create mode 100644 src/main/java/junit/framework/AssertionFailedError.java create mode 100644 src/main/java/junit/framework/ComparisonCompactor.java create mode 100644 src/main/java/junit/framework/ComparisonFailure.java create mode 100644 src/main/java/junit/framework/JUnit4TestAdapter.java create mode 100644 src/main/java/junit/framework/JUnit4TestAdapterCache.java create mode 100644 src/main/java/junit/framework/JUnit4TestCaseFacade.java create mode 100644 src/main/java/junit/framework/Protectable.java create mode 100644 src/main/java/junit/framework/Test.java create mode 100644 src/main/java/junit/framework/TestCase.java create mode 100644 src/main/java/junit/framework/TestFailure.java create mode 100644 src/main/java/junit/framework/TestListener.java create mode 100644 src/main/java/junit/framework/TestResult.java create mode 100644 src/main/java/junit/framework/TestSuite.java create mode 100644 src/main/java/junit/framework/package-info.java create mode 100644 src/main/java/junit/runner/BaseTestRunner.java create mode 100644 src/main/java/junit/runner/TestRunListener.java create mode 100644 src/main/java/junit/runner/Version.java create mode 100644 src/main/java/junit/runner/Version.java.template create mode 100644 src/main/java/junit/runner/package-info.java create mode 100644 src/main/java/junit/textui/ResultPrinter.java create mode 100644 src/main/java/junit/textui/TestRunner.java create mode 100644 src/main/java/junit/textui/package-info.java create mode 100644 src/main/java/org/junit/After.java create mode 100644 src/main/java/org/junit/AfterClass.java create mode 100755 src/main/java/org/junit/Assert.java create mode 100644 src/main/java/org/junit/Assume.java create mode 100644 src/main/java/org/junit/AssumptionViolatedException.java create mode 100644 src/main/java/org/junit/Before.java create mode 100644 src/main/java/org/junit/BeforeClass.java create mode 100644 src/main/java/org/junit/ClassRule.java create mode 100644 src/main/java/org/junit/ComparisonFailure.java create mode 100644 src/main/java/org/junit/FixMethodOrder.java create mode 100644 src/main/java/org/junit/Ignore.java create mode 100644 src/main/java/org/junit/Rule.java create mode 100644 src/main/java/org/junit/Test.java create mode 100644 src/main/java/org/junit/experimental/ParallelComputer.java create mode 100644 src/main/java/org/junit/experimental/categories/Categories.java create mode 100644 src/main/java/org/junit/experimental/categories/Category.java create mode 100644 src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java create mode 100644 src/main/java/org/junit/experimental/categories/CategoryValidator.java create mode 100644 src/main/java/org/junit/experimental/categories/ExcludeCategories.java create mode 100644 src/main/java/org/junit/experimental/categories/IncludeCategories.java create mode 100644 src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java create mode 100644 src/main/java/org/junit/experimental/max/MaxCore.java create mode 100644 src/main/java/org/junit/experimental/max/MaxHistory.java create mode 100644 src/main/java/org/junit/experimental/results/FailureList.java create mode 100644 src/main/java/org/junit/experimental/results/PrintableResult.java create mode 100644 src/main/java/org/junit/experimental/results/ResultMatchers.java create mode 100644 src/main/java/org/junit/experimental/runners/Enclosed.java create mode 100644 src/main/java/org/junit/experimental/theories/DataPoint.java create mode 100644 src/main/java/org/junit/experimental/theories/DataPoints.java create mode 100644 src/main/java/org/junit/experimental/theories/FromDataPoints.java create mode 100644 src/main/java/org/junit/experimental/theories/ParameterSignature.java create mode 100644 src/main/java/org/junit/experimental/theories/ParameterSupplier.java create mode 100644 src/main/java/org/junit/experimental/theories/ParametersSuppliedBy.java create mode 100644 src/main/java/org/junit/experimental/theories/PotentialAssignment.java create mode 100644 src/main/java/org/junit/experimental/theories/Theories.java create mode 100644 src/main/java/org/junit/experimental/theories/Theory.java create mode 100644 src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java create mode 100644 src/main/java/org/junit/experimental/theories/internal/Assignments.java create mode 100644 src/main/java/org/junit/experimental/theories/internal/BooleanSupplier.java create mode 100644 src/main/java/org/junit/experimental/theories/internal/EnumSupplier.java create mode 100644 src/main/java/org/junit/experimental/theories/internal/ParameterizedAssertionError.java create mode 100644 src/main/java/org/junit/experimental/theories/internal/SpecificDataPointsSupplier.java create mode 100644 src/main/java/org/junit/experimental/theories/suppliers/TestedOn.java create mode 100644 src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java create mode 100644 src/main/java/org/junit/function/ThrowingRunnable.java create mode 100644 src/main/java/org/junit/internal/ArrayComparisonFailure.java create mode 100644 src/main/java/org/junit/internal/AssumptionViolatedException.java create mode 100644 src/main/java/org/junit/internal/Classes.java create mode 100644 src/main/java/org/junit/internal/ComparisonCriteria.java create mode 100644 src/main/java/org/junit/internal/ExactComparisonCriteria.java create mode 100644 src/main/java/org/junit/internal/InexactComparisonCriteria.java create mode 100644 src/main/java/org/junit/internal/JUnitSystem.java create mode 100644 src/main/java/org/junit/internal/MethodSorter.java create mode 100644 src/main/java/org/junit/internal/RealSystem.java create mode 100644 src/main/java/org/junit/internal/TextListener.java create mode 100644 src/main/java/org/junit/internal/Throwables.java create mode 100644 src/main/java/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java create mode 100644 src/main/java/org/junit/internal/builders/AnnotatedBuilder.java create mode 100644 src/main/java/org/junit/internal/builders/IgnoredBuilder.java create mode 100644 src/main/java/org/junit/internal/builders/IgnoredClassRunner.java create mode 100644 src/main/java/org/junit/internal/builders/JUnit3Builder.java create mode 100644 src/main/java/org/junit/internal/builders/JUnit4Builder.java create mode 100644 src/main/java/org/junit/internal/builders/NullBuilder.java create mode 100644 src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java create mode 100644 src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java create mode 100644 src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java create mode 100644 src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java create mode 100644 src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java create mode 100644 src/main/java/org/junit/internal/requests/ClassRequest.java create mode 100644 src/main/java/org/junit/internal/requests/FilterRequest.java create mode 100644 src/main/java/org/junit/internal/requests/SortingRequest.java create mode 100644 src/main/java/org/junit/internal/requests/package-info.java create mode 100644 src/main/java/org/junit/internal/runners/ClassRoadie.java create mode 100644 src/main/java/org/junit/internal/runners/ErrorReportingRunner.java create mode 100644 src/main/java/org/junit/internal/runners/FailedBefore.java create mode 100644 src/main/java/org/junit/internal/runners/InitializationError.java create mode 100644 src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java create mode 100644 src/main/java/org/junit/internal/runners/JUnit4ClassRunner.java create mode 100644 src/main/java/org/junit/internal/runners/MethodRoadie.java create mode 100644 src/main/java/org/junit/internal/runners/MethodValidator.java create mode 100644 src/main/java/org/junit/internal/runners/SuiteMethod.java create mode 100644 src/main/java/org/junit/internal/runners/TestClass.java create mode 100644 src/main/java/org/junit/internal/runners/TestMethod.java create mode 100644 src/main/java/org/junit/internal/runners/model/EachTestNotifier.java create mode 100644 src/main/java/org/junit/internal/runners/model/MultipleFailureException.java create mode 100644 src/main/java/org/junit/internal/runners/model/ReflectiveCallable.java create mode 100644 src/main/java/org/junit/internal/runners/package-info.java create mode 100644 src/main/java/org/junit/internal/runners/rules/RuleMemberValidator.java create mode 100644 src/main/java/org/junit/internal/runners/rules/ValidationError.java create mode 100644 src/main/java/org/junit/internal/runners/statements/ExpectException.java create mode 100644 src/main/java/org/junit/internal/runners/statements/Fail.java create mode 100644 src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java create mode 100644 src/main/java/org/junit/internal/runners/statements/InvokeMethod.java create mode 100644 src/main/java/org/junit/internal/runners/statements/RunAfters.java create mode 100644 src/main/java/org/junit/internal/runners/statements/RunBefores.java create mode 100644 src/main/java/org/junit/matchers/JUnitMatchers.java create mode 100644 src/main/java/org/junit/matchers/package-info.java create mode 100644 src/main/java/org/junit/package-info.java create mode 100644 src/main/java/org/junit/rules/DisableOnDebug.java create mode 100644 src/main/java/org/junit/rules/ErrorCollector.java create mode 100644 src/main/java/org/junit/rules/ExpectedException.java create mode 100644 src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java create mode 100644 src/main/java/org/junit/rules/ExternalResource.java create mode 100644 src/main/java/org/junit/rules/MethodRule.java create mode 100644 src/main/java/org/junit/rules/RuleChain.java create mode 100644 src/main/java/org/junit/rules/RunRules.java create mode 100644 src/main/java/org/junit/rules/Stopwatch.java create mode 100644 src/main/java/org/junit/rules/TemporaryFolder.java create mode 100644 src/main/java/org/junit/rules/TestName.java create mode 100644 src/main/java/org/junit/rules/TestRule.java create mode 100644 src/main/java/org/junit/rules/TestWatcher.java create mode 100644 src/main/java/org/junit/rules/TestWatchman.java create mode 100644 src/main/java/org/junit/rules/Timeout.java create mode 100644 src/main/java/org/junit/rules/Verifier.java create mode 100644 src/main/java/org/junit/runner/Computer.java create mode 100644 src/main/java/org/junit/runner/Describable.java create mode 100644 src/main/java/org/junit/runner/Description.java create mode 100644 src/main/java/org/junit/runner/FilterFactories.java create mode 100644 src/main/java/org/junit/runner/FilterFactory.java create mode 100644 src/main/java/org/junit/runner/FilterFactoryParams.java create mode 100644 src/main/java/org/junit/runner/JUnitCommandLineParseResult.java create mode 100644 src/main/java/org/junit/runner/JUnitCore.java create mode 100644 src/main/java/org/junit/runner/Request.java create mode 100644 src/main/java/org/junit/runner/Result.java create mode 100644 src/main/java/org/junit/runner/RunWith.java create mode 100644 src/main/java/org/junit/runner/Runner.java create mode 100644 src/main/java/org/junit/runner/manipulation/Filter.java create mode 100644 src/main/java/org/junit/runner/manipulation/Filterable.java create mode 100644 src/main/java/org/junit/runner/manipulation/NoTestsRemainException.java create mode 100644 src/main/java/org/junit/runner/manipulation/Sortable.java create mode 100644 src/main/java/org/junit/runner/manipulation/Sorter.java create mode 100644 src/main/java/org/junit/runner/manipulation/package-info.java create mode 100644 src/main/java/org/junit/runner/notification/Failure.java create mode 100644 src/main/java/org/junit/runner/notification/RunListener.java create mode 100644 src/main/java/org/junit/runner/notification/RunNotifier.java create mode 100644 src/main/java/org/junit/runner/notification/StoppedByUserException.java create mode 100644 src/main/java/org/junit/runner/notification/SynchronizedRunListener.java create mode 100644 src/main/java/org/junit/runner/notification/package-info.java create mode 100644 src/main/java/org/junit/runner/package-info.java create mode 100644 src/main/java/org/junit/runners/AllTests.java create mode 100644 src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java create mode 100644 src/main/java/org/junit/runners/JUnit4.java create mode 100644 src/main/java/org/junit/runners/MethodSorters.java create mode 100644 src/main/java/org/junit/runners/Parameterized.java create mode 100755 src/main/java/org/junit/runners/ParentRunner.java create mode 100644 src/main/java/org/junit/runners/Suite.java create mode 100644 src/main/java/org/junit/runners/model/Annotatable.java create mode 100644 src/main/java/org/junit/runners/model/FrameworkField.java create mode 100644 src/main/java/org/junit/runners/model/FrameworkMember.java create mode 100644 src/main/java/org/junit/runners/model/FrameworkMethod.java create mode 100644 src/main/java/org/junit/runners/model/InitializationError.java create mode 100644 src/main/java/org/junit/runners/model/InvalidTestClassError.java create mode 100644 src/main/java/org/junit/runners/model/MultipleFailureException.java create mode 100644 src/main/java/org/junit/runners/model/NoGenericTypeParametersValidator.java create mode 100644 src/main/java/org/junit/runners/model/RunnerBuilder.java create mode 100644 src/main/java/org/junit/runners/model/RunnerScheduler.java create mode 100644 src/main/java/org/junit/runners/model/Statement.java create mode 100755 src/main/java/org/junit/runners/model/TestClass.java create mode 100644 src/main/java/org/junit/runners/model/TestTimedOutException.java create mode 100644 src/main/java/org/junit/runners/package-info.java create mode 100644 src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParameters.java create mode 100644 src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersFactory.java create mode 100644 src/main/java/org/junit/runners/parameterized/ParametersRunnerFactory.java create mode 100644 src/main/java/org/junit/runners/parameterized/TestWithParameters.java create mode 100644 src/main/java/org/junit/validator/AnnotationValidator.java create mode 100644 src/main/java/org/junit/validator/AnnotationValidatorFactory.java create mode 100644 src/main/java/org/junit/validator/AnnotationsValidator.java create mode 100644 src/main/java/org/junit/validator/PublicClassValidator.java create mode 100644 src/main/java/org/junit/validator/TestClassValidator.java create mode 100644 src/main/java/org/junit/validator/ValidateWith.java create mode 100644 src/main/javadoc/stylesheet.css create mode 100644 src/main/resources/junit/runner/logo.gif create mode 100644 src/main/resources/junit/runner/smalllogo.gif create mode 100644 src/site/fml/faq.fml create mode 100644 src/site/markdown/cookbook.md create mode 100644 src/site/resources/css/hopscotch-0.1.2.min.css create mode 100644 src/site/resources/css/plain-links.css create mode 100644 src/site/resources/images/junit-logo.png create mode 100644 src/site/resources/images/junit-logo.svg create mode 100644 src/site/resources/scripts/hopscotch-0.1.2.min.js create mode 100644 src/site/resources/scripts/index.js create mode 100644 src/site/site.xml create mode 100644 src/site/xdoc/index.xml create mode 100644 src/test/java/junit/samples/AllTests.java create mode 100644 src/test/java/junit/samples/ListTest.java create mode 100644 src/test/java/junit/samples/SimpleTest.java create mode 100644 src/test/java/junit/samples/money/IMoney.java create mode 100644 src/test/java/junit/samples/money/Money.java create mode 100644 src/test/java/junit/samples/money/MoneyBag.java create mode 100644 src/test/java/junit/samples/money/MoneyTest.java create mode 100644 src/test/java/junit/samples/money/package-info.java create mode 100644 src/test/java/junit/samples/package-info.java create mode 100644 src/test/java/junit/tests/AllTests.java create mode 100644 src/test/java/junit/tests/WasRun.java create mode 100644 src/test/java/junit/tests/extensions/ActiveTestTest.java create mode 100644 src/test/java/junit/tests/extensions/AllTests.java create mode 100644 src/test/java/junit/tests/extensions/ExtensionTest.java create mode 100644 src/test/java/junit/tests/extensions/RepeatedTestTest.java create mode 100644 src/test/java/junit/tests/extensions/package-info.java create mode 100644 src/test/java/junit/tests/framework/AllTests.java create mode 100644 src/test/java/junit/tests/framework/AssertTest.java create mode 100644 src/test/java/junit/tests/framework/AssertionFailedErrorTest.java create mode 100644 src/test/java/junit/tests/framework/ComparisonCompactorTest.java create mode 100644 src/test/java/junit/tests/framework/ComparisonFailureTest.java create mode 100644 src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java create mode 100644 src/test/java/junit/tests/framework/Failure.java create mode 100644 src/test/java/junit/tests/framework/FloatAssertTest.java create mode 100644 src/test/java/junit/tests/framework/InheritedTestCase.java create mode 100644 src/test/java/junit/tests/framework/NoArgTestCaseTest.java create mode 100644 src/test/java/junit/tests/framework/NoTestCaseClass.java create mode 100644 src/test/java/junit/tests/framework/NoTestCases.java create mode 100644 src/test/java/junit/tests/framework/NotPublicTestCase.java create mode 100644 src/test/java/junit/tests/framework/NotVoidTestCase.java create mode 100644 src/test/java/junit/tests/framework/OneTestCase.java create mode 100644 src/test/java/junit/tests/framework/OverrideTestCase.java create mode 100644 src/test/java/junit/tests/framework/Success.java create mode 100644 src/test/java/junit/tests/framework/SuiteTest.java create mode 100644 src/test/java/junit/tests/framework/TestCaseTest.java create mode 100644 src/test/java/junit/tests/framework/TestImplementorTest.java create mode 100644 src/test/java/junit/tests/framework/TestListenerTest.java create mode 100644 src/test/java/junit/tests/framework/ThreeTestCases.java create mode 100644 src/test/java/junit/tests/framework/package-info.java create mode 100644 src/test/java/junit/tests/package-info.java create mode 100644 src/test/java/junit/tests/runner/AllTests.java create mode 100644 src/test/java/junit/tests/runner/BaseTestRunnerTest.java create mode 100644 src/test/java/junit/tests/runner/ResultTest.java create mode 100644 src/test/java/junit/tests/runner/StackFilterTest.java create mode 100644 src/test/java/junit/tests/runner/TextFeedbackTest.java create mode 100644 src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java create mode 100644 src/test/java/junit/tests/runner/TextRunnerTest.java create mode 100644 src/test/java/junit/tests/runner/package-info.java create mode 100644 src/test/java/org/junit/AssumptionViolatedExceptionTest.java create mode 100644 src/test/java/org/junit/experimental/categories/AllCategoriesTests.java create mode 100644 src/test/java/org/junit/experimental/categories/CategoriesAndParameterizedTest.java create mode 100644 src/test/java/org/junit/experimental/categories/CategoryFilterFactoryTest.java create mode 100644 src/test/java/org/junit/experimental/categories/CategoryTest.java create mode 100644 src/test/java/org/junit/experimental/categories/CategoryValidatorTest.java create mode 100644 src/test/java/org/junit/experimental/categories/JavadocTest.java create mode 100644 src/test/java/org/junit/experimental/categories/MultiCategoryTest.java create mode 100644 src/test/java/org/junit/internal/AllInternalTests.java create mode 100644 src/test/java/org/junit/internal/ArrayComparisonFailureTest.java create mode 100644 src/test/java/org/junit/internal/MethodSorterTest.java create mode 100644 src/test/java/org/junit/internal/builders/AnnotatedBuilderTest.java create mode 100644 src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java create mode 100644 src/test/java/org/junit/internal/matchers/ThrowableCauseMatcherTest.java create mode 100644 src/test/java/org/junit/internal/runners/ErrorReportingRunnerTest.java create mode 100644 src/test/java/org/junit/internal/runners/statements/FailOnTimeoutTest.java create mode 100644 src/test/java/org/junit/rules/AllRulesTests.java create mode 100644 src/test/java/org/junit/rules/BlockJUnit4ClassRunnerOverrideTest.java create mode 100644 src/test/java/org/junit/rules/ClassRulesTest.java create mode 100644 src/test/java/org/junit/rules/DisableOnDebugTest.java create mode 100644 src/test/java/org/junit/rules/EventCollector.java create mode 100644 src/test/java/org/junit/rules/ExpectedExceptionTest.java create mode 100644 src/test/java/org/junit/rules/ExternalResourceRuleTest.java create mode 100644 src/test/java/org/junit/rules/LoggingTestWatcher.java create mode 100644 src/test/java/org/junit/rules/MethodRulesTest.java create mode 100644 src/test/java/org/junit/rules/NameRulesTest.java create mode 100644 src/test/java/org/junit/rules/RuleChainTest.java create mode 100644 src/test/java/org/junit/rules/RuleMemberValidatorTest.java create mode 100644 src/test/java/org/junit/rules/StopwatchTest.java create mode 100644 src/test/java/org/junit/rules/TempFolderRuleTest.java create mode 100644 src/test/java/org/junit/rules/TemporaryFolderRuleAssuredDeletionTest.java create mode 100644 src/test/java/org/junit/rules/TemporaryFolderUsageTest.java create mode 100644 src/test/java/org/junit/rules/TestRuleTest.java create mode 100644 src/test/java/org/junit/rules/TestWatcherTest.java create mode 100644 src/test/java/org/junit/rules/TestWatchmanTest.java create mode 100644 src/test/java/org/junit/rules/TimeoutRuleTest.java create mode 100644 src/test/java/org/junit/rules/VerifierRuleTest.java create mode 100644 src/test/java/org/junit/runner/AllRunnerTests.java create mode 100644 src/test/java/org/junit/runner/FilterFactoriesTest.java create mode 100644 src/test/java/org/junit/runner/FilterOptionIntegrationTest.java create mode 100644 src/test/java/org/junit/runner/JUnitCommandLineParseResultTest.java create mode 100644 src/test/java/org/junit/runner/JUnitCoreTest.java create mode 100644 src/test/java/org/junit/runner/RunnerSpy.java create mode 100644 src/test/java/org/junit/runner/notification/AllNotificationTests.java create mode 100644 src/test/java/org/junit/runner/notification/ConcurrentRunNotifierTest.java create mode 100644 src/test/java/org/junit/runner/notification/RunNotifierTest.java create mode 100644 src/test/java/org/junit/runner/notification/SynchronizedRunListenerTest.java create mode 100644 src/test/java/org/junit/runners/AllRunnersTests.java create mode 100644 src/test/java/org/junit/runners/CustomBlockJUnit4ClassRunnerTest.java create mode 100644 src/test/java/org/junit/runners/model/AllModelTests.java create mode 100644 src/test/java/org/junit/runners/model/FrameworkFieldTest.java create mode 100644 src/test/java/org/junit/runners/model/FrameworkMethodTest.java create mode 100644 src/test/java/org/junit/runners/model/InvalidTestClassErrorTest.java create mode 100644 src/test/java/org/junit/runners/model/RunnerBuilderStub.java create mode 100644 src/test/java/org/junit/runners/model/TestClassTest.java create mode 100644 src/test/java/org/junit/runners/parameterized/AllParameterizedTests.java create mode 100644 src/test/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersTest.java create mode 100644 src/test/java/org/junit/runners/parameterized/ParameterizedNamesTest.java create mode 100644 src/test/java/org/junit/runners/parameterized/TestWithParametersTest.java create mode 100644 src/test/java/org/junit/samples/AllSamplesTests.java create mode 100644 src/test/java/org/junit/samples/ListTest.java create mode 100644 src/test/java/org/junit/samples/SimpleTest.java create mode 100644 src/test/java/org/junit/samples/money/MoneyTest.java create mode 100644 src/test/java/org/junit/samples/money/package-info.java create mode 100644 src/test/java/org/junit/samples/package-info.java create mode 100644 src/test/java/org/junit/tests/AllTests.java create mode 100644 src/test/java/org/junit/tests/ObjectContractTest.java create mode 100644 src/test/java/org/junit/tests/TestSystem.java create mode 100644 src/test/java/org/junit/tests/assertion/AllAssertionTests.java create mode 100755 src/test/java/org/junit/tests/assertion/AssertionTest.java create mode 100644 src/test/java/org/junit/tests/assertion/ComparisonFailureTest.java create mode 100644 src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java create mode 100644 src/test/java/org/junit/tests/deprecated/AllDeprecatedTests.java create mode 100644 src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java create mode 100644 src/test/java/org/junit/tests/description/AllDescriptionTests.java create mode 100644 src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java create mode 100644 src/test/java/org/junit/tests/description/SuiteDescriptionTest.java create mode 100644 src/test/java/org/junit/tests/description/TestDescriptionMethodNameTest.java create mode 100644 src/test/java/org/junit/tests/description/TestDescriptionTest.java create mode 100644 src/test/java/org/junit/tests/experimental/AllExperimentalTests.java create mode 100644 src/test/java/org/junit/tests/experimental/AssumptionTest.java create mode 100644 src/test/java/org/junit/tests/experimental/MatcherTest.java create mode 100644 src/test/java/org/junit/tests/experimental/max/AllMaxTests.java create mode 100644 src/test/java/org/junit/tests/experimental/max/DescriptionTest.java create mode 100644 src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java create mode 100644 src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java create mode 100644 src/test/java/org/junit/tests/experimental/parallel/AllParallelTests.java create mode 100644 src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java create mode 100644 src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java create mode 100644 src/test/java/org/junit/tests/experimental/results/AllResultsTests.java create mode 100644 src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java create mode 100644 src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/AllTheoriesTests.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/AssumingInTheoriesTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/PotentialAssignmentTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/TestedOnSupplierTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/TheoryTestUtils.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/internal/AllMembersSupplierTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/internal/AllTheoriesInternalTests.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/internal/ParameterizedAssertionErrorTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/internal/SpecificDataPointsSupplierTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/AllTheoriesRunnerTests.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/FailingDataPointMethods.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataPointsMethod.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithAutoGeneratedDataPoints.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithNamedDataPoints.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithParameterSupplier.java create mode 100644 src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/AllJUnit3CompatibilityTests.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/OldTests.java create mode 100644 src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java create mode 100644 src/test/java/org/junit/tests/listening/AllListeningTests.java create mode 100644 src/test/java/org/junit/tests/listening/ListenerTest.java create mode 100644 src/test/java/org/junit/tests/listening/RunnerTest.java create mode 100644 src/test/java/org/junit/tests/listening/TestListenerTest.java create mode 100644 src/test/java/org/junit/tests/listening/TextListenerTest.java create mode 100644 src/test/java/org/junit/tests/listening/UserStopTest.java create mode 100644 src/test/java/org/junit/tests/manipulation/AllManipulationTests.java create mode 100644 src/test/java/org/junit/tests/manipulation/FilterTest.java create mode 100644 src/test/java/org/junit/tests/manipulation/FilterableTest.java create mode 100644 src/test/java/org/junit/tests/manipulation/SingleMethodTest.java create mode 100644 src/test/java/org/junit/tests/manipulation/SortableTest.java create mode 100644 src/test/java/org/junit/tests/package-info.java create mode 100644 src/test/java/org/junit/tests/running/AllRunningTests.java create mode 100644 src/test/java/org/junit/tests/running/classes/AllClassesTests.java create mode 100644 src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/ClassLevelMethodsWithIgnoredTestsTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/EnclosedTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/RunWithTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/SuiteTest.java create mode 100644 src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java create mode 100644 src/test/java/org/junit/tests/running/core/AllCoreTests.java create mode 100644 src/test/java/org/junit/tests/running/core/CommandLineTest.java create mode 100644 src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java create mode 100644 src/test/java/org/junit/tests/running/core/MainRunner.java create mode 100644 src/test/java/org/junit/tests/running/core/SystemExitTest.java create mode 100644 src/test/java/org/junit/tests/running/methods/AllMethodsTests.java create mode 100644 src/test/java/org/junit/tests/running/methods/AnnotationTest.java create mode 100644 src/test/java/org/junit/tests/running/methods/ExpectedTest.java create mode 100644 src/test/java/org/junit/tests/running/methods/InheritedTestTest.java create mode 100644 src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java create mode 100644 src/test/java/org/junit/tests/running/methods/TestMethodTest.java create mode 100644 src/test/java/org/junit/tests/running/methods/TimeoutTest.java create mode 100644 src/test/java/org/junit/tests/validation/AllValidationTests.java create mode 100644 src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java create mode 100644 src/test/java/org/junit/tests/validation/FailedConstructionTest.java create mode 100644 src/test/java/org/junit/tests/validation/ValidationTest.java create mode 100644 src/test/java/org/junit/tests/validation/anotherpackage/Sub.java create mode 100644 src/test/java/org/junit/tests/validation/anotherpackage/Super.java create mode 100644 src/test/java/org/junit/validator/AllValidatorTests.java create mode 100644 src/test/java/org/junit/validator/AnnotationValidatorFactoryTest.java create mode 100644 src/test/java/org/junit/validator/AnnotationsValidatorTest.java create mode 100644 src/test/java/org/junit/validator/PublicClassValidatorTest.java create mode 100644 src/test/resources/junit/tests/runner/testRunFailureResultCanBeSerialised create mode 100644 src/test/resources/junit/tests/runner/testRunSuccessResultCanBeSerialised create mode 100644 src/test/resources/org/junit/internal/arrayComparisonFailure_411 create mode 100644 src/test/resources/org/junit/internal/arrayComparisonFailure_412 create mode 100644 to-do.txt diff --git a/.classpath b/.classpath new file mode 100644 index 000000000000..f648ca63c5ff --- /dev/null +++ b/.classpath @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000000..b3df647a6236 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +MaxCore.ser +bin +junit4.* +target +MaxCore.max +# IntelliJ +.idea +*.ipr +*.iml +*.iws +out +java.hprof.txt +.gitattributes \ No newline at end of file diff --git a/.project b/.project new file mode 100644 index 000000000000..88756880f282 --- /dev/null +++ b/.project @@ -0,0 +1,18 @@ + + + junit + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.team.cvs.core.cvsnature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000000..d54f4c25de99 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,357 @@ +#Mon Oct 12 21:57:10 EDT 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.codeComplete.fieldPrefixes=f +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=protected +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=protected +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=no_tag +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=protected +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled +org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,NORMAL,HIGH,NORMAL +org.eclipse.jdt.core.compiler.taskTags=TODO,REVISIT,HACK,QUESTION +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=1 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 000000000000..dd34e34a0426 --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,13 @@ +#Tue Jul 22 09:31:38 PDT 2008 +eclipse.preferences.version=1 +formatter_profile=_junit +formatter_settings_version=11 +internal.default.compliance=default +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=java;javax;com; +org.eclipse.jdt.ui.keywordthis=false +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000000..378d46143fe0 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: java +script: mvn verify javadoc:javadoc site:site +jdk: + - oraclejdk7 + - oraclejdk8 + - openjdk7 + - openjdk6 diff --git a/BUILDING b/BUILDING new file mode 100644 index 000000000000..fa39b86e49cd --- /dev/null +++ b/BUILDING @@ -0,0 +1,14 @@ +BUILDING FROM GITHUB: +===================== + +git clone https://github.com/junit-team/junit4.git +cd junit +mvn install + +BUILDING FROM JARS OR ZIPS: +=========================== + +The contents of the zip and jar files are largely maintained for historical +reasons. We do not at this time have an official way to build from the src +jar or zip. If this is an important missing feature, please let us know +at http://github.com/junit-team/junit4/issues diff --git a/CODING_STYLE.txt b/CODING_STYLE.txt new file mode 100644 index 000000000000..3ceb3637c3b8 --- /dev/null +++ b/CODING_STYLE.txt @@ -0,0 +1,5 @@ +JUnit project uses the Google Java Style (https://github.com/google/styleguide) for all new +code (under org.junit.*). Deviating from this, indentation is 4 spaces instead of 2. + +Legacy code (under junit.*) used the legacy guide specified in LEGACY_CODING_STYLE.txt in the +project root. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000000..4ce0de739e9b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,26 @@ +### Project License: Eclipse Public License v1.0 + +- You will only Submit Contributions where You have authored 100% of the content. +- You will only Submit Contributions to which You have the necessary rights. This means that if You are employed You have received the necessary permissions from Your employer to make the Contributions. +- Whatever content You Contribute will be provided under the Project License(s). + +--- + +### How to submit a pull request + +We love pull requests. Here is a quick guide: + +1. You need to have Maven and a JDK (at least version 1.5) installed. +2. [Fork the repo](https://help.github.com/articles/fork-a-repo). +3. [Create a new branch](https://help.github.com/articles/creating-and-deleting-branches-within-your-repository/) from master. +4. Ensure that you have a clean state by running `mvn verify`. +5. Add your change together with a test (tests are not needed for refactorings and documentation changes). +6. Format your code: Import the JUnit project in Eclipse and use its formatter or apply the rules in the `CODING_STYLE` file manually. Only format the code you've changed; reformatting unrelated code makes it harder for us to review your changes. +7. Run `mvn verify` again and ensure all tests are passing. +8. Push to your fork and [submit a pull request](https://help.github.com/articles/creating-a-pull-request/). + +Now you are waiting on us. We review your pull request and at least leave some comments. + + +Note that if you are thinking of providing a fix for one of the bugs or feature requests, it's usually +a good idea to add a comment to the bug to make sure that there's agreement on how we should proceed. diff --git a/LEGACY_CODING_STYLE.txt b/LEGACY_CODING_STYLE.txt new file mode 100644 index 000000000000..81e553b31f45 --- /dev/null +++ b/LEGACY_CODING_STYLE.txt @@ -0,0 +1,132 @@ +================================== +Coding style +================================== + +---------------------------------- +Tabs and Indents +---------------------------------- +* Tab size : 4 +* Indent : 4 +* Continuation indent : 8 +* Label indent : 0 + +> Don't use tab characters. + +---------------------------------- +Spaces +---------------------------------- +Before Parentheses +* if parentheses +* for parentheses +* while parentheses +* switch parentheses +* try parentheses +* catch parentheses +* synchronized parentheses + +Around Operators +* Assignment operators (=, +=, …) +* Logical operators (&&, ||) +* Equality operators (==, !=) +* Relational operators (<, >, <=, >=) +* Bitwise operators (&, |, ^) +* Additive operators (+, -) +* Multiplicative operators (*, /, %) +* Shift operators (<<, >>, >>>) + +Before Left Brace +* Class left brace +* Method left brace +* if left brace +* else left brace +* for left brace +* while left brace +* do left brace +* switch left brace +* try left brace +* catch left brace +* finally left brace +* synchronized left brace + +Before Keywords +* else keyword +* while keyword +* catch keyword +* finally keyword + +In Ternary Operator (?:) +* Before ? +* After ? +* Before : +* After : + +Within Type Arguments +* After comma + +Other +* After comma +* After semicolon +* After type cast + +---------------------------------- +Wrapping and Braces +---------------------------------- +Braces placement +* In class declaration : End of line +* In method declaration : End of line +* Other : End of line + +Use Of Braces +* if() statement : When multiline +* for() statement : When multiline +* while() statement : When multiline +* do .. while() statement : When multiline + +Annotations +* Class annotations : Wrap always +* Method annotations : Wrap always +* Field annotations : Wrap always +* Parameter annotations : Do not wrap +* Local variable annotations : Do not wrap + +---------------------------------- +Blank Lines +---------------------------------- +Minimum Blank Lines +* Before package statement : 0 +* After package statement : 1 +* Before imports : 1 +* After imports : 1 +* Around class : 1 +* After class header : 0 +* After anonymous class header : 0 +* Around field in interface : 0 +* Around field : 0 +* Around method in interface : 1 +* Around method : 1 +* Before method body : 0 + +---------------------------------- +JavaDoc +---------------------------------- +Alignment +* Align thrown exception descriptions + +Blank Lines +* After description + +Other +* Enable leading asterisks +* Use @throws rather than @exception +* Keep empty lines + +---------------------------------- +Imports +---------------------------------- +import static (all other imports) + +import java.* +import javax.* +import com.* + +import (all other imports) diff --git a/LICENSE-junit.txt b/LICENSE-junit.txt new file mode 100644 index 000000000000..fb686291a055 --- /dev/null +++ b/LICENSE-junit.txt @@ -0,0 +1,214 @@ +JUnit + +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC +LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM +CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + + a) in the case of the initial Contributor, the initial code and + documentation distributed under this Agreement, and + b) in the case of each subsequent Contributor: + + i) changes to the Program, and + + ii) additions to the Program; + + where such changes and/or additions to the Program originate from and are +distributed by that particular Contributor. A Contribution 'originates' from a +Contributor if it was added to the Program by such Contributor itself or anyone +acting on such Contributor's behalf. Contributions do not include additions to +the Program which: (i) are separate modules of software distributed in +conjunction with the Program under their own license agreement, and (ii) are +not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents " mean patent claims licensable by a Contributor which are +necessarily infringed by the use or sale of its Contribution alone or when +combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, +including all Contributors. + +2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide, royalty-free copyright license to +reproduce, prepare derivative works of, publicly display, publicly perform, +distribute and sublicense the Contribution of such Contributor, if any, and +such derivative works, in source code and object code form. + + b) Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide, royalty-free patent license under +Licensed Patents to make, use, sell, offer to sell, import and otherwise +transfer the Contribution of such Contributor, if any, in source code and +object code form. This patent license shall apply to the combination of the +Contribution and the Program if, at the time the Contribution is added by the +Contributor, such addition of the Contribution causes such combination to be +covered by the Licensed Patents. The patent license shall not apply to any +other combinations which include the Contribution. No hardware per se is +licensed hereunder. + + c) Recipient understands that although each Contributor grants the +licenses to its Contributions set forth herein, no assurances are provided by +any Contributor that the Program does not infringe the patent or other +intellectual property rights of any other entity. Each Contributor disclaims +any liability to Recipient for claims brought by any other entity based on +infringement of intellectual property rights or otherwise. As a condition to +exercising the rights and licenses granted hereunder, each Recipient hereby +assumes sole responsibility to secure any other intellectual property rights +needed, if any. For example, if a third party patent license is required to +allow Recipient to distribute the Program, it is Recipient's responsibility to +acquire that license before distributing the Program. + + d) Each Contributor represents that to its knowledge it has sufficient +copyright rights in its Contribution, if any, to grant the copyright license +set forth in this Agreement. + +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under +its own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + + b) its license agreement: + + i) effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose; + + ii) effectively excludes on behalf of all Contributors all liability for +damages, including direct, indirect, special, incidental and consequential +damages, such as lost profits; + + iii) states that any provisions which differ from this Agreement are +offered by that Contributor alone and not by any other party; and + + iv) states that source code for the Program is available from such +Contributor, and informs licensees how to obtain it in a reasonable manner on +or through a medium customarily used for software exchange. + +When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + + b) a copy of this Agreement must be included with each copy of the +Program. + +Contributors may not remove or alter any copyright notices contained within the +Program. + +Each Contributor must identify itself as the originator of its Contribution, if +any, in a manner that reasonably allows subsequent Recipients to identify the +originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with +respect to end users, business partners and the like. While this license is +intended to facilitate the commercial use of the Program, the Contributor who +includes the Program in a commercial product offering should do so in a manner +which does not create potential liability for other Contributors. Therefore, if +a Contributor includes the Program in a commercial product offering, such +Contributor ("Commercial Contributor") hereby agrees to defend and indemnify +every other Contributor ("Indemnified Contributor") against any losses, damages +and costs (collectively "Losses") arising from claims, lawsuits and other legal +actions brought by a third party against the Indemnified Contributor to the +extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may +participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product +offering, Product X. That Contributor is then a Commercial Contributor. If that +Commercial Contributor then makes performance claims, or offers warranties +related to Product X, those performance claims and warranties are such +Commercial Contributor's responsibility alone. Under this section, the +Commercial Contributor would have to defend claims against the other +Contributors related to those performance claims and warranties, and if a court +requires any other Contributor to pay any damages as a result, the Commercial +Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR +IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each +Recipient is solely responsible for determining the appropriateness of using +and distributing the Program and assumes all risks associated with its exercise +of rights under this Agreement, including but not limited to the risks and +costs of program errors, compliance with applicable laws, damage to or loss of +data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY +CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST +PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY +WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS +GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable +law, it shall not affect the validity or enforceability of the remainder of the +terms of this Agreement, and without further action by the parties hereto, such +provision shall be reformed to the minimum extent necessary to make such +provision valid and enforceable. + +If Recipient institutes patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging that the +Program itself (excluding combinations of the Program with other software or +hardware) infringes such Recipient's patent(s), then such Recipient's rights +granted under Section 2(b) shall terminate as of the date such litigation is +filed. + +All Recipient's rights under this Agreement shall terminate if it fails to +comply with any of the material terms or conditions of this Agreement and does +not cure such failure in a reasonable period of time after becoming aware of +such noncompliance. If all Recipient's rights under this Agreement terminate, +Recipient agrees to cease use and distribution of the Program as soon as +reasonably practicable. However, Recipient's obligations under this Agreement +and any licenses granted by Recipient relating to the Program shall continue +and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in +order to avoid inconsistency the Agreement is copyrighted and may only be +modified in the following manner. The Agreement Steward reserves the right to +publish new versions (including revisions) of this Agreement from time to time. +No one other than the Agreement Steward has the right to modify this Agreement. +The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the +intellectual property laws of the United States of America. No party to this +Agreement will bring a legal action under this Agreement more than one year +after the cause of action arose. Each party waives its rights to a jury trial +in any resulting litigation. + diff --git a/NOTICE.txt b/NOTICE.txt new file mode 100644 index 000000000000..69b4faf86b2b --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,5 @@ + =================================================================================== + == Notices and attributions required by libraries that the project depends on == + =================================================================================== + + The JUnit depends on Java Hamcrest (http://hamcrest.org/JavaHamcrest/). diff --git a/README.md b/README.md new file mode 100644 index 000000000000..9ad06e6a4403 --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +# JUnit 4 +JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. + +For more information, please visit: +* [Wiki](https://github.com/junit-team/junit4/wiki) +* [Download and Install guide](https://github.com/junit-team/junit4/wiki/Download-and-Install) +* [Getting Started](https://github.com/junit-team/junit4/wiki/Getting-started) + +[![Latest Build Status](https://junit.ci.cloudbees.com/job/JUnit/badge/icon)](https://junit.ci.cloudbees.com/) + +[![Built on DEV@cloud](http://www.cloudbees.com/sites/default/files/Button-Built-on-CB-1.png)](http://www.cloudbees.com/foss/foss-dev.cb) + diff --git a/acknowledgements.txt b/acknowledgements.txt new file mode 100644 index 000000000000..832c0f005bd3 --- /dev/null +++ b/acknowledgements.txt @@ -0,0 +1,163 @@ +2006 March 9 + Matthias Schmidt: improved org.junit package javadoc + +2006 August 3 + giovanni: better test for TestCase without a name. + Matthias Pfau: better error message when test case constructor fails + +2006 November 21 + dakcalouro: Found defect with comparing ints and longs (1555161) + Ben Maurer: Found defect with timeouts taking twice as long as specified (1536198) + +2007 February 08 + Kazimierz Pogoda: Found defect with null array elements (1438163) + +2007 July 09 + wangqq: Found defect with @After not running after a timeout (1745048) + +2007 July 18 + Andrew Dick: Found defect with assertEquals comparing non-Integer Numbers (1715326) + Michael Schechter: Found defect with Filters and suite() methods (1739095) + +2008 February 5 + Walter Gildersleeve: Found assertEquals(null, "null") defect (1857283) + +2008 July 1 + Johannes Link: Submitted test for running subclasses of Suite + +2008 July 23 + Daniel Brolund: Submitted patch for build.xml, fixing 1.5 compatibility (2021396) + +2008 Aug 1 + Nat Pryce: Found defect in treatment of validation errors from custom + subclasses of the legacy JUnit4ClassRunner. + +2008 Aug 18 + Nir Soffer: Suggested adding to the cookbook information about running + running JUnit from the command line. + +2008 Aug 19 + Jack Woehr: Discovered build.xml was missing from junit-4.x.zip + +2009 Jan 5 + Amanda Robinson: Fixed overly permissive @DataPoint processing. + +2009 Feb 9 + Mark Shapiro: Discovered bug in test counting after an ignored method (2106324) + +2009 Apr 20 + Chris Felaco: Discovered regression in handling suite() methods with JUnit 3 runner (1812200) + Toby Byron: Suggested updating linking in javadoc (2090230) + Raphael Parree: Improved docs on Parameterized (2186792) + Robin de Silva Jayasinghe: Fixed Javadoc code sample for AfterClass (2126279) + +2009 May 04 + James Abbley: Submitted a patch that fixed the 2-second limit on Parallel execution. + +2009 Nov 16 + Kristian Rosenvold: Submitted a patch (github#16) that improves thread-safety of + result counting +2010 Feb 08 + Paul Holser: Submitted additional test for TestName rule. + +2010 May 03 + jonas22@github: Found bug (github#98) with assumptions and expected exceptions. + +2011 Jan 03 + jens.schauder@freenet.de: Found bug (github#74) with Categories and + Parameterized. + +2011 Jan 18 + Markus Keller: Reported bug (github#163): + Bad comparison failure message when using assertEquals(String, String) + + Kevin Cooney (kcooney@github): + Patches for runLeaf, public multiple failure exception, + assertion messages and null. + +2011 Mar 04 + Jerome Lacoste (lacostej@github) for initial patch for GH-191. + +2011 Apr 15 + reinholdfuereder@github For initial test for GH-39 + +2011 Apr 15 + ububenheimer@github for bug report https://github.com/junit-team/junit4/issues/208 + +2011 Apr 29 + reinholdfuereder@github: bug report, test, and fix for GH-38: + ParentRunner filtering +2011 Apr 29 + Markus Keller (mkeller@github): Report for GH-187: + Unintentional dependency on Java 6 + +2011 May 31 + Kevin Cooney (kcooney@github): Patches for filtering test suites: + copy List returned by getChildren() before mutating it; + optimize ParentRunner.filter for nested suites; + optimize Filter.intersect for common cases + +2011 Jun 06 + Vampire@github: Report for GH-235: 4.7 release notes incorrect. + +2011 Jun 24 + Samuel Le Berrigaud (sleberrigaud@github): Report for GH-248: + protected BlockJUnit4ClassRunner#rules method removed from 4.8.2 + +2011 Jun 24 + Daniel Rothmaler (drothmaler@github): + #299: random temp file/folder creation + #300: ErrorCollector.checkThat overload + +2011 Jun 25 + Juan Cortez (jcortez@github): Fixed issue #219 where floats were being + printed and represented as doubles in error messages. + +2011 Jul 06 + Stefan Birkner: Fixed wrong documentation of ClassRule (github#254). + +2011 Jul 08 + Paul Holser (pholser@alumni.rice.edu): Beginnings of fix for GH-64: + Theories doesn't honor parameterized types + +2011 Jul 09 + Nigel Charman: Reported Rules bugs github#257 and gihub#258. + +2011 Jul 09 + Stefan Birkner: Fixed rules bugs (github#257, gihub#258, github#260). + +2011 Jul 09 + Stefan Birkner: Fixed rules bugs (github#257, gihub#258, github#260). + +2011 Jul 16 + Rob Dawson: Submitted a patch that makes Results serlializable. + +2011 Jul 20 + Asaf Ary, Stefan Birkner: Fixed FailOnTimeout class (github#265). + +2011 Jul 22 + Andreas Köhler, Stefan Birkner: Fixed wrong documentation of Parameterized (github#89). + +2011 Jul 28 + electrickery, Stefan Birkner: Fixed typo in JavaDoc (github#134). + +2011 Aug 07 + Esko Luontola: Fixed TemporaryFolder creating files in the current working directory (github#278). + +2011 Aug 09 + Stefan Birkner: Fixed JavaDoc links. + +2011 Aug 10 + rodolfoliviero@github and JoseRibeiro@github: feature to create recursive temporary folders. + +2011 Aug 12 + Esko Luontola: Fixed syntax error in Parameterized's usage example (github#285). + +2011 Sep 09 + Robert Munteanu, Stefan Birkner: + TestWatcher and TestWatchman don't call failed when assumption is violated (github#296). + digulla@github, Stefan Birkner: Removed useless code (github#289). + +== NOTE: as of September 2011, we have stopped recording contributions here. + For a full list of everyone who has contributed great bug reports and code, please see + http://github.com/junit-team/junit diff --git a/doc/ReleaseNotes4.10.html b/doc/ReleaseNotes4.10.html new file mode 100644 index 000000000000..ed442c3c56b9 --- /dev/null +++ b/doc/ReleaseNotes4.10.html @@ -0,0 +1,93 @@ +

Summary of Changes in version 4.10 [unreleased!]

+ +

A full summary of commits between 4.9 and 4.10 is on github

+ +

junit-dep has correct contents

+ +

junit-dep-4.9.jar incorrectly contained hamcrest classes, which could lead to version conflicts in projects that depend on hamcrest directly. This is fixed in 4.10 [@dsaff, closing gh-309]

+ +

RuleChain

+ +

The RuleChain rule allows ordering of TestRules:

+ +
public static class UseRuleChain {
+    @Rule
+    public TestRule chain= RuleChain
+                           .outerRule(new LoggingRule("outer rule")
+                           .around(new LoggingRule("middle rule")
+                           .around(new LoggingRule("inner rule");
+
+    @Test
+    public void example() {
+        assertTrue(true);
+    }
+}
+
+ +

writes the log

+ +
starting outer rule
+starting middle rule
+starting inner rule
+finished inner rule
+finished middle rule
+finished outer rule
+
+ +

TemporaryFolder

+ +
    +
  • TemporaryFolder#newFolder(String... folderNames) creates recursively deep temporary folders +[@rodolfoliviero, closing gh-283]
  • +
  • TemporaryFolder#newFile() creates a randomly named new file, and #newFolder() creates a randomly named new folder +[@Daniel Rothmaler, closing gh-299]
  • +
+ +

Theories

+ +

The Theories runner does not anticipate theory parameters that have generic +types, as reported by github#64. Fixing this won't happen until Theories is +moved to junit-contrib. In anticipation of this, 4.9.1 adds some of the +necessary machinery to the runner classes, and deprecates a method that only +the Theories runner uses, FrameworkMethod#producesType(). +The Common Public License that JUnit is released under is now included +in the source repository.

+ +

Thanks to @pholser for identifying a potential resolution for github#64 +and initiating work on it.

+ +

Bug fixes

+ +
    +
  • Built-in Rules implementations +
      +
    • TemporaryFolder should not create files in the current working directory if applying the rule fails +[@orfjackal, fixing gh-278]
    • +
    • TestWatcher and TestWatchman should not call failed for AssumptionViolatedExceptions +[@stefanbirkner, fixing gh-296]
    • +
  • +
  • Javadoc bugs +
      +
    • Assert documentation [@stefanbirkner, fixing gh-134]
    • +
    • ClassRule [@stefanbirkner, fixing gh-254]
    • +
    • Parameterized [@stefanbirkner, fixing gh-89]
    • +
    • Parameterized, again [@orfjackal, fixing gh-285]
    • +
  • +
  • Miscellaneous +
      +
    • Useless code in RunAfters [@stefanbirkner, fixing gh-289]
    • +
    • Parameterized test classes should be able to have @Category annotations +[@dsaff, fixing gh-291]
    • +
    • Error count should be initialized in junit.tests.framework.TestListenerTest [@stefanbirkner, fixing gh-225]
    • +
    • AssertionFailedError constructor shouldn't call super with null message [@stefanbirkner, fixing gh-318]
    • +
    • Clearer error message for non-static inner test classes [@stefanbirkner, fixing gh-42]
    • +
  • +
+ +

Minor changes

+ +
    +
  • Description, Result and Failure are Serializable [@ephox-rob, closing gh-101]
  • +
  • FailOnTimeout is reusable, allowing for retrying Rules [@stefanbirkner, closing gh-265]
  • +
  • New ErrorCollector.checkThat overload, that allows you to specify a reason [@drothmaler, closing gh-300]
  • +
diff --git a/doc/ReleaseNotes4.10.md b/doc/ReleaseNotes4.10.md new file mode 100644 index 000000000000..0e609afb4d3d --- /dev/null +++ b/doc/ReleaseNotes4.10.md @@ -0,0 +1,86 @@ +## Summary of Changes in version 4.10 ## + +Thanks to a full cast of contributors of bug fixes and new features. + +A full summary of commits between 4.9 and 4.10 is on [github](https://github.com/junit-team/junit4/compare/r4.9...4.10) + +### junit-dep has correct contents ### + +junit-dep-4.9.jar incorrectly contained hamcrest classes, which could lead to version conflicts in projects that depend on hamcrest directly. This is fixed in 4.10 [@dsaff, closing gh-309] + +### RuleChain ### + +The RuleChain rule allows ordering of TestRules: + +```java +public static class UseRuleChain { + @Rule + public TestRule chain= RuleChain + .outerRule(new LoggingRule("outer rule") + .around(new LoggingRule("middle rule") + .around(new LoggingRule("inner rule"); + + @Test + public void example() { + assertTrue(true); + } +} +``` + +writes the log + + starting outer rule + starting middle rule + starting inner rule + finished inner rule + finished middle rule + finished outer rule + +### TemporaryFolder ### + +- `TemporaryFolder#newFolder(String... folderNames)` creates recursively deep temporary folders + [@rodolfoliviero, closing gh-283] +- `TemporaryFolder#newFile()` creates a randomly named new file, and `#newFolder()` creates a randomly named new folder + [@Daniel Rothmaler, closing gh-299] + +### Theories ### + +The `Theories` runner does not anticipate theory parameters that have generic +types, as reported by github#64. Fixing this won't happen until `Theories` is +moved to junit-contrib. In anticipation of this, 4.9.1 adds some of the +necessary machinery to the runner classes, and deprecates a method that only +the `Theories` runner uses, `FrameworkMethod`#producesType(). +The Common Public License that JUnit is released under is now included +in the source repository. + +Thanks to `@pholser` for identifying a potential resolution for github#64 +and initiating work on it. + +### Bug fixes ### + +- Built-in Rules implementations + - TemporaryFolder should not create files in the current working directory if applying the rule fails + [@orfjackal, fixing gh-278] + - TestWatcher and TestWatchman should not call failed for AssumptionViolatedExceptions + [@stefanbirkner, fixing gh-296] +- Javadoc bugs + - Assert documentation [@stefanbirkner, fixing gh-134] + - ClassRule [@stefanbirkner, fixing gh-254] + - Parameterized [@stefanbirkner, fixing gh-89] + - Parameterized, again [@orfjackal, fixing gh-285] +- Miscellaneous + - Useless code in RunAfters [@stefanbirkner, fixing gh-289] + - Parameterized test classes should be able to have `@Category` annotations + [@dsaff, fixing gh-291] + - Error count should be initialized in junit.tests.framework.TestListenerTest [@stefanbirkner, fixing gh-225] + - AssertionFailedError constructor shouldn't call super with null message [@stefanbirkner, fixing gh-318] + - Clearer error message for non-static inner test classes [@stefanbirkner, fixing gh-42] + +### Minor changes ### + +- Description, Result and Failure are Serializable [@ephox-rob, closing gh-101] +- FailOnTimeout is reusable, allowing for retrying Rules [@stefanbirkner, closing gh-265] +- New `ErrorCollector.checkThat` overload, that allows you to specify a reason [@drothmaler, closing gh-300] + + + diff --git a/doc/ReleaseNotes4.10.txt b/doc/ReleaseNotes4.10.txt new file mode 100644 index 000000000000..bc63f07611c7 --- /dev/null +++ b/doc/ReleaseNotes4.10.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.10.md diff --git a/doc/ReleaseNotes4.11.html b/doc/ReleaseNotes4.11.html new file mode 100644 index 000000000000..fefd79f6910a --- /dev/null +++ b/doc/ReleaseNotes4.11.html @@ -0,0 +1,121 @@ +

Summary of changes in version 4.11

+ +

Matchers: Upgrade to Hamcrest 1.3

+ +

JUnit now uses the latest version of Hamcrest. Thus, you can use all the available matchers and benefit from an improved assertThat which will now print the mismatch description from the matcher when an assertion fails.

+ +

Example

+ +
assertThat(Long.valueOf(1), instanceOf(Integer.class));
+
+ +

Old error message:

+ +
Expected: an instance of java.lang.Integer
+     got: <1L>
+
+ +

New error message:

+ +
Expected: an instance of java.lang.Integer
+     but: <1L> is a java.lang.Long
+
+ +

Hamcrest's new FeatureMatcher makes writing custom matchers that make use of custom mismatch descriptions quite easy:

+ +
@Test
+public void featureMatcher() throws Exception {
+    assertThat("Hello World!", length(is(0)));
+}
+
+private Matcher<String> length(Matcher<? super Integer> matcher) {
+    return new FeatureMatcher<String, Integer>(matcher, "a String of length that", "length") {
+        @Override
+        protected Integer featureValueOf(String actual) {
+            return actual.length();
+        }
+    };
+}
+
+ +

Running this test will return the following failure message:

+ +
Expected: a String of length that is <0>
+     but: length was <12>
+
+ +

Most of the matchers in JUnitMatchers have been deprecated. Please use org.hamcrest.CoreMatchers directly.

+ +

Parameterized Tests

+ +

In order to easily identify the individual test cases in a Parameterized test, you may provide a name using the @Parameters annotation. This name is allowed to contain placeholders that are replaced at runtime:

+ +
    +
  • {index}: the current parameter index
  • +
  • {0}, {1}, …: the first, second, and so on, parameter value
  • +
+ +

Example

+ +
@RunWith(Parameterized.class)
+public class FibonacciTest {
+
+    @Parameters(name = "{index}: fib({0})={1}")
+    public static Iterable<Object[]> data() {
+        return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
+                { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
+    }
+
+    private int input;
+    private int expected;
+
+    public FibonacciTest(int input, int expected) {
+        this.input = input;
+        this.expected = expected;
+    }
+
+    @Test
+    public void test() {
+        assertEquals(expected, Fibonacci.compute(input));
+    }
+}
+
+ +

In the example given above, the Parameterized runner creates names like [1: fib(3)=2]. If you don't specify a name, the current parameter index will be used by default.

+ +

Test execution order

+ +

By design, JUnit does not specify the execution order of test method invocations. Until now, the methods were simply invoked in the order returned by the reflection API. However, using the JVM order is unwise since the Java platform does not specify any particular order, and in fact JDK 7 returns a more or less random order. Of course, well-written test code would not assume any order, but some does, and a predictable failure is better than a random failure on certain platforms.

+ +

From now on, JUnit will by default use a deterministic, but not predictable, order (MethodSorters.DEFAULT). To change the test execution order simply annotate your test class using @FixMethodOrder and specify one of the available MethodSorters:

+ +
    +
  • @FixMethodOrder(MethodSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run.

  • +
  • @FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

  • +
+ +

Maven artifacts

+ +

Up until now there were two Maven artifacts for JUnit: junit:junit-dep and junit:junit. From a Maven point-of-view only the former made sense because it did not contain the Hamcrest classes but declared a dependency to the Hamcrest Maven artifact. The latter included the Hamcrest classes which was very un-Maven-like.

+ +

From this release on, you should use junit:junit which will be what junit:junit-dep used to. If you still reference junit:junit-dep, Maven will automatically relocate you to the new junit:junit and issue a warning for you to fix.

+ +

Rules

+ +

A number of improvements have been made to Rules:

+ +
    +
  • MethodRule is no longer deprecated.
  • +
  • Both @Rule and @ClassRule can now be used on methods that return a TestRule.
  • +
  • ExpectedException now always prints the stacktrace of the actual exception in case of failure.
  • +
  • A parent folder can be specified for TemporaryFolder. In addition, the newFile/newFolder methods will now fail when the file or folder could not be created.
  • +
  • TestWatcher has a new template method called skipped that is invoked when a test is skipped due to a failed assumption.
  • +
+ +

Improvements to Assert and Assume

+ +
    +
  • assertNotEquals has been added to Assert.
  • +
  • assertEquals has been overloaded in order to check whether two floats are equal given a certain float delta.
  • +
  • Most methods in Assume now allow to pass a custom message.
  • +
diff --git a/doc/ReleaseNotes4.11.md b/doc/ReleaseNotes4.11.md new file mode 100644 index 000000000000..740c64a09d7c --- /dev/null +++ b/doc/ReleaseNotes4.11.md @@ -0,0 +1,116 @@ +## Summary of changes in version 4.11 + +### Matchers: Upgrade to Hamcrest 1.3 + +JUnit now uses the latest version of Hamcrest. Thus, you can use all the available matchers and benefit from an improved `assertThat` which will now print the mismatch description from the matcher when an assertion fails. + +#### Example + +```java +assertThat(Long.valueOf(1), instanceOf(Integer.class)); +``` + +Old error message: + + Expected: an instance of java.lang.Integer + got: <1L> + +New error message: + + Expected: an instance of java.lang.Integer + but: <1L> is a java.lang.Long + +Hamcrest's new `FeatureMatcher` makes writing custom matchers that make use of custom mismatch descriptions quite easy: + +```java +@Test +public void featureMatcher() throws Exception { + assertThat("Hello World!", length(is(0))); +} + +private Matcher length(Matcher matcher) { + return new FeatureMatcher(matcher, "a String of length that", "length") { + @Override + protected Integer featureValueOf(String actual) { + return actual.length(); + } + }; +} +``` + +Running this test will return the following failure message: + + Expected: a String of length that is <0> + but: length was <12> + + +Most of the matchers in `JUnitMatchers` have been deprecated. Please use `org.hamcrest.CoreMatchers` directly. + +### Parameterized Tests + +In order to easily identify the individual test cases in a Parameterized test, you may provide a name using the `@Parameters` annotation. This name is allowed to contain placeholders that are replaced at runtime: + +* `{index}`: the current parameter index +* `{0}`, `{1}`, …: the first, second, and so on, parameter value + +#### Example + +```java +@RunWith(Parameterized.class) +public class FibonacciTest { + + @Parameters(name = "{index}: fib({0})={1}") + public static Iterable data() { + return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 }, + { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } }); + } + + private int input; + private int expected; + + public FibonacciTest(int input, int expected) { + this.input = input; + this.expected = expected; + } + + @Test + public void test() { + assertEquals(expected, Fibonacci.compute(input)); + } +} +``` + +In the example given above, the `Parameterized` runner creates names like `[1: fib(3)=2]`. If you don't specify a name, the current parameter index will be used by default. + +### Test execution order + +By design, JUnit does not specify the execution order of test method invocations. Until now, the methods were simply invoked in the order returned by the reflection API. However, using the JVM order is unwise since the Java platform does not specify any particular order, and in fact JDK 7 returns a more or less random order. Of course, well-written test code would not assume any order, but some does, and a predictable failure is better than a random failure on certain platforms. + +From now on, JUnit will by default use a deterministic, but not predictable, order (`MethodSorters.DEFAULT`). To change the test execution order simply annotate your test class using `@FixMethodOrder` and specify one of the available `MethodSorters`: + +* `@FixMethodOrder(MethodSorters.JVM)`: Leaves the test methods in the order returned by the JVM. This order may vary from run to run. + +* `@FixMethodOrder(MethodSorters.NAME_ASCENDING)`: Sorts the test methods by method name, in lexicographic order. + +### Maven artifacts + +Up until now there were two Maven artifacts for JUnit: `junit:junit-dep` and `junit:junit`. From a Maven point-of-view only the former made sense because it did not contain the Hamcrest classes but declared a dependency to the Hamcrest Maven artifact. The latter included the Hamcrest classes which was very un-Maven-like. + +From this release on, you should use `junit:junit` which will be what `junit:junit-dep` used to. If you still reference `junit:junit-dep`, Maven will automatically relocate you to the new `junit:junit` and issue a warning for you to fix. + +### Rules + +A number of improvements have been made to Rules: + +* `MethodRule` is no longer deprecated. +* Both `@Rule` and `@ClassRule` can now be used on methods that return a `TestRule`. +* `ExpectedException` now always prints the stacktrace of the actual exception in case of failure. +* A parent folder can be specified for `TemporaryFolder`. In addition, the `newFile`/`newFolder` methods will now fail when the file or folder could not be created. +* `TestWatcher` has a new template method called `skipped` that is invoked when a test is skipped due to a failed assumption. + +### Improvements to Assert and Assume + +* `assertNotEquals` has been added to `Assert`. +* `assertEquals` has been overloaded in order to check whether two floats are equal given a certain float delta. +* Most methods in `Assume` now allow to pass a custom message. + diff --git a/doc/ReleaseNotes4.11.txt b/doc/ReleaseNotes4.11.txt new file mode 100644 index 000000000000..2138b03b4480 --- /dev/null +++ b/doc/ReleaseNotes4.11.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.11.md diff --git a/doc/ReleaseNotes4.12.md b/doc/ReleaseNotes4.12.md new file mode 100644 index 000000000000..602d6bfa06e8 --- /dev/null +++ b/doc/ReleaseNotes4.12.md @@ -0,0 +1,732 @@ +## Summary of changes in version 4.12 + +# Assertions + +### [Pull request #611:](https://github.com/junit-team/junit4/pull/611) Assert.assertNotEquals() for `float` parameters + +Version 4.11 added `Assert.assertEquals()` for `float` parameters with a delta, and `Assert.assertNotEquals()`. This is the combination of those two features. + + +### [Pull request #632:](https://github.com/junit-team/junit4/pull/632) Assert.assertArrayEquals() for `boolean[]` parameters. + +`Assert.assertArrayEquals()` previously existed for all primitive array types, except `boolean[]`. This has now been added for `boolean[]`. + + +### [Pull request #918:](https://github.com/junit-team/junit4/pull/918) Avoid potentially expensive reflection-based loop in Assert.assertArrayEquals() + +In the usual case, where the array elements are in fact exactly equal, the potentially expensive reflection-based loop to compare them is avoided by using `Arrays.deepEquals()` first. The exact comparison is only executed when `deepEquals()` returns `false`. + + +# Command-line options +### [Pull request #647:](https://github.com/junit-team/junit4/pull/647) Support command-line `--filter` param. + +When running JUnit from the command line, a command-line parameter can be supplied using `--filter`, which supplies a filter that will restrict which tests and subtests from the rest of the command will be run. For example, this will run only the tests in ExampleTestSuite that are in categories Cat1 or Cat2: + +``` +java org.junit.runner.JUnitCore \ + --filter=org.junit.experimental.categories.IncludeCategories=pkg.of.Cat1,pkg.of.Cat2 \ + com.example.ExampleTestSuite +``` + +In general, the argument to `--filter` should be `ClassName=param`, where `ClassName` names an implementation of `FilterFactory`, whose `createFilter` method will be called with an instance of `FilterFactoryParams` that contains `"param"`, in order to return the filter to be applied. + +# Test Runners + + +### [Pull request #763:](https://github.com/junit-team/junit4/pull/763) Allow custom test runners to create their own TestClasses and customize the scanning of annotations. + +This introduces some extension points to `ParentRunner` to allow subclasses to control creation +of the `TestClass` instance and to scan for annotations. + +### [Pull request #817:](https://github.com/junit-team/junit4/pull/817) Support for context hierarchies + +The `AnnotatedBuilder` is a strategy for constructing runners for test classes that have been annotated with the `@RunWith` annotation. All tests within such a class will be executed using the runner that was specified within the annotation. + +Prior to JUnit 4.12, this covered only the tests within the annotated test class. With 4.12, the `AnnotationBuilder` will also support inner member classes. If a custom test runner supports inner member classes (which JUnit does not support out-of-the-box), the member classes will inherit the runner from the enclosing class, e.g.: + +```java +@RunWith(MyRunner.class) +public class MyTest { + // some tests might go here + + public class MyMemberClass { + @Test + public void thisTestRunsWith_MyRunner() { + // some test logic + } + + // some more tests might go here + } + + @RunWith(AnotherRunner.class) + public class AnotherMemberClass { + // some tests might go here + + public class DeepInnerClass { + @Test + public void thisTestRunsWith_AnotherRunner() { + // some test logic + } + } + + public class DeepInheritedClass extends SuperTest { + @Test + public void thisTestRunsWith_SuperRunner() { + // some test logic + } + } + } +} + +@RunWith(SuperRunner.class) +public class SuperTest { + // some tests might go here +} +``` + +The key points to note here are: + +* If there is no `@RunWith` annotation, no runner will be created. +* The resolve step is inside-out, e.g. the closest `@RunWith` annotation wins. +* `@RunWith` annotations are inherited and work as if the class was annotated itself. +* The default JUnit runner does not support inner member classes, so this is only valid for custom runners that support inner member classes. +* Custom runners with support for inner classes may or may not support `@RunWith` annotations for member classes. Please refer to the custom runner documentation. + +One example of a runner that makes use of this extension is the Hierarchical Context Runner (see https://github.com/bechte/junit-hierarchicalcontextrunner/wiki). + + +### [Pull request #716:](https://github.com/junit-team/junit4/pull/716) Fix annotation collection from superclasses of JUnit3 tests. + +Previously `Description.getAnnotations()` would always return an empty list for _test*_ methods derived from superclasses. + + +### [Pull request #625 (commit 72af03c49f):](https://github.com/junit-team/junit4/commit/72af03c49fdad5f10e36c7eb4e7045feb971d253) Make `RunNotifier` code concurrent. + +When running tests from multiple threads, JUnit will now call `RunListener` methods from multiple threads if the listener class is annotated with `@RunListener.ThreadSafe`. In addition, the code in `RunNotifier` has been modified to not use locks. + + +### [Pull request #684:](https://github.com/junit-team/junit4/pull/684) Adding `AnnotationValidator` framework and validation checks for `@Category`. + +This allows for validation to be added to annotations. Validators should extend `AnnotationValidator` and be attached to annotations with the `@ValidateWith` annotation. `CategoryValidator` extends `AnnotationValidator` and ensures that incompatible annotations (`@BeforeClass`, `@AfterClass`, `@Before`, `@After`) are not used in conjunction with `@Category`. + + +# Exception Testing + + +### [Pull request #583:](https://github.com/junit-team/junit4/pull/583) [Pull request #720:](https://github.com/junit-team/junit4/pull/720) Fix handling of `AssertionError` and `AssumptionViolatedException` in `ExpectedException` rule. + +`ExpectedException` didn't handle `AssertionError`s and `AssumptionViolatedException` well. This has been fixed. The new documentation explains the usage of `ExpectedException` for testing these exceptions. The two methods `handleAssertionErrors()` and `handleAssumptionViolatedExceptions()` are not needed anymore. If you have used them, just remove it and read `ExpectedException`'s documentation. + + +### [Pull request #818:](https://github.com/junit-team/junit4/pull/818) [Pull request #993:](https://github.com/junit-team/junit4/pull/993) External version of AssumptionViolatedException + +In JUnit 4.11 and earlier, if you wanted to write a custom runner that handled +`AssumptionViolatedException` or you needed to create an instance of `AssumptionViolatedException` +directly, you needed to import an internal class (`org.junit.internal.AssumptionViolatedException`). +Now you can import `org.junit.AssumptionViolatedException` (which extends +`org.junit.internal.AssumptionViolatedException`). + +The classes in `Assume` have been modified to throw `org.junit.AssumptionViolatedException`. + +The constructors in the external `AssumptionViolatedException` are also +simpler than the ones in the internal version. That being said, +it's recommended that you create `AssumptionViolatedException` via the methods in `Assume`. + + +### [Pull request #985:](https://github.com/junit-team/junit4/pull/985) Change AssumptionViolatedException to not set the cause to null; fixes issue #494 + +Previously, the `AssumptionViolatedException` constructors would explicitly set the cause to `null` +(unless you use a constructor where you provide a `Throwable`, in which case it would set that as +the cause). This prevented code directly creating the exception from setting a cause. + +With this change, the cause is only set if you pass in a `Throwable`. + +It's recommended that you create `AssumptionViolatedException` via the methods in `Assume`. + + +### [Pull request #542:](https://github.com/junit-team/junit4/pull/542) Customized failure message for `ExpectedException` + +`ExpectedException` now allows customization of the failure message when the test does not throw the expected exception. For example: + +```java +thrown.reportMissingExceptionWithMessage("FAIL: Expected exception to be thrown"); +``` + +If a custom failure message is not provided, a default message is used. + + +### [Pull request #1013:](https://github.com/junit-team/junit/pull/1013) Make ErrorCollector#checkSucceeds generic + +The method `ErrorCollector.checkSucceeds()` is now generic. Previously, you could only pass +in a `Callable` and it returned `Object`. You can now pass any `Callable` and the +return type will match the type of the callable. + + +# Timeout for Tests +*See also [Timeout for tests](https://github.com/junit-team/junit4/wiki/Timeout-for-tests)* + +### [Pull request #823:](https://github.com/junit-team/junit4/pull/823) Throw `TestFailedOnTimeoutException` instead of plain `Exception` on timeout + +When a test times out, a `org.junit.runners.model.TestTimedOutException` is now thrown instead of a plain `java.lang.Exception`. + + +### [Pull request #742:](https://github.com/junit-team/junit4/pull/742) [Pull request #986:](https://github.com/junit-team/junit4/pull/986) `Timeout` exceptions now include stack trace from stuck thread (experimental) + +`Timeout` exceptions try to determine if there is a child thread causing the problem, and if so its stack trace is included in the exception in addition to the one of the main thread. This feature must be enabled with the timeout rule by creating it through the new `Timeout.builder()` method: + +```java +public class HasGlobalTimeout { + @Rule public final TestRule timeout = Timeout.builder() + .withTimeout(10, TimeUnit.SECONDS) + .withLookingForStuckThread(true) + .build(); + + @Test + public void testInfiniteLoop() { + for (;;) { + } + } +} +``` + + +### [Pull request #544:](https://github.com/junit-team/junit4/pull/544) New constructor and factories in `Timeout` + +`Timeout` deprecated the old constructor `Timeout(int millis)`. +A new constructor is available: `Timeout(long timeout, TimeUnit unit)`. It enables you to use different granularities of time units like `NANOSECONDS`, `MICROSECONDS`, `MILLISECONDS`, and `SECONDS`. Examples: + +```java +@Rule public final TestRule globalTimeout = new Timeout(50, TimeUnit.MILLISECONDS); +``` + +```java +@Rule public final TestRule globalTimeout = new Timeout(10, TimeUnit.SECONDS); +``` + +and factory methods in `Timeout`: + +```java +@Rule public final TestRule globalTimeout = Timeout.millis(50); +``` + +```java +@Rule public final TestRule globalTimeout = Timeout.seconds(10); +``` + +This usage avoids the truncation, which was the problem in the deprecated constructor `Timeout(int millis)` when casting `long` to `int`. + + +### [Pull request #549:](https://github.com/junit-team/junit4/pull/549) fixes for #544 and #545 + +The `Timeout` rule applies the same timeout to all test methods in a class: + +```java +public class HasGlobalTimeout { + @Rule + public Timeout globalTimeout = new Timeout(10, TimeUnit.SECONDS); + + @Test + public void testInfiniteLoop() { + for (;;) { + } + } + + @Test + public synchronized void testInterruptableLock() throws InterruptedException { + wait(); + } + + @Test + public void testInterruptableIO() throws IOException { + for (;;) { + FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); + + // Interrupted thread closes channel and throws ClosedByInterruptException. + channel.write(buffer); + channel.close(); + } + } +} +``` +Each test is run in a new _daemon_ thread. If the specified timeout elapses before the test completes, its execution is interrupted via `Thread#interrupt()`. This happens in interruptable I/O (operations throwing `java.io.InterruptedIOException` and `java.nio.channels.ClosedByInterruptException`), locks (package `java.util.concurrent`) and methods in `java.lang.Object` and `java.lang.Thread` throwing `java.lang.InterruptedException`. + +### [Pull request #876:](https://github.com/junit-team/junit4/pull/876) The timeout rule never times out if you pass in a timeout of zero. + + +# Parameterized Tests + + +### [Pull request #702:](https://github.com/junit-team/junit4/pull/702) Support more return types for the `@Parameters` method of the `Parameterized` runner + +The return types `Iterator`, `Object[]` and `Object[][]` are now supported on methods annotated with `@Parameters`. You don't have to wrap arrays with `Iterable`s and single parameters with `Object` arrays. + + +### [Pull request #773:](https://github.com/junit-team/junit4/pull/773) Allow configurable creation of child runners of parameterized suites + +The factory for creating the `Runner` instance of a single set of parameters is now configurable. It can be specified by the `@UseParametersRunnerFactory` annotation. + + +# Rules + + +### [Pull request #552:](https://github.com/junit-team/junit4/pull/552) [Pull request #937:](https://github.com/junit-team/junit4/pull/937) `Stopwatch` rule + +The `Stopwatch` Rule notifies one of its own protected methods of the time spent by a test. Override them to get the time in nanoseconds. For example, this class will keep logging the time spent by each passed, failed, skipped, and finished test: + +```java +public static class StopwatchTest { + private static final Logger logger = Logger.getLogger(""); + + private static void logInfo(String testName, String status, long nanos) { + logger.info(String.format("Test %s %s, spent %d microseconds", + testName, status, Stopwatch.toMicros(nanos))); + } + + @Rule + public Stopwatch stopwatch = new Stopwatch() { + @Override + protected void succeeded(long nanos, Description description) { + logInfo(description.getMethodName(), "succeeded", nanos); + } + + @Override + protected void failed(long nanos, Throwable e, Description description) { + logInfo(description.getMethodName(), "failed", nanos); + } + + @Override + protected void skipped(long nanos, AssumptionViolatedException e, Description description) { + logInfo(description.getMethodName(), "skipped", nanos); + } + + @Override + protected void finished(long nanos, Description description) { + logInfo(description.getMethodName(), "finished", nanos); + } + }; + + @Test + public void succeeds() { + } + + @Test + public void fails() { + fail(); + } + + @Test + public void skips() { + assumeTrue(false); + } +} +``` + +An example to assert running time: + +```java +@Test +public void performanceTest() throws InterruptedException { + long delta = 30; + Thread.sleep(300L); + assertEquals(300D, stopwatch.runtime(MILLISECONDS), delta); + Thread.sleep(500L); + assertEquals(800D, stopwatch.runtime(MILLISECONDS), delta); +} +``` + +### [Pull request #932:](https://github.com/junit-team/junit4/pull/932) Allow static `@Rule`s also annotated with `@ClassRule` + +JUnit 4.11 introduced restrictions requiring `@Rule` members to be non-static and `@ClassRule` members to be static. These restrictions have been relaxed slightly, in that a static member annotated with both `@Rule` and `@ClassRule` is now considered valid. This means a single rule may be used to perform actions both before/after a class (e.g. setup/tear down an external resource) and between tests (e.g. reset the external resource), without the need for any workarounds mentioned in issue [#793](https://github.com/junit-team/junit4/issues/793). + +Note that a non-static `@ClassRule` annotated member is still considered invalid, even if annotated with `@Rule`. + +```java +public class CommonRuleTest { + @Rule + @ClassRule + public static MySetupResetAndTearDownRule rule = new MySetupResetAndTearDownRule(); +} +``` + +Be warned that if you have static methods or fields annotated with `@Rule` you will not be able to run your test methods in parallel. + +### [Pull request #956:](https://github.com/junit-team/junit4/pull/956) `DisableOnDebug` rule + +The `DisableOnDebug` rule allows users to disable other rules when the JVM is launched in debug mode. Prior to this feature the common approach to disable rules that make debugging difficult was to comment them out and remember to revert the change. When using this feature users no longer have to modify their test code nor do they need to remember to revert changes. + +This rule is particularly useful in combination with the `Timeout` rule. + +``` +@Rule +public DisableOnDebug timeout = new DisableOnDebug(Timeout.seconds(1)); +``` + +See the Javadoc for more detail and limitations. Related to https://github.com/junit-team/junit4/issues/738 + +### [Pull request #974:](https://github.com/junit-team/junit4/pull/974) Updated `TemporaryFolder.newFolder()` to give an error message if a path contains a slash. + +If you call `TemporaryFolder.newFolder("foo/bar")` in JUnit 4.10 the method returns a `File` object for the new folder but actually fails to create it. That is contrary to the expected behaviour of the method which is to actually create the folder. In JUnit 4.11 the same call throws an exception. Nowhere in the documentation does it explain that the String(s) passed to that method can only be single path components. + +With this fix, folder names are validated to contain single path name. If the folder name consists of multiple path names, an exception is thrown stating that usage of multiple path components in a string containing folder name is disallowed. + +### [Pull request #1015:](https://github.com/junit-team/junit4/pull/1015) Methods annotated with `Rule` can return a `MethodRule`. + +Methods annotated with `@Rule` can now return either a `TestRule` (or subclass) or a +`MethodRule` (or subclass). + +Prior to this change, all public methods annotated with `@Rule` were called, but the +return value was ignored if it could not be assigned to a `TestRule`. After this change, +the method is only called if the return type could be assigned to `TestRule` or +`MethodRule`. For methods annotated with `@Rule` that return other values, see the notes +for pull request #1020. + +### [Pull request #1020:](https://github.com/junit-team/junit4/pull/1020) Added validation that @ClassRule should only be implementation of TestRule. + +Prior to this change, fields annotated with `@ClassRule` that did not have a type of `TestRule` +(or a class that implements `TestRule`) were ignored. With this change, the test will fail +with a validation error. + +Prior to this change, methods annotated with `@ClassRule` that did specify a return type +of `TestRule`(or a class that implements `TestRule`) were ignored. With this change, the test +will fail with a validation error. + +### [Pull request #1021:](https://github.com/junit-team/junit4/pull/1021) JavaDoc of TemporaryFolder: folder not guaranteed to be deleted. + +Adjusted JavaDoc of TemporaryFolder to reflect that temporary folders are not guaranteed to be +deleted. + +# Theories + + +### [Pull request #529:](https://github.com/junit-team/junit4/pull/529) `@DataPoints`-annotated methods can now yield `null` values + +Up until JUnit 4.11 a `@DataPoints`-annotated array field could contain `null` values, but the array returned by a `@DataPoints`-annotated method could not. This asymmetry has been resolved: _both_ can now provide a `null` data point. + + +### [Pull request #572:](https://github.com/junit-team/junit4/pull/572) Ensuring no-generic-type-parms validator called/tested for theories + +The `Theories` runner now disallows `Theory` methods with parameters that have "unresolved" generic type parameters (e.g. `List` where `T` is a type variable). It is exceedingly difficult for the `DataPoint(s)` scraper or other `ParameterSupplier`s to correctly decide values that can legitimately be assigned to such parameters in a type-safe way, so JUnit now disallows them altogether. Theory parameters such as `List` and `Iterable` are still allowed. + +The machinery to perform this validation was in the code base for some time, but not used. It now is used. + +[junit.contrib](https://github.com/junit-team/junit.contrib)'s rendition of theories performs the same validation. + + +### [Pull request #607:](https://github.com/junit-team/junit4/pull/607) Improving theory failure messages + +Theory failure messages previously were of the form: `ParameterizedAssertionError: theoryTest(badDatapoint, allValues[1], otherVar)`, where allValues, badDatapoint and otherVar were the variables the datapoints was sourced from. These messages are now of the form: + +```java +ParameterizedAssertionError: theoryTest(null , "good value" , + [toString() threw RuntimeException: Error message] ) +``` + + +### [Pull request #601:](https://github.com/junit-team/junit4/pull/601) Allow use of `Assume` in tests run by `Theories` runner + +If, in a theory, all parameters were "assumed" away, the `Theories` runner would properly fail, informing you that no parameters were found to actually test something. However, if you had another method in that same class, that was not a theory (annotated with `@Test` only,) you could not use Assume in that test. Now, the `Theories` runner will verify the method is annotated with `@Theory` before failing due to no parameters being found. + +```java +@RunWith(Theories.class) +public class TheoriesAndTestsTogether { + @DataPoint + public static Object o; + + @Theory + public void theory(Object o) { + // this will still fail: java.lang.AssertionError: Never found parameters that satisfied method assumptions. + Assume.assumeTrue(false); + } + + @Test + public void test() { + // this will no longer fail + Assume.assumeTrue(false); + } +} +``` + + +### [Pull request #623:](https://github.com/junit-team/junit4/pull/623) Ensure data points array fields and methods are `public` and `static` in Theory classes. + +Previously if a data points array field or method was non-`static` or non-`public` it would be silently ignored and the data points not used. Now the `Theories` runner verifies that all `@DataPoint` or `@DataPoints` annotated fields or methods in classes are both `public` and `static`, and such classes will fail to run with `InitializationError`s if they are not. + + +### [Pull request #621:](https://github.com/junit-team/junit4/pull/621) Added mechanism for matching specific data points in theories to specific parameters, by naming data points. + +`@DataPoints` fields or methods can now be given (one or more) names in the annotation, and `@Theory` method parameters can be annotated with `@FromDataPoints(name)`, to limit the data points considered for that parameter to only the data points with that name: + +```java +@DataPoints +public static String[] unnamed = new String[] { ... }; + +@DataPoints("regexes") +public static String[] regexStrings = new String[] { ... }; + +@DataPoints({"forMatching", "alphanumeric"}) +public static String[] testStrings = new String[] { ... }; + +@Theory +public void stringTheory(String param) { + // This will be called with every value in 'regexStrings', + // 'testStrings' and 'unnamed'. +} + +@Theory +public void regexTheory(@FromDataPoints("regexes") String regex, + @FromDataPoints("forMatching") String value) { + // This will be called with only the values in 'regexStrings' as + // regex, only the values in 'testStrings' as value, and none + // of the values in 'unnamed'. +} +``` + + +### [Pull request #654:](https://github.com/junit-team/junit4/pull/654) Auto-generation of `enum` and `boolean` data points + +Any theory method parameters with `boolean` or `enum` types that cannot be supplied with values by any other sources will be automatically supplied with default values: `true` and `false`, or every value of the given `enum`. If other explicitly defined values are available (e.g. from a specified `ParameterSupplier` or some `DataPoints` method in the theory class), only those explicitly defined values will be used. + + +### [Pull request #651:](https://github.com/junit-team/junit4/pull/651) Improvements to Theory parameter and DataPoint type matching + + * Validity of `DataPoints` for theory parameters for all field data points and multi-valued method data points (i.e. not single-valued method data points) is now done on runtime type, not field/method return type (previously this was the case for multi-valued array methods only). + + * Validity of `DataPoints` for theory parameters for all data points now correctly handles boxing and unboxing for primitive and wrapper types; e.g. `int` values will be considered for theory parameters that are `Integer` assignable, and vice versa. + + +### [Pull request #639:](https://github.com/junit-team/junit4/pull/639) Failing theory datapoint methods now cause theory test failures + +Previously `@DataPoint(s)` methods that threw exceptions were quietly ignored and if another `DataPoint` source was available then those values alone were used, leaving the theory passing using only a subset of the (presumably) intended input values. Now, any data point method failures during invocation of a theory will cause the theory being tested to fail immediately. + +*This is a non-backward-compatible change*, and could potentially break theory tests that depended on failing methods. If that was desired behavior, then the expected exceptions can instead be specifically ignored using the new `ignoredExceptions` array attribute on `@DataPoint` and `@DataPoints` methods. Adding an exception to this `ignoredExceptions` array will stop theory methods from failing if the given exception, or subclasses of it, are thrown in the annotated method. This attribute has no effect on data point fields. + + +### [Pull request #658:](https://github.com/junit-team/junit4/pull/658) `Iterable`s can now be used as data points + +Previously, when building sets of data points for theory parameters, the only valid multi-valued `@DataPoints` types were arrays. This has now been extended to also take parameters from `Iterable` `@DataPoints` methods and fields. + + +# Categories + + +### [Pull request #566:](https://github.com/junit-team/junit4/pull/566) Enables inheritance on `Category` by adding `@Inherited` + +`@interface Category` now is annotated with `@Inherited` itself. This enables inheritance of categories from ancestors (e.g. abstract test-classes). Note that you are able to "overwrite" `@Category` on inheritors and that this has no effect on method-level categories (see [@Inherited](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/annotation/Inherited.html)). + + +### [Pull request #503:](https://github.com/junit-team/junit4/pull/503) Configurable Categories + +From a given set of test classes, the `Categories` runner runs only the classes and methods +that are annotated with either the category given with the `@IncludeCategory` annotation, or a subtype of that category. Either classes or interfaces can be used as categories. Subtyping works, so if you say `@IncludeCategory(SuperClass.class)`, a test marked `@Category({SubClass.class})` will be run. + +You can also exclude categories by using the `@ExcludeCategory` annotation; see `SlowTestSuiteWithoutFast`. + +The suite `FastOrSmokeTestSuite` is an example to run multiple categories. + +To execute tests which match all categories, use `matchAny = false` in annotations. See `FastAndSmokeTestSuite`. + +Example: + +```java +public static interface FastTests { /* category marker */ } +public static interface SlowTests { /* category marker */ } +public static interface SmokeTests { /* category marker */ } + +public static class A { + public void a() { + fail(); + } + + @Category(SlowTests.class) + @Test + public void b() { + } + + @Category({FastTests.class, SmokeTests.class}) + @Test + public void c() { + } +} + +@Category({SlowTests.class, FastTests.class}) +public static class B { + @Test + public void d() { + } +} + +@RunWith(Categories.class) +@Categories.IncludeCategory(SlowTests.class) +@Suite.SuiteClasses({A.class, B.class}) +public static class SlowTestSuite { + // Will run A.b and B.d, but not A.a and A.c +} + +@RunWith(Categories.class) +@Categories.IncludeCategory({FastTests.class, SmokeTests.class}) +@Suite.SuiteClasses({A.class, B.class}) +public static class FastOrSmokeTestSuite { + // Will run A.c and B.d, but not A.b because it is not any of FastTests or SmokeTests +} + +@RunWith(Categories.class) +@Categories.IncludeCategory(value = {FastTests.class, SmokeTests.class}, matchAny = false) +@Suite.SuiteClasses({A.class, B.class}) +public static class FastAndSmokeTestSuite { + // Will run only A.c => match both FastTests AND SmokeTests +} + +@RunWith(Categories.class) +@Categories.IncludeCategory(SlowTests.class) +@Categories.ExcludeCategory(FastTests.class) +@Suite.SuiteClasses({A.class, B.class}) // Note that Categories is a kind of Suite +public class SlowTestSuiteWithoutFast { + // Will run A.b, but not A.a, A.c or B.d +} +``` + + +# Use with Maven + + +### [Pull request #879:] (https://github.com/junit-team/junit4/pull/879) Add the default 'Implementation-*' headers to the manifest + +The default Maven-style 'Implementation-*' headers are now present in the manifest of `junit.jar`. Example: +``` +Implementation-Vendor: JUnit +Implementation-Title: JUnit +Implementation-Version: 4.12 +Implementation-Vendor-Id: junit +``` + + +### [Pull request #511:](https://github.com/junit-team/junit4/pull/511) Maven project junit:junit:jar + + +#### How to install Maven + +Download the Maven binary [http://www.us.apache.org/dist/maven/maven-3/3.0.4/binaries](http://www.us.apache.org/dist/maven/maven-3/3.0.4/binaries). + +(wget http://www.us.apache.org/dist/maven/maven-3/3.0.4/binaries/apache-maven-3.0.4-bin.tar.gz) + +If you are in the project root, extract the archive (tar xvzf apache-maven-3.0.4-bin.tar.gz). +Create directory _.m2_ in your _user home_. Then the artifacts and plugins are stored in `~/.m2/repository`. +( _~_ stands for user home) + + +#### How to launch the build from the command line + +Clone the project (git clone https://github.com/junit-team/junit4.git) and navigate to the project root on your local system (cd junit). +Clean the previous build in _target_ directory, build the project, and install new artifacts in your local repository: + +`apache-maven-3.0.4/bin/mvn clean install` + +On Windows type the command `apache-maven-3.0.4\bin\mvn clean install`. + +Set the environment variables `M2_HOME` and `PATH` when frequently building via command line `mvn clean install`. + +[http://maven.apache.org/guides/development/guide-building-m2.html#Building_Maven_Without_Maven_Installed](http://maven.apache.org/guides/development/guide-building-m2.html#Building_Maven_Without_Maven_Installed) + + +#### How to install and build the Maven project in Eclipse + +I made a clone of JUnit project from GitHub to local folder `C:\cygwin\usr\local\etc\junit`. + +In menu go to _File -> Import..._ + +In the popup menu open section _Maven_, click on _Existing Maven Projects_ and click on _Next_. In _Import Maven Projects_ specify the project root, and next proceed further with installing maven support plugin in Eclipse. + +You have created the Maven project, and now build the project. + +In the Package Explorer click on _pom.xml_. In the menu _Run -> Run As -> 2 Maven build..._ open the popup _Edit Configuration_ and specify the build phase _clean install_ in section _Goals_. Click on _Run_ and build the project. + +#### How to install and build the Maven project in IntelliJ IDEA + +In IDEA menu create a new project _File -> New Project..._. + +Select _Create Java project from existing sources_, then click on Next and specify _Project file location_. + +On the right-hand side is the _Maven Projects_ tab. Click on + and add _pom.xml_ into the project. Then click on the icon _Maven Settings_, and set _Maven home directory_ as the location of extracted Maven archive on your system. Click on the green triangle and launch the build. + +See the IntelliJ IDEA Web help +[http://www.jetbrains.com/idea/webhelp/maven-2.html](http://www.jetbrains.com/idea/webhelp/maven-2.html) + +#### How to install the Maven project with documentation +Use the profile `generate-docs` to build _sources.jar_ and _javadoc.jar_. Building Maven site is not yeat supported. + +Example: `mvn -Pgenerate-docs install` + +#### How to activate and deactivate Maven profiles in Integrated Development Environments: + +In _Eclipse_, from the main menu navigate to Run -> Run As -> 2 Maven build..., open the popup _Edit Configuration_ and specify the profiles. + +Follow this link for _IntelliJ IDEA_: [http://www.jetbrains.com/idea/webhelp/activating-and-deactivating-maven-profiles.html](http://www.jetbrains.com/idea/webhelp/activating-and-deactivating-maven-profiles.html) + + +# Miscellaneous + + +### [Pull request #776:](https://github.com/junit-team/junit4/pull/776) Add support for [Travis CI](http://travis-ci.org) + +Travis CI is a free CI server for public Github repositories. Every pull request is run by Travis CI and Github's web interface shows the CI result for each pull request. Every user can use Travis CI for testing her branches, too. + +### [Pull request #921:](https://github.com/junit-team/junit4/pull/921) Apply Google Code Style + +JUnit is now using the well documented [Google Code Style](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html) + +### [Pull request #939](https://github.com/junit-team/junit4/pull/939) Renamed license file + +While using JUnit in Android apps, if any other referenced library has a file named `LICENSE.txt`, the APK generation failed with the following error - + +`Error generating final archive: Found duplicate file for APK: LICENSE.txt` + +To avoid this, the license file has been renamed to `LICENSE-junit.txt` + + +### [Pull request #962:](https://github.com/junit-team/junit4/pull/962) Do not include thread start time in test timeout measurements. + +The time it takes to start a thread can be surprisingly large. +Especially in virtualized cloud environments where noisy neighbours. +This change reduces the probability of non-deterministic failures of +tests with timeouts (@Test(timeout=…)) by not beginning the timeout +clock until we have observed the starting of the task thread – the +thread that runs the actual test. This should make tests with small +timeout values more reliable in general, and especially in cloud CI +environments. + +# Fixes to issues introduced in JUnit 4.12 + +The following section lists fixes to problems introduced in the first +release candidates for JUnit 4.12. You can ignore this section if you are +trying to understand the changes between 4.11 and 4.12. + +### [Pull request #961:](https://github.com/junit-team/junit4/pull/961) Restore field names with f prefix. + +In order to make the JUnit code more consistent with current coding practices, we changed +a number of field names to not start with the prefix "f". Unfortunately, at least one IDE +referenced a private field via reflection. This change reverts the field names for fields +known to be read via reflection. + +### [Pull request #988:](https://github.com/junit-team/junit4/pull/988) Revert "Delete classes that are deprecated for six years." + +In [745ca05](https://github.com/junit-team/junit4/commit/745ca05dccf5cc907e43a58142bb8be97da2b78f) +we removed classes that were deprecated for many releases. There was some concern that people +might not expect classes to be removed in a 4.x release. Even though we are not aware of any +problems from the deletion, we decided to add them back. + +These classes may be removed in JUnit 5.0 or later. + +### [Pull request #989:](https://github.com/junit-team/junit4/pull/989) Add JUnitSystem.exit() back. + +In [917a88f](https://github.com/junit-team/junit4/commit/917a88fad06ce108a596a8fdb4607b1a2fbb3f3e) +the exit() method in JUnit was removed. This caused problems for at least one user. Even +though this class is in an internal package, we decided to add it back, and deprecated it. + +This method may be removed in JUnit 5.0 or later. + +### [Pull request #994:](https://github.com/junit-team/junit4/pull/994) [Pull request #1000:](https://github.com/junit-team/junit4/pull/1000) Ensure serialization compatibility where possible. + +JUnit 4.12 RC1 introduced serilization incompatibilities with some of the classes. For example, +these pre-release versions of JUnit could not read instances of `Result` that were serialized +in JUnit 4.11 and earlier. These changes fix that problem. + diff --git a/doc/ReleaseNotes4.13.md b/doc/ReleaseNotes4.13.md new file mode 100644 index 000000000000..f9dec0ab5925 --- /dev/null +++ b/doc/ReleaseNotes4.13.md @@ -0,0 +1,6 @@ +## Summary of changes in version 4.13 [unreleased!] + +We collect release notes in the wiki: +https://github.com/junit-team/junit4/wiki/4.13-release-notes + +This file will be updated right before release. diff --git a/doc/ReleaseNotes4.4.html b/doc/ReleaseNotes4.4.html new file mode 100644 index 000000000000..383d7b504038 --- /dev/null +++ b/doc/ReleaseNotes4.4.html @@ -0,0 +1,271 @@ +

Summary of Changes in version 4.5

+ +

Categories

+ +

Each test method and test class can be annotated as belonging to a category:

+ +
public static class SomeUITests {
+    @Category(UserAvailable.class)
+    @Test
+    public void askUserToPressAKey() { }
+
+    @Test
+    public void simulatePressingKey() { }
+}
+
+@Category(InternetConnected.class)
+public static class InternetTests {
+    @Test
+    public void pingServer() { }
+}
+
+ +

To run all of the tests in a particular category, you must currently explicitly create a custom request:

+ +
new JUnitCore().run(Request.aClass(SomeUITests.class).inCategories(UserAvailable.class));
+
+ +

This feature will very likely be improved before the final release of JUnit 4.5

+ +

Miscellaneous

+ +
    +
  • @Before and @After methods are run before and after each set of attempted parameters +on a Theory

  • +
  • Refactoring removed duplication that used to exist in classes MethodRoadie and ClassRoadie

  • +
  • Exposed API ParameterSignature.getType()

  • +
+ +

Summary of Changes in version 4.4

+ +

JUnit is designed to efficiently capture developers' intentions about +their code, and quickly check their code matches those intentions. +Over the last year, we've been talking about what things developers +would like to say about their code that have been difficult in the +past, and how we can make them easier.

+ +

Download

+ +

assertThat

+ +

Two years ago, Joe Walnes built a new assertion mechanism on top of what was +then JMock 1. The method name was assertThat, and the syntax looked like this:

+ +
assertThat(x, is(3));
+assertThat(x, is(not(4)));
+assertThat(responseString, either(containsString("color")).or(containsString("colour")));
+assertThat(myList, hasItem("3"));
+
+ +

More generally:

+ +
assertThat([value], [matcher statement]);
+
+ +

Advantages of this assertion syntax include:

+ +
    +
  • More readable and typeable: this syntax allows you to think in terms of subject, verb, object +(assert "x is 3") rather than assertEquals, which uses verb, object, subject (assert "equals 3 x")

  • +
  • Combinations: any matcher statement s can be negated (not(s)), combined (either(s).or(t)), +mapped to a collection (each(s)), or used in custom combinations (afterFiveSeconds(s))

  • +
  • Readable failure messages. Compare

    + +
    assertTrue(responseString.contains("color") || responseString.contains("colour"));
    +// ==> failure message: 
    +// java.lang.AssertionError:
    +
    +
    +assertThat(responseString, anyOf(containsString("color"), containsString("colour")));
    +// ==> failure message:
    +// java.lang.AssertionError: 
    +// Expected: (a string containing "color" or a string containing "colour")
    +//      got: "Please choose a font"
    +
  • +
  • Custom Matchers. By implementing the Matcher interface yourself, you can get all of the +above benefits for your own custom assertions.

  • +
  • For a more thorough description of these points, see Joe Walnes's +original post.

  • +
+ +

We have decided to include this API directly in JUnit. +It's an extensible and readable syntax, and it enables +new features, like assumptions and theories.

+ +

Some notes:

+ +
    +
  • The old assert methods are never, ever, going away. Developers may +continue using the old assertEquals, assertTrue, and so on.
  • +
  • The second parameter of an assertThat statement is a Matcher. +We include the Matchers we want as static imports, like this:

    + +
    import static org.hamcrest.CoreMatchers.is;
    +
    + +

    or:

    + +
    import static org.hamcrest.CoreMatchers.*;
    +
  • +
  • Manually importing Matcher methods can be frustrating. Eclipse 3.3 includes the ability to +define +"Favorite" classes to import static methods from, which makes it easier +(Search for "Favorites" in the Preferences dialog). +We expect that support for static imports will improve in all Java IDEs in the future.

  • +
  • To allow compatibility with a wide variety of possible matchers, +we have decided to include the classes from hamcrest-core, +from the Hamcrest project. This is the first time that +third-party classes have been included in JUnit.

  • +
  • JUnit currently ships with a few matchers, defined in +org.hamcrest.CoreMatchers and org.junit.matchers.JUnitMatchers.
    +To use many, many more, consider downloading the full hamcrest package.

  • +
  • JUnit contains special support for comparing string and array +values, giving specific information on how they differ. This is not +yet available using the assertThat syntax, but we hope to bring +the two assert methods into closer alignment in future releases.

  • +
+ +

+ +

Assumptions

+ +

Ideally, the developer writing a test has control of all of the forces that might cause a test to fail. +If this isn't immediately possible, making dependencies explicit can often improve a design.
+For example, if a test fails when run in a different locale than the developer intended, +it can be fixed by explicitly passing a locale to the domain code.

+ +

However, sometimes this is not desirable or possible.
+It's good to be able to run a test against the code as it is currently written, +implicit assumptions and all, or to write a test that exposes a known bug. +For these situations, JUnit now includes the ability to express "assumptions":

+ +
import static org.junit.Assume.*
+
+@Test public void filenameIncludesUsername() {
+   assumeThat(File.separatorChar, is('/'));
+   assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg"));
+}
+
+@Test public void correctBehaviorWhenFilenameIsNull() {
+   assumeTrue(bugFixed("13356"));  // bugFixed is not included in JUnit
+   assertThat(parse(null), is(new NullDocument()));
+}
+
+ +

With this release, a failed assumption will lead to the test being marked as passing, +regardless of what the code below the assumption may assert. +In the future, this may change, and a failed assumption may lead to the test being ignored: +however, third-party runners do not currently allow this option.

+ +

We have included assumeTrue for convenience, but thanks to the +inclusion of Hamcrest, we do not need to create assumeEquals, +assumeSame, and other analogues to the assert* methods. All of +those functionalities are subsumed in assumeThat, with the appropriate +matcher.

+ +

A failing assumption in a @Before or @BeforeClass method will have the same effect +as a failing assumption in each @Test method of the class.

+ +

+ +

Theories

+ +

More flexible and expressive assertions, combined with the ability to +state assumptions clearly, lead to a new kind of statement of intent, +which we call a "Theory". A test captures the intended behavior in +one particular scenario. A theory captures some aspect of the +intended behavior in possibly +infinite numbers of potential scenarios. For example:

+ +
@RunWith(Theories.class)
+public class UserTest {
+  @DataPoint public static String GOOD_USERNAME = "optimus";
+  @DataPoint public static String USERNAME_WITH_SLASH = "optimus/prime";
+
+  @Theory public void filenameIncludesUsername(String username) {
+    assumeThat(username, not(containsString("/")));
+    assertThat(new User(username).configFileName(), containsString(username));
+  }
+}
+
+ +

This makes it clear that the user's filename should be included in the +config file name, only if it doesn't contain a slash. Another test +or theory might define what happens when a username does contain a slash.

+ +

UserTest will attempt to run filenameIncludesUsername on +every compatible DataPoint defined in the class. If any of the +assumptions fail, the data point is silently ignored. If all of the +assumptions pass, but an assertion fails, the test fails.

+ +

The support for Theories has been absorbed from the Popper +project, and more complete documentation can be found +there.

+ +

Defining general statements in this way can jog the developer's memory +about other potential data points and tests, also allows automated +tools to search for new, unexpected data +points that expose bugs.

+ +

Other changes

+ +

This release contains other bug fixes and new features. Among them:

+ +
    +
  • Annotated descriptions

    + +

    Runner UIs, Filters, and Sorters operate on Descriptions of test +methods and test classes. These Descriptions now include the +annotations on the original Java source element, allowing for richer +display of test results, and easier development of annotation-based +filters.

  • +
  • Bug fix (1715326): assertEquals now compares all Numbers using their +native implementation of equals. This assertion, which passed in +4.3, will now fail:

    + +
    assertEquals(new Integer(1), new Long(1));
    +
    + +

    Non-integer Numbers (Floats, Doubles, BigDecimals, etc), +which were compared incorrectly in 4.3, are now fixed.

  • +
  • assertEquals(long, long) and assertEquals(double, double) have +been re-introduced to the Assert class, to take advantage of +Java's native widening conversions. Therefore, this still passes:

    + +
    assertEquals(1, 1L);
    +
  • +
  • The default runner for JUnit 4 test classes has been refactored. +The old version was named TestClassRunner, and the new is named +JUnit4ClassRunner. Likewise, OldTestClassRunner is now +JUnit3ClassRunner. The new design allows variations in running +individual test classes to be expressed with fewer custom classes. +For a good example, see the source to +org.junit.experimental.theories.Theories.

  • +
  • The rules for determining which runner is applied by default to a +test class have been simplified:

    + +
      +
    1. If the class has a @RunWith annotation, the annotated runner +class is used.

    2. +
    3. If the class can be run with the JUnit 3 test runner (it +subclasses TestCase, or contains a public static Test suite() +method), JUnit38ClassRunner is used.

    4. +
    5. Otherwise, JUnit4ClassRunner is used.

    6. +
    + +

    This default guess can always be overridden by an explicit +@RunWith(JUnit4ClassRunner.class) or +@RunWith(JUnit38ClassRunner.class) annotation.

    + +

    The old class names TestClassRunner and OldTestClassRunner +remain as deprecated.

  • +
  • Bug fix (1739095): Filters and Sorters work correctly on test +classes that contain a suite method like:

    + +
    public static junit.framework.Test suite() {
    +  return new JUnit4TestAdapter(MyTest.class);
    +}
    +
  • +
  • Bug fix (1745048): @After methods are now correctly called +after a test method times out.

  • +
diff --git a/doc/ReleaseNotes4.4.md b/doc/ReleaseNotes4.4.md new file mode 100644 index 000000000000..2be5e49bd01f --- /dev/null +++ b/doc/ReleaseNotes4.4.md @@ -0,0 +1,319 @@ +## Summary of Changes in version 4.5 ## + +### Categories ### +Each test method and test class can be annotated as belonging to a _category_: + +```java +public static class SomeUITests { + @Category(UserAvailable.class) + @Test + public void askUserToPressAKey() { } + + @Test + public void simulatePressingKey() { } +} + +@Category(InternetConnected.class) +public static class InternetTests { + @Test + public void pingServer() { } +} +``` + +To run all of the tests in a particular category, you must currently explicitly create a custom request: + +```java +new JUnitCore().run(Request.aClass(SomeUITests.class).inCategories(UserAvailable.class)); +``` + +This feature will very likely be improved before the final release of JUnit 4.5 + +### Theories ### + +- `@Before` and `@After` methods are run before and after each set of attempted parameters + on a Theory, and each set of parameters is run on a new instance of the test class. + +- Exposed API's `ParameterSignature.getType()` and `ParameterSignature.getAnnotations()` + +- An array of data points can be introduced by a field or method marked with the new annotation `@DataPoints` + +- The Theories custom runner has been refactored to make it easier to extend + +### JUnit 4 Runner API ### + +- There has been a drastic rewrite of the API for custom Runners in 4.5. This + needs to be written up separately before release. + +- Tests with failed assumptions are now marked as Ignored, rather than silently passing. + This may change behavior in some client tests, and also will require some new support + on the part of IDE's. + +## Summary of Changes in version 4.4 ## + +JUnit is designed to efficiently capture developers' intentions about +their code, and quickly check their code matches those intentions. +Over the last year, we've been talking about what things developers +would like to say about their code that have been difficult in the +past, and how we can make them easier. + +[Download][] + +[Download]: http://sourceforge.net/project/showfiles.php?group_id=15278 + +### assertThat ### + +Two years ago, Joe Walnes built a [new assertion mechanism][walnes] on top of what was +then [JMock 1][]. The method name was `assertThat`, and the syntax looked like this: + +[walnes]: http://joewalnes.com/2005/05/13/flexible-junit-assertions-with-assertthat/ +[JMock 1]: http://www.jmock.org/download.html + +```java +assertThat(x, is(3)); +assertThat(x, is(not(4))); +assertThat(responseString, either(containsString("color")).or(containsString("colour"))); +assertThat(myList, hasItem("3")); +``` + +More generally: + +```java +assertThat([value], [matcher statement]); +``` + +Advantages of this assertion syntax include: + +- More readable and typeable: this syntax allows you to think in terms of subject, verb, object + (assert "x is 3") rather than `assertEquals`, which uses verb, object, subject (assert "equals 3 x") + +- Combinations: any matcher statement `s` can be negated (`not(s)`), combined (`either(s).or(t)`), + mapped to a collection (`each(s)`), or used in custom combinations (`afterFiveSeconds(s)`) + +- Readable failure messages. Compare + +```java +assertTrue(responseString.contains("color") || responseString.contains("colour")); +// ==> failure message: +// java.lang.AssertionError: + +assertThat(responseString, anyOf(containsString("color"), containsString("colour"))); +// ==> failure message: +// java.lang.AssertionError: +// Expected: (a string containing "color" or a string containing "colour") +// got: "Please choose a font" +``` + +- Custom Matchers. By implementing the `Matcher` interface yourself, you can get all of the + above benefits for your own custom assertions. + +- For a more thorough description of these points, see [Joe Walnes's + original post][walnes]. + +We have decided to include this API directly in JUnit. +It's an extensible and readable syntax, and it enables +new features, like [assumptions][] and [theories][]. + +[assumptions]: #assumptions +[theories]: #theories + +Some notes: + +- The old assert methods are never, ever, going away. Developers may + continue using the old `assertEquals`, `assertTrue`, and so on. +- The second parameter of an `assertThat` statement is a `Matcher`. + We include the Matchers we want as static imports, like this: + +```java +import static org.hamcrest.CoreMatchers.is; +``` + + or: + +```java +import static org.hamcrest.CoreMatchers.*; +``` + +- Manually importing `Matcher` methods can be frustrating. [Eclipse 3.3][] includes the ability to + define + "Favorite" classes to import static methods from, which makes it easier + (Search for "Favorites" in the Preferences dialog). + We expect that support for static imports will improve in all Java IDEs in the future. + +[Eclipse 3.3]: http://www.eclipse.org/downloads/ + +- To allow compatibility with a wide variety of possible matchers, + we have decided to include the classes from hamcrest-core, + from the [Hamcrest][] project. This is the first time that + third-party classes have been included in JUnit. + +[Hamcrest]: http://code.google.com/p/hamcrest/ + +- JUnit currently ships with a few matchers, defined in + `org.hamcrest.CoreMatchers` and `org.junit.matchers.JUnitMatchers`. + To use many, many more, consider downloading the [full hamcrest package][]. + +[full hamcrest package]: http://hamcrest.googlecode.com/files/hamcrest-all-1.1.jar + +- JUnit contains special support for comparing string and array + values, giving specific information on how they differ. This is not + yet available using the `assertThat` syntax, but we hope to bring + the two assert methods into closer alignment in future releases. + + +### Assumptions ### + +Ideally, the developer writing a test has control of all of the forces that might cause a test to fail. +If this isn't immediately possible, making dependencies explicit can often improve a design. +For example, if a test fails when run in a different locale than the developer intended, +it can be fixed by explicitly passing a locale to the domain code. + +However, sometimes this is not desirable or possible. +It's good to be able to run a test against the code as it is currently written, +implicit assumptions and all, or to write a test that exposes a known bug. +For these situations, JUnit now includes the ability to express "assumptions": + +```java +import static org.junit.Assume.* + +@Test public void filenameIncludesUsername() { + assumeThat(File.separatorChar, is('/')); + assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg")); +} + +@Test public void correctBehaviorWhenFilenameIsNull() { + assumeTrue(bugFixed("13356")); // bugFixed is not included in JUnit + assertThat(parse(null), is(new NullDocument())); +} +``` + +With this release, a failed assumption will lead to the test being marked as passing, +regardless of what the code below the assumption may assert. +In the future, this may change, and a failed assumption may lead to the test being ignored: +however, third-party runners do not currently allow this option. + +We have included `assumeTrue` for convenience, but thanks to the +inclusion of Hamcrest, we do not need to create `assumeEquals`, +`assumeSame`, and other analogues to the `assert*` methods. All of +those functionalities are subsumed in `assumeThat`, with the appropriate +matcher. + +A failing assumption in a `@Before` or `@BeforeClass` method will have the same effect +as a failing assumption in each `@Test` method of the class. + + +### Theories ### + +More flexible and expressive assertions, combined with the ability to +state assumptions clearly, lead to a new kind of statement of intent, +which we call a "Theory". A test captures the intended behavior in +one particular scenario. A theory captures some aspect of the +intended behavior in possibly +infinite numbers of potential scenarios. For example: + +```java +@RunWith(Theories.class) +public class UserTest { + @DataPoint public static String GOOD_USERNAME = "optimus"; + @DataPoint public static String USERNAME_WITH_SLASH = "optimus/prime"; + + @Theory public void filenameIncludesUsername(String username) { + assumeThat(username, not(containsString("/"))); + assertThat(new User(username).configFileName(), containsString(username)); + } +} +``` + +This makes it clear that the user's filename should be included in the +config file name, only if it doesn't contain a slash. Another test +or theory might define what happens when a username does contain a slash. + +`UserTest` will attempt to run `filenameIncludesUsername` on +every compatible `DataPoint` defined in the class. If any of the +assumptions fail, the data point is silently ignored. If all of the +assumptions pass, but an assertion fails, the test fails. + +The support for Theories has been absorbed from the [Popper][] +project, and [more complete documentation][popper-docs] can be found +there. + +[Popper]: http://popper.tigris.org +[popper-docs]: http://popper.tigris.org/tutorial.html + +Defining general statements in this way can jog the developer's memory +about other potential data points and tests, also allows [automated +tools][junit-factory] to [search][my-blog] for new, unexpected data +points that expose bugs. + +[junit-factory]: http://www.junitfactory.org +[my-blog]: http://shareandenjoy.saff.net/2007/04/popper-and-junitfactory.html + +### Other changes ### + +This release contains other bug fixes and new features. Among them: + +- Annotated descriptions + + Runner UIs, Filters, and Sorters operate on Descriptions of test + methods and test classes. These Descriptions now include the + annotations on the original Java source element, allowing for richer + display of test results, and easier development of annotation-based + filters. + +- Bug fix (1715326): assertEquals now compares all Numbers using their + native implementation of `equals`. This assertion, which passed in + 4.3, will now fail: + +```java +assertEquals(new Integer(1), new Long(1)); +``` + + Non-integer Numbers (Floats, Doubles, BigDecimals, etc), + which were compared incorrectly in 4.3, are now fixed. + +- `assertEquals(long, long)` and `assertEquals(double, double)` have + been re-introduced to the `Assert` class, to take advantage of + Java's native widening conversions. Therefore, this still passes: + +```java +assertEquals(1, 1L); +``` + +- The default runner for JUnit 4 test classes has been refactored. + The old version was named `TestClassRunner`, and the new is named + `JUnit4ClassRunner`. Likewise, `OldTestClassRunner` is now + `JUnit3ClassRunner`. The new design allows variations in running + individual test classes to be expressed with fewer custom classes. + For a good example, see the source to + `org.junit.experimental.theories.Theories`. + +- The rules for determining which runner is applied by default to a + test class have been simplified: + + 1. If the class has a `@RunWith` annotation, the annotated runner + class is used. + + 2. If the class can be run with the JUnit 3 test runner (it + subclasses `TestCase`, or contains a `public static Test suite()` + method), JUnit38ClassRunner is used. + + 3. Otherwise, JUnit4ClassRunner is used. + + This default guess can always be overridden by an explicit + `@RunWith(JUnit4ClassRunner.class)` or + `@RunWith(JUnit38ClassRunner.class)` annotation. + + The old class names `TestClassRunner` and `OldTestClassRunner` + remain as deprecated. + +- Bug fix (1739095): Filters and Sorters work correctly on test + classes that contain a `suite` method like: + +```java +public static junit.framework.Test suite() { + return new JUnit4TestAdapter(MyTest.class); +} +``` + +- Bug fix (1745048): @After methods are now correctly called + after a test method times out. + diff --git a/doc/ReleaseNotes4.4.txt b/doc/ReleaseNotes4.4.txt new file mode 100644 index 000000000000..63a0a8110501 --- /dev/null +++ b/doc/ReleaseNotes4.4.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.4.md diff --git a/doc/ReleaseNotes4.5.html b/doc/ReleaseNotes4.5.html new file mode 100644 index 000000000000..d6549aa5badc --- /dev/null +++ b/doc/ReleaseNotes4.5.html @@ -0,0 +1,320 @@ +

Summary of Changes in version 4.5

+ +

Installation

+ +
    +
  • We are releasing junit-4.5.jar, which contains all the classes +necessary to run JUnit, and junit-dep-4.5.jar, which leaves out +hamcrest classes, for developers who already use hamcrest outside of +JUnit.
  • +
+ +

Basic JUnit operation

+ +
    +
  • JUnitCore now more often exits with the correct exit code (0 for +success, 1 for failure)

  • +
  • Badly formed test classes (exceptions in constructors, classes +without tests, multiple constructors, Suite without @SuiteClasses) +produce more helpful error messages

  • +
  • Test classes whose only test methods are inherited from superclasses +now run.

  • +
  • Optimization to annotation processing can cut JUnit overhead by more than half +on large test classes, especially when using Theories. [Bug 1796847]

  • +
  • A failing assumption in a constructor ignores the class

  • +
  • Correct results when comparing the string "null" with potentially +null values. [Bug 1857283]

  • +
  • Annotating a class with @RunWith(JUnit4.class) will always invoke the +default JUnit 4 runner in the current version of JUnit. This default changed +from JUnit4ClassRunner in 4.4 to BlockJUnit4ClassRunner in 4.5 (see below), +and may change again.

  • +
+ +

Extension

+ +
    +
  • BlockJUnit4Runner is a new implementation of the standard JUnit 4 +test class functionality. In contrast to JUnit4ClassRunner (the old +implementation):

    + +
      +
    • BlockJUnit4Runner has a much simpler implementation based on +Statements, allowing new operations to be inserted into the +appropriate point in the execution flow.

    • +
    • BlockJUnit4Runner is published, and extension and reuse are +encouraged, whereas JUnit4ClassRunner was in an internal package, +and is now deprecated.

    • +
  • +
  • ParentRunner is a base class for runners that iterate over +a list of "children", each an object representing a test or suite to run. +ParentRunner provides filtering, sorting, @BeforeClass, @AfterClass, +and method validation to subclasses.

  • +
  • TestClass wraps a class to be run, providing efficient, repeated access +to all methods with a given annotation.

  • +
  • The new RunnerBuilder API allows extending the behavior of +Suite-like custom runners.

  • +
  • AssumptionViolatedException.toString() is more informative

  • +
+ +

Extra Runners

+ +
    +
  • Parameterized.eachOne() has been removed

  • +
  • New runner Enclosed runs all static inner classes of an outer class.

  • +
+ +

Theories

+ +
    +
  • @Before and @After methods are run before and after each set of attempted parameters +on a Theory, and each set of parameters is run on a new instance of the test class.

  • +
  • Exposed API's ParameterSignature.getType() and ParameterSignature.getAnnotations()

  • +
  • An array of data points can be introduced by a field or method +marked with the new annotation @DataPoints

  • +
  • The Theories custom runner has been refactored to make it faster and +easier to extend

  • +
+ +

Development

+ +
    +
  • Source has been split into directories src/main/java and +src/test/java, making it easier to exclude tests from builds, and +making JUnit more maven-friendly

  • +
  • Test classes in org.junit.tests have been organized into +subpackages, hopefully making finding tests easier.

  • +
  • ResultMatchers has more informative descriptions.

  • +
  • TestSystem allows testing return codes and other system-level interactions.

  • +
+ +

Summary of Changes in version 4.4

+ +

JUnit is designed to efficiently capture developers' intentions about +their code, and quickly check their code matches those intentions. +Over the last year, we've been talking about what things developers +would like to say about their code that have been difficult in the +past, and how we can make them easier.

+ +

assertThat

+ +

Two years ago, Joe Walnes built a new assertion mechanism on top of what was +then JMock 1. The method name was assertThat, and the syntax looked like this:

+ +
assertThat(x, is(3));
+assertThat(x, is(not(4)));
+assertThat(responseString, either(containsString("color")).or(containsString("colour")));
+assertThat(myList, hasItem("3"));
+
+ +

More generally:

+ +
assertThat([value], [matcher statement]);
+
+ +

Advantages of this assertion syntax include:

+ +
    +
  • More readable and typeable: this syntax allows you to think in terms of subject, verb, object +(assert "x is 3") rathern than assertEquals, which uses verb, object, subject (assert "equals 3 x")

  • +
  • Combinations: any matcher statement s can be negated (not(s)), combined (either(s).or(t)), +mapped to a collection (each(s)), or used in custom combinations (afterFiveSeconds(s))

  • +
  • Readable failure messages. Compare

    + +
    assertTrue(responseString.contains("color") || responseString.contains("colour"));
    +// ==> failure message: 
    +// java.lang.AssertionError:
    +
    +
    +assertThat(responseString, anyOf(containsString("color"), containsString("colour")));
    +// ==> failure message:
    +// java.lang.AssertionError: 
    +// Expected: (a string containing "color" or a string containing "colour")
    +//      got: "Please choose a font"
    +
  • +
  • Custom Matchers. By implementing the Matcher interface yourself, you can get all of the +above benefits for your own custom assertions.

  • +
  • For a more thorough description of these points, see Joe Walnes's +original post.:

  • +
+ +

We have decided to include this API directly in JUnit. +It's an extensible and readable syntax, and because it enables +new features, like assumptions and theories.

+ +

Some notes:

+ +
    +
  • The old assert methods are never, ever, going away.
    +Developers may continue using the old assertEquals, assertTrue, and +so on.
  • +
  • The second parameter of an assertThat statement is a Matcher. +We include the Matchers we want as static imports, like this:

    + +
    import static org.hamcrest.CoreMatchers.is;
    +
    + +

    or:

    + +
    import static org.hamcrest.CoreMatchers.*;
    +
  • +
  • Manually importing Matcher methods can be frustrating. [Eclipse +3.3][] includes the ability to +define +"Favorite" classes to import static methods from, which makes it easier +(Search for "Favorites" in the Preferences dialog). +We expect that support for static imports will improve in all Java IDEs in the future.

  • +
  • To allow compatibility with a wide variety of possible matchers, +we have decided to include the classes from hamcrest-core, +from the Hamcrest project. This is the first time that +third-party classes have been included in JUnit.

  • +
  • To allow developers to maintain full control of the classpath contents, the JUnit distribution also provides an unbundled junit-dep jar, +ie without hamcrest-core classes included. This is intended for situations when using other libraries that also depend on hamcrest-core, to +avoid classloading conflicts or issues. Developers using junit-dep should ensure a compatible version of hamcrest-core jar (ie 1.1+) is present in the classpath.

  • +
  • JUnit currently ships with a few matchers, defined in +org.hamcrest.CoreMatchers and org.junit.matchers.JUnitMatchers.
    +To use many, many more, consider downloading the full hamcrest package.

  • +
  • JUnit contains special support for comparing string and array +values, giving specific information on how they differ. This is not +yet available using the assertThat syntax, but we hope to bring +the two assert methods into closer alignment in future releases.

  • +
+ +

assumeThat

+ +

+Ideally, the developer writing a test has control of all of the forces that might cause a test to fail. +If this isn't immediately possible, making dependencies explicit can often improve a design.
+For example, if a test fails when run in a different locale than the developer intended, +it can be fixed by explicitly passing a locale to the domain code.

+ +

However, sometimes this is not desirable or possible.
+It's good to be able to run a test against the code as it is currently written, +implicit assumptions and all, or to write a test that exposes a known bug. +For these situations, JUnit now includes the ability to express "assumptions":

+ +
import static org.junit.Assume.*
+
+@Test public void filenameIncludesUsername() {
+   assumeThat(File.separatorChar, is('/'));
+   assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg"));
+}
+
+@Test public void correctBehaviorWhenFilenameIsNull() {
+   assumeTrue(bugFixed("13356"));  // bugFixed is not included in JUnit
+   assertThat(parse(null), is(new NullDocument()));
+}
+
+ +

With this beta release, a failed assumption will lead to the test being marked as passing, +regardless of what the code below the assumption may assert. +In the future, this may change, and a failed assumption may lead to the test being ignored: +however, third-party runners do not currently allow this option.

+ +

We have included assumeTrue for convenience, but thanks to the +inclusion of Hamcrest, we do not need to create assumeEquals, +assumeSame, and other analogues to the assert* methods. All of +those functionalities are subsumed in assumeThat, with the appropriate +matcher.

+ +

A failing assumption in a @Before or @BeforeClass method will have the same effect +as a failing assumption in each @Test method of the class.

+ +

Theories

+ +

+More flexible and expressive assertions, combined with the ability to +state assumptions clearly, lead to a new kind of statement of intent, +which we call a "Theory". A test captures the intended behavior in +one particular scenario. A theory allows a developer to be +as precise as desired about the behavior of the code in possibly +infinite numbers of possible scenarios. For example:

+ +
@RunWith(Theories.class)
+public class UserTest {
+  @DataPoint public static String GOOD_USERNAME = "optimus";
+  @DataPoint public static String USERNAME_WITH_SLASH = "optimus/prime";
+
+  @Theory public void filenameIncludesUsername(String username) {
+    assumeThat(username, not(containsString("/")));
+    assertThat(new User(username).configFileName(), containsString(username));
+  }
+}
+
+ +

This makes it clear that the user's filename should be included in the +config file name, only if it doesn't contain a slash. Another test +or theory might define what happens when a username does contain a slash.

+ +

UserTest will attempt to run filenameIncludesUsername on +every compatible DataPoint defined in the class. If any of the +assumptions fail, the data point is silently ignored. If all of the +assumptions pass, but an assertion fails, the test fails.

+ +

The support for Theories has been absorbed from the Popper +project, and more complete documentation can be found +there.

+ +

Defining general statements in this way can jog the developer's memory +about other potential data points and tests, also allows automated +tools to search for new, unexpected data +points that expose bugs.

+ +

Other changes

+ +

This release contains other bug fixes and new features. Among them:

+ +
    +
  • Annotated descriptions

    + +

    Runner UIs, Filters, and Sorters operate on Descriptions of test +methods and test classes. These Descriptions now include the +annotations on the original Java source element, allowing for richer +display of test results, and easier development of annotation-based +filters.

  • +
  • Bug fix (1715326): assertEquals now compares all Numbers using their +native implementation of equals. This assertion, which passed in +4.3, will now fail:

    + +

    assertEquals(new Integer(1), new Long(1));

    + +

    Non-integer Numbers (Floats, Doubles, BigDecimals, etc), +which were compared incorrectly in 4.3, are now fixed.

  • +
  • assertEquals(long, long) and assertEquals(double, double) have +been re-introduced to the Assert class, to take advantage of +Java's native widening conversions. Therefore, this still passes:

    + +

    assertEquals(1, 1L);

  • +
  • The default runner for JUnit 4 test classes has been refactored. +The old version was named TestClassRunner, and the new is named +JUnit4ClassRunner. Likewise, OldTestClassRunner is now +JUnit3ClassRunner. The new design allows variations in running +individual test classes to be expressed with fewer custom classes. +For a good example, see the source to +org.junit.experimental.theories.Theories.

  • +
  • The rules for determining which runner is applied by default to a +test class have been simplified:

    + +
      +
    1. If the class has a @RunWith annotation, the annotated runner +class is used.

    2. +
    3. If the class can be run with the JUnit 3 test runner (it +subclasses TestCase, or contains a public static Test suite() +method), JUnit38ClassRunner is used.

    4. +
    5. Otherwise, JUnit4ClassRunner is used.

    6. +
    + +

    This default guess can always be overridden by an explicit +@RunWith(JUnit4ClassRunner.class) or +@RunWith(JUnit38ClassRunner.class) annotation.

    + +

    The old class names TestClassRunner and OldTestClassRunner +remain as deprecated.

  • +
  • Bug fix (1739095): Filters and Sorters work correctly on test +classes that contain a suite method like:

    + +

    public static junit.framework.Test suite() { + return new JUnit4TestAdapter(MyTest.class); +}

  • +
  • Bug fix (1745048): @After methods are now correctly called +after a test method times out.

  • +
diff --git a/doc/ReleaseNotes4.5.md b/doc/ReleaseNotes4.5.md new file mode 100644 index 000000000000..66aac7004a25 --- /dev/null +++ b/doc/ReleaseNotes4.5.md @@ -0,0 +1,96 @@ +## Summary of Changes in version 4.5 ## + +### Installation ### + +- We are releasing `junit-4.5.jar`, which contains all the classes + necessary to run JUnit, and `junit-dep-4.5.jar`, which leaves out + hamcrest classes, for developers who already use hamcrest outside of + JUnit. + +### Basic JUnit operation ### + +- JUnitCore now more often exits with the correct exit code (0 for + success, 1 for failure) + +- Badly formed test classes (exceptions in constructors, classes + without tests, multiple constructors, Suite without @SuiteClasses) + produce more helpful error messages + +- Test classes whose only test methods are inherited from superclasses + now run. + +- Optimization to annotation processing can cut JUnit overhead by more than half + on large test classes, especially when using Theories. [Bug 1796847] + +- A failing assumption in a constructor ignores the class + +- Correct results when comparing the string "null" with potentially + null values. [Bug 1857283] + +- Annotating a class with `@RunWith(JUnit4.class)` will always invoke the + default JUnit 4 runner in the current version of JUnit. This default changed + from `JUnit4ClassRunner` in 4.4 to `BlockJUnit4ClassRunner` in 4.5 (see below), + and may change again. + +### Extension ### + +- `BlockJUnit4Runner` is a new implementation of the standard JUnit 4 + test class functionality. In contrast to `JUnit4ClassRunner` (the old + implementation): + + - `BlockJUnit4Runner` has a much simpler implementation based on + Statements, allowing new operations to be inserted into the + appropriate point in the execution flow. + + - `BlockJUnit4Runner` is published, and extension and reuse are + encouraged, whereas `JUnit4ClassRunner` was in an internal package, + and is now deprecated. + +- `ParentRunner` is a base class for runners that iterate over + a list of "children", each an object representing a test or suite to run. + `ParentRunner` provides filtering, sorting, `@BeforeClass`, `@AfterClass`, + and method validation to subclasses. + +- `TestClass` wraps a class to be run, providing efficient, repeated access + to all methods with a given annotation. + +- The new `RunnerBuilder` API allows extending the behavior of + Suite-like custom runners. + +- `AssumptionViolatedException.toString()` is more informative + +### Extra Runners ### + +- `Parameterized.eachOne()` has been removed + +- New runner `Enclosed` runs all static inner classes of an outer class. + +### Theories ### + +- `@Before` and `@After` methods are run before and after each set of attempted parameters + on a Theory, and each set of parameters is run on a new instance of the test class. + +- Exposed API's `ParameterSignature.getType()` and `ParameterSignature.getAnnotations()` + +- An array of data points can be introduced by a field or method + marked with the new annotation `@DataPoints` + +- The Theories custom runner has been refactored to make it faster and + easier to extend + +### Development ### + +- Source has been split into directories `src/main/java` and + `src/test/java`, making it easier to exclude tests from builds, and + making JUnit more maven-friendly + +- Test classes in `org.junit.tests` have been organized into + subpackages, hopefully making finding tests easier. + +- `ResultMatchers` has more informative descriptions. + +- `TestSystem` allows testing return codes and other system-level interactions. + +### Incompatible changes ### + +- Removed Request.classes(String, Class...) factory method diff --git a/doc/ReleaseNotes4.5.txt b/doc/ReleaseNotes4.5.txt new file mode 100644 index 000000000000..704e8023abe5 --- /dev/null +++ b/doc/ReleaseNotes4.5.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.5.md diff --git a/doc/ReleaseNotes4.6.html b/doc/ReleaseNotes4.6.html new file mode 100644 index 000000000000..36c432a86070 --- /dev/null +++ b/doc/ReleaseNotes4.6.html @@ -0,0 +1,106 @@ +

Summary of Changes in version 4.6

+ +

Max

+ +

JUnit now includes a new experimental Core, MaxCore. MaxCore +remembers the results of previous test runs in order to run new +tests out of order. MaxCore prefers new tests to old tests, fast +tests to slow tests, and recently failing tests to tests that last +failed long ago. There's currently not a standard UI for running +MaxCore included in JUnit, but there is a UI included in the JUnit +Max Eclipse plug-in at:

+ +

http://www.junitmax.com/junitmax/subscribe.html

+ +

Example:

+ +
public static class TwoUnEqualTests {
+    @Test
+    public void slow() throws InterruptedException {
+        Thread.sleep(100);
+        fail();
+    }
+
+    @Test
+    public void fast() {
+        fail();
+    }
+}
+
+@Test
+public void rememberOldRuns() {
+    File maxFile = new File("history.max");
+    MaxCore firstMax = MaxCore.storedLocally(maxFile);
+    firstMax.run(TwoUnEqualTests.class);
+
+    MaxCore useHistory= MaxCore.storedLocally(maxFile);
+    List<Failure> failures= useHistory.run(TwoUnEqualTests.class)
+            .getFailures();
+    assertEquals("fast", failures.get(0).getDescription().getMethodName());
+    assertEquals("slow", failures.get(1).getDescription().getMethodName());
+}
+
+ +

Test scheduling strategies

+ +

JUnitCore now includes an experimental method that allows you to +specify a model of the Computer that runs your tests. Currently, +the only built-in Computers are the default, serial runner, and two +runners provided in the ParallelRunner class: +ParallelRunner.classes(), which runs classes in parallel, and +ParallelRunner.methods(), which runs classes and methods in parallel.

+ +

This feature is currently less stable than MaxCore, and may be +merged with MaxCore in some way in the future.

+ +

Example:

+ +
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, 1500));
+}
+
+ +

Comparing double arrays

+ +

Arrays of doubles can be compared, using a delta allowance for equality:

+ +
@Test
+public void doubleArraysAreEqual() {
+    assertArrayEquals(new double[] {1.0, 2.0}, new double[] {1.0, 2.0}, 0.01);
+}
+
+ +

Filter.matchDescription API

+ +

Since 4.0, it has been possible to run a single method using the Request.method +API. In 4.6, the filter that implements this is exposed as Filter.matchDescription.

+ +

Documentation

+ +
    +
  • A couple classes and packages that once had empty javadoc have been +doc'ed.

  • +
  • Added how to run JUnit from the command line to the cookbook.

  • +
  • junit-4.x.zip now contains build.xml

  • +
+ +

Bug fixes

+ +
    +
  • Fixed overly permissive @DataPoint processing (2191102)
  • +
  • Fixed bug in test counting after an ignored method (2106324)
  • +
diff --git a/doc/ReleaseNotes4.6.md b/doc/ReleaseNotes4.6.md new file mode 100644 index 000000000000..f1f6a8e6ac6b --- /dev/null +++ b/doc/ReleaseNotes4.6.md @@ -0,0 +1,106 @@ +## Summary of Changes in version 4.6 ## + +### Max ### + +JUnit now includes a new experimental Core, `MaxCore`. `MaxCore` +remembers the results of previous test runs in order to run new +tests out of order. `MaxCore` prefers new tests to old tests, fast +tests to slow tests, and recently failing tests to tests that last +failed long ago. There's currently not a standard UI for running +`MaxCore` included in JUnit, but there is a UI included in the JUnit +Max Eclipse plug-in at: + + http://www.junitmax.com/junitmax/subscribe.html + +Example: + +```java +public static class TwoUnEqualTests { + @Test + public void slow() throws InterruptedException { + Thread.sleep(100); + fail(); + } + + @Test + public void fast() { + fail(); + } +} + +@Test +public void rememberOldRuns() { + File maxFile = new File("history.max"); + MaxCore firstMax = MaxCore.storedLocally(maxFile); + firstMax.run(TwoUnEqualTests.class); + + MaxCore useHistory= MaxCore.storedLocally(maxFile); + List failures= useHistory.run(TwoUnEqualTests.class) + .getFailures(); + assertEquals("fast", failures.get(0).getDescription().getMethodName()); + assertEquals("slow", failures.get(1).getDescription().getMethodName()); +} +``` + +### Test scheduling strategies ### + +`JUnitCore` now includes an experimental method that allows you to +specify a model of the `Computer` that runs your tests. Currently, +the only built-in Computers are the default, serial runner, and two +runners provided in the `ParallelRunner` class: +`ParallelRunner.classes()`, which runs classes in parallel, and +`ParallelRunner.methods()`, which runs classes and methods in parallel. + +This feature is currently less stable than MaxCore, and may be +merged with MaxCore in some way in the future. + +Example: + +```java +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, 1500)); +} +``` + +### Comparing double arrays ### + +Arrays of doubles can be compared, using a delta allowance for equality: + +```java +@Test +public void doubleArraysAreEqual() { + assertArrayEquals(new double[] {1.0, 2.0}, new double[] {1.0, 2.0}, 0.01); +} +``` + +### `Filter.matchDescription` API ### + +Since 4.0, it has been possible to run a single method using the `Request.method` +API. In 4.6, the filter that implements this is exposed as `Filter.matchDescription`. + +### Documentation ### + +- A couple classes and packages that once had empty javadoc have been + doc'ed. + +- Added how to run JUnit from the command line to the cookbook. + +- junit-4.x.zip now contains build.xml + +### Bug fixes ### +- Fixed overly permissive @DataPoint processing (2191102) +- Fixed bug in test counting after an ignored method (2106324) diff --git a/doc/ReleaseNotes4.6.txt b/doc/ReleaseNotes4.6.txt new file mode 100644 index 000000000000..ab4977e116fe --- /dev/null +++ b/doc/ReleaseNotes4.6.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.6.md diff --git a/doc/ReleaseNotes4.7.html b/doc/ReleaseNotes4.7.html new file mode 100644 index 000000000000..69b66c6a3768 --- /dev/null +++ b/doc/ReleaseNotes4.7.html @@ -0,0 +1,229 @@ +

Summary of Changes in version 4.7

+ +

Rules

+ +
    +
  • Rules allow very flexible addition or redefinition of the behavior +of each test method in a test class. Testers can reuse or extend one of the +provided Rules below, or write their own.

    + +

    For more on this feature, see http://www.threeriversinstitute.org/blog/?p=155

  • +
  • The TemporaryFolder Rule allows creation of files and folders +that are guaranteed to be deleted when the test method finishes +(whether it passes or fails):

    + +

    public static class HasTempFolder { + @Rule + public TemporaryFolder folder= new TemporaryFolder();

    + +
    @Test
    +public void testUsingTempFolder() throws IOException {
    +    File createdFile= folder.newFile("myfile.txt");
    +    File createdFolder= folder.newFolder("subfolder");
    +    // ...
    +}
    +
    + +

    }

  • +
  • ExternalResource is a base class for Rules (like TemporaryFolder) +that set up an external resource before a test (a file, socket, server, +database connection, etc.), and guarantee to tear it down afterward:

    + +

    public static class UsesExternalResource { + Server myServer = new Server();

    + +
    @Rule public ExternalResource resource = new ExternalResource() {
    +    @Override
    +    protected void before() throws Throwable {
    +        myServer.connect();
    +    };
    +
    +
    +
    @Override
    +protected void after() {
    +    myServer.disconnect();
    +};
    +
    + +}; + + +@Test public void testFoo() { + new Client().run(myServer); +} +
    + +

    }

  • +
  • The ErrorCollector Rule allows execution of a test to continue +after the first problem is found (for example, to collect all the +incorrect rows in a table, and report them all at once):

    + +

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

    }

  • +
  • Verifier is a base class for Rules like ErrorCollector, which +can turn otherwise passing test methods into failing tests if a verification +check is failed

    + +

    public static class ErrorLogVerifier() { + private ErrorLog errorLog = new ErrorLog();

    + +

    @Rule + public MethodRule verifier = new Verifier() { + @Override public void verify() { + assertTrue(errorLog.isEmpty()); + } + }

    + +

    @Test public void testThatMightWriteErrorLog() { + // ... + } +}

  • +
  • TestWatchman is a base class for Rules that take note +of the testing action, without modifying it. +For example, this class will keep a log of each passing and failing +test:

    + +

    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() { +} +
    + +

    }

  • +
  • The TestName Rule makes the current test name available inside test methods:

    + +

    public class NameRuleTest { + @Rule public TestName name = new TestName();

    + +
    @Test public void testA() {
    +    assertEquals("testA", name.getMethodName());
    +}
    +
    +
    +@Test public void testB() {
    +    assertEquals("testB", name.getMethodName());
    +}
    +
    + +

    }

  • +
  • The Timeout Rule applies the same timeout to all test methods in a class:

    + +

    public static class HasGlobalTimeout { + public static String log;

    + +
    @Rule public MethodRule globalTimeout = new Timeout(20);
    +
    +
    +@Test public void testInfiniteLoop1() {
    +    log+= "ran1";
    +    for(;;) {}
    +}
    +
    +
    +@Test public void testInfiniteLoop2() {
    +    log+= "ran2";
    +    for(;;) {}
    +}
    +
    + +

    }

  • +
  • The ExpectedException Rule allows in-test specification +of expected exception types and messages:

    + +

    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?");
    +    thrown.expectMessage(startsWith("What"));
    +    throw new NullPointerException("What happened?");
    +}
    +
    + +

    }

  • +
+ +

Timeouts

+ +
    +
  • Tests that time out now show the stack trace of the test thread.
  • +
+ +

Matchers

+ +
    +
  • Due to typing incompatibilities, JUnit is still including the 1.1 release +of hamcrest. This is not a change from 4.6, but is a change from +pre-beta releases of 4.7. Due to this incompatibility, tests using +Hamcrest 1.2 must still use the MatcherAssert.assertThat method from +Hamcrest, not Assert.assertThat from JUnit.
  • +
+ +

Docs

+ +
    +
  • Javadocs now link to online JDK javadocs (bug 2090230)
  • +
  • Parameterized runner javadocs improved (bug 2186792)
  • +
  • Fixed Javadoc code sample for AfterClass (2126279)
  • +
  • Fixed Javadoc for assertArraysEqual(float[], float[])
  • +
+ +

Bug fixes

+ +
    +
  • Fixed: BaseTestRunner.getTest() requires class to extend TestCase (1812200)
  • +
  • Fixed: Suite does not allow for inheritance in annotations (2783118)
  • +
  • Fixed: ParallelComputer skipped tests that took longer than 2 seconds
  • +
diff --git a/doc/ReleaseNotes4.7.md b/doc/ReleaseNotes4.7.md new file mode 100644 index 000000000000..d33a501e2e5e --- /dev/null +++ b/doc/ReleaseNotes4.7.md @@ -0,0 +1,210 @@ +## Summary of Changes in version 4.7 ## + +### Rules ### + +- Rules allow very flexible addition or redefinition of the behavior + of each test method in a test class. Testers can reuse or extend one of the + provided Rules below, or write their own. + + For more on this feature, see http://www.threeriversinstitute.org/blog/?p=155 + +- The TemporaryFolder Rule allows creation of files and folders + that are guaranteed to be deleted when the test method finishes + (whether it passes or fails): + +```java +public static class HasTempFolder { + @Rule + public TemporaryFolder folder= new TemporaryFolder(); + + @Test + public void testUsingTempFolder() throws IOException { + File createdFile= folder.newFile("myfile.txt"); + File createdFolder= folder.newFolder("subfolder"); + // ... + } +} +``` + +- ExternalResource is a base class for Rules (like TemporaryFolder) + that set up an external resource before a test (a file, socket, server, + database connection, etc.), and guarantee to tear it down afterward: + +```java +public static class UsesExternalResource { + Server myServer = new Server(); + + @Rule public ExternalResource resource = new ExternalResource() { + @Override + protected void before() throws Throwable { + myServer.connect(); + }; + + @Override + protected void after() { + myServer.disconnect(); + }; + }; + + @Test public void testFoo() { + new Client().run(myServer); + } +} +``` + +- The ErrorCollector Rule allows execution of a test to continue + after the first problem is found (for example, to collect _all_ the + incorrect rows in a table, and report them all at once): + +```java +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")); + } +} +``` + +- Verifier is a base class for Rules like ErrorCollector, which + can turn otherwise passing test methods into failing tests if a verification + check is failed + +```java +public static class ErrorLogVerifier() { + private ErrorLog errorLog = new ErrorLog(); + + @Rule + public MethodRule verifier = new Verifier() { + @Override public void verify() { + assertTrue(errorLog.isEmpty()); + } + } + + @Test public void testThatMightWriteErrorLog() { + // ... + } +} +``` + +- TestWatchman is a base class for Rules that take note + of the testing action, without modifying it. + For example, this class will keep a log of each passing and failing + test: + +```java +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() { + } +} +``` + +- The TestName Rule makes the current test name available inside test methods: + +```java +public class NameRuleTest { + @Rule public TestName name = new TestName(); + + @Test public void testA() { + assertEquals("testA", name.getMethodName()); + } + + @Test public void testB() { + assertEquals("testB", name.getMethodName()); + } +} +``` + +- The Timeout Rule applies the same timeout to all test methods in a class: + +```java +public static class HasGlobalTimeout { + public static String log; + + @Rule public MethodRule globalTimeout = new Timeout(20); + + @Test public void testInfiniteLoop1() { + log+= "ran1"; + for(;;) {} + } + + @Test public void testInfiniteLoop2() { + log+= "ran2"; + for(;;) {} + } +} +``` + +- The ExpectedException Rule allows in-test specification + of expected exception types and messages: + +```java +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?"); + thrown.expectMessage(startsWith("What")); + throw new NullPointerException("What happened?"); + } +} +``` + +### Timeouts ### +- Tests that time out now show the stack trace of the test thread. + +### Matchers ### +- Due to typing incompatibilities, JUnit is still including the 1.1 release + of hamcrest. This is not a change from 4.6, but is a change from + pre-beta releases of 4.7. Due to this incompatibility, tests using + Hamcrest 1.2 must still use the MatcherAssert.assertThat method from + Hamcrest, not Assert.assertThat from JUnit. + +### Docs ### +- Javadocs now link to online JDK javadocs (bug 2090230) +- Parameterized runner javadocs improved (bug 2186792) +- Fixed Javadoc code sample for AfterClass (2126279) +- Fixed Javadoc for assertArraysEqual(float[], float[]) + +### Bug fixes ### +- Fixed: BaseTestRunner.getTest() requires class to extend TestCase (1812200) +- Fixed: Suite does not allow for inheritance in annotations (2783118) +- Fixed: ParallelComputer skipped tests that took longer than 2 seconds diff --git a/doc/ReleaseNotes4.7.txt b/doc/ReleaseNotes4.7.txt new file mode 100644 index 000000000000..58765736986d --- /dev/null +++ b/doc/ReleaseNotes4.7.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.7.md diff --git a/doc/ReleaseNotes4.8.1.html b/doc/ReleaseNotes4.8.1.html new file mode 100644 index 000000000000..32e36a656d8d --- /dev/null +++ b/doc/ReleaseNotes4.8.1.html @@ -0,0 +1,9 @@ +

Summary of Changes in version 4.8.1

+ +

This was a quick bugfix release for an important bug

+ +

Bug fixes

+ +
    +
  • github#61: Category annotations on classes were not honored.
  • +
diff --git a/doc/ReleaseNotes4.8.1.md b/doc/ReleaseNotes4.8.1.md new file mode 100644 index 000000000000..bc13f26ae14a --- /dev/null +++ b/doc/ReleaseNotes4.8.1.md @@ -0,0 +1,7 @@ +## Summary of Changes in version 4.8.1 ## + +This was a quick bugfix release for an important bug + +### Bug fixes ### + +- github#61: Category annotations on classes were not honored. \ No newline at end of file diff --git a/doc/ReleaseNotes4.8.1.txt b/doc/ReleaseNotes4.8.1.txt new file mode 100644 index 000000000000..ef1cd68a7a25 --- /dev/null +++ b/doc/ReleaseNotes4.8.1.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.8.1.md diff --git a/doc/ReleaseNotes4.8.2.html b/doc/ReleaseNotes4.8.2.html new file mode 100644 index 000000000000..273f03bcf220 --- /dev/null +++ b/doc/ReleaseNotes4.8.2.html @@ -0,0 +1,10 @@ +

Summary of Changes in version 4.8.2

+ +

This was a quick bugfix release

+ +

Bug fixes

+ +
    +
  • github#96: TestSuite(MyTestCase.class) should dynamically detect if MyTestCase +is a TestCase
  • +
diff --git a/doc/ReleaseNotes4.8.2.md b/doc/ReleaseNotes4.8.2.md new file mode 100644 index 000000000000..8631275cacbc --- /dev/null +++ b/doc/ReleaseNotes4.8.2.md @@ -0,0 +1,8 @@ +## Summary of Changes in version 4.8.2 ## + +This was a quick bugfix release + +### Bug fixes ### + +- github#96: TestSuite(MyTestCase.class) should dynamically detect if MyTestCase + is a TestCase diff --git a/doc/ReleaseNotes4.8.2.txt b/doc/ReleaseNotes4.8.2.txt new file mode 100644 index 000000000000..e6a2ec01bcdc --- /dev/null +++ b/doc/ReleaseNotes4.8.2.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.8.2.md diff --git a/doc/ReleaseNotes4.8.html b/doc/ReleaseNotes4.8.html new file mode 100644 index 000000000000..086f5d0f5220 --- /dev/null +++ b/doc/ReleaseNotes4.8.html @@ -0,0 +1,59 @@ +

Summary of Changes in version 4.8

+ +

Categories

+ +

From a given set of test classes, the Categories runner +runs only the classes and methods +that are annotated with either the category given with the @IncludeCategory +annotation, or a subtype of that category. Either classes or interfaces can be +used as categories. Subtyping works, so if you say @IncludeCategory(SuperClass.class), +a test marked @Category({SubClass.class}) will be run.

+ +

You can also exclude categories by using the @ExcludeCategory annotation

+ +

Example:

+ +
public interface FastTests { /* category marker */ }
+public interface SlowTests { /* category marker */ }
+
+public class A {
+    @Test
+    public void a() {
+        fail();
+    }
+
+    @Category(SlowTests.class)
+    @Test
+    public void b() {
+    }
+}
+
+@Category({SlowTests.class, FastTests.class})
+public class B {
+    @Test
+    public void c() {
+
+    }
+}
+
+@RunWith(Categories.class)
+@IncludeCategory(SlowTests.class)
+@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
+public class SlowTestSuite {
+  // Will run A.b and B.c, but not A.a
+}
+
+@RunWith(Categories.class)
+@IncludeCategory(SlowTests.class)
+@ExcludeCategory(FastTests.class)
+@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
+public class SlowTestSuite {
+  // Will run A.b, but not A.a or B.c
+}
+
+ +

Bug fixes

+ +
    +
  • github#16: thread safety of Result counting
  • +
diff --git a/doc/ReleaseNotes4.8.md b/doc/ReleaseNotes4.8.md new file mode 100644 index 000000000000..cc429ea08b74 --- /dev/null +++ b/doc/ReleaseNotes4.8.md @@ -0,0 +1,57 @@ +## Summary of Changes in version 4.8 ## + +### Categories ### + +From a given set of test classes, the `Categories` runner +runs only the classes and methods +that are annotated with either the category given with the `@IncludeCategory` +annotation, or a subtype of that category. Either classes or interfaces can be +used as categories. Subtyping works, so if you say `@IncludeCategory(SuperClass.class)`, +a test marked `@Category({SubClass.class})` will be run. + +You can also exclude categories by using the `@ExcludeCategory` annotation + +Example: + +```java +public interface FastTests { /* category marker */ } +public interface SlowTests { /* category marker */ } + +public class A { + @Test + public void a() { + fail(); + } + + @Category(SlowTests.class) + @Test + public void b() { + } +} + +@Category({SlowTests.class, FastTests.class}) +public class B { + @Test + public void c() { + } +} + +@RunWith(Categories.class) +@IncludeCategory(SlowTests.class) +@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite +public class SlowTestSuite { + // Will run A.b and B.c, but not A.a +} + +@RunWith(Categories.class) +@IncludeCategory(SlowTests.class) +@ExcludeCategory(FastTests.class) +@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite +public class SlowTestSuite { + // Will run A.b, but not A.a or B.c +} +``` + +### Bug fixes ### + +- github#16: thread safety of Result counting diff --git a/doc/ReleaseNotes4.8.txt b/doc/ReleaseNotes4.8.txt new file mode 100644 index 000000000000..6f4904e020f4 --- /dev/null +++ b/doc/ReleaseNotes4.8.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.8.md diff --git a/doc/ReleaseNotes4.9.1.md b/doc/ReleaseNotes4.9.1.md new file mode 100644 index 000000000000..eded783dbb66 --- /dev/null +++ b/doc/ReleaseNotes4.9.1.md @@ -0,0 +1,14 @@ +## Summary of Changes in version 4.9.1 [unreleased!] ## + +### Theories ### + +The `Theories` runner does not anticipate theory parameters that have generic +types, as reported by github#64. Fixing this won't happen until `Theories` is +moved to junit-contrib. In anticipation of this, 4.9.1 adds some of the +necessary machinery to the runner classes, and deprecates a method that only +the `Theories` runner uses, `FrameworkMethod`#producesType(). +The Common Public License that JUnit is released under is now included +in the source repository. + +Thanks to `@pholser` for identifying a potential resolution for github#64 +and initiating work on it. diff --git a/doc/ReleaseNotes4.9.1.txt b/doc/ReleaseNotes4.9.1.txt new file mode 100644 index 000000000000..1a0a67b89fa7 --- /dev/null +++ b/doc/ReleaseNotes4.9.1.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.9.1.md diff --git a/doc/ReleaseNotes4.9.html b/doc/ReleaseNotes4.9.html new file mode 100644 index 000000000000..36921023a654 --- /dev/null +++ b/doc/ReleaseNotes4.9.html @@ -0,0 +1,96 @@ +

Summary of Changes in version 4.9, final

+ +

Release theme: Test-class and suite level Rules.

+ +

ClassRule

+ +

The ClassRule annotation extends the idea of method-level Rules, +adding static fields that can affect the operation of a whole class. Any +subclass of ParentRunner, including the standard BlockJUnit4ClassRunner +and Suite classes, will support ClassRules.

+ +

For example, here is a test suite that connects to a server once before +all the test classes run, and disconnects after they are finished:

+ +
@RunWith(Suite.class)
+@SuiteClasses({A.class, B.class, C.class})
+public class UsesExternalResource {
+    public static Server myServer= new Server();
+
+    @ClassRule
+    public static ExternalResource resource= new ExternalResource() {
+        @Override
+        protected void before() throws Throwable {
+            myServer.connect();
+        };
+
+        @Override
+        protected void after() {
+            myServer.disconnect();
+        };
+    };
+}
+
+ +

TestRule

+ +

In JUnit 4.9, fields that can be annotated with either @Rule or @ClassRule +should be of type TestRule. The old MethodRule type, which only made sense +for method-level rules, will still work, but is deprecated.

+ +

Most built-in Rules have been moved to the new type already, in a way that +should be transparent to most users. TestWatchman has been deprecated, +and replaced by TestWatcher, which has the same functionality, but implements +the new type.

+ +

Maven support

+ +

Maven bundles have, in the past, been uploaded by kind volunteers. Starting +with this release, the JUnit team is attempting to perform this task ourselves.

+ +

LICENSE checked in

+ +

The Common Public License that JUnit is released under is now included +in the source repository.

+ +

Bug fixes

+ +
    +
  • github#98: assumeTrue() does not work with expected exceptions
  • +
  • github#74: Categories + Parameterized

    + +

    In JUnit 4.8.2, the Categories runner would fail to run correctly +if any contained test class had a custom Runner with a structure +significantly different from the built-in Runner. With this fix, +such classes can be assigned one or more categories at the class level, +and will be run correctly. Trying to assign categories to methods within +such a class will flag an error.

  • +
  • github#38: ParentRunner filters more than once

    + +

    Thanks to @reinholdfuereder

  • +
  • github#248: protected BlockJUnit4ClassRunner#rules method removed from 4.8.2

  • +
  • github#187: Accidental dependency on Java 6
  • +
+ +

Thanks to @kcooney for:

+ +
    +
  • github#163: Bad comparison failure message when using assertEquals(String, String)
  • +
  • github#227: ParentRunner now assumes that getChildren() returns a modifiable list
  • +
+ +

Minor changes

+ +
    +
  • Backed out unused folder "experimental-use-of-antunit", replaced by +bash-based script at build_tests.sh
  • +
  • Various Javadoc fixes
  • +
+ +

Thanks to @kcooney for:

+ +
    +
  • Made MultipleFailureException public, to assist extension writers.
  • +
  • github#240: Add "test" target to build.xml, for faster ant-driven testing.
  • +
  • github#247: Give InitializationError a useful message
  • +
diff --git a/doc/ReleaseNotes4.9.md b/doc/ReleaseNotes4.9.md new file mode 100644 index 000000000000..5e62cea11d0a --- /dev/null +++ b/doc/ReleaseNotes4.9.md @@ -0,0 +1,91 @@ +## Summary of Changes in version 4.9, final ## + +Release theme: Test-class and suite level Rules. + +### ClassRule ### + +The `ClassRule` annotation extends the idea of method-level Rules, +adding static fields that can affect the operation of a whole class. Any +subclass of `ParentRunner`, including the standard `BlockJUnit4ClassRunner` +and `Suite` classes, will support `ClassRule`s. + +For example, here is a test suite that connects to a server once before +all the test classes run, and disconnects after they are finished: + +```java +@RunWith(Suite.class) +@SuiteClasses({A.class, B.class, C.class}) +public class UsesExternalResource { + public static Server myServer= new Server(); + + @ClassRule + public static ExternalResource resource= new ExternalResource() { + @Override + protected void before() throws Throwable { + myServer.connect(); + }; + + @Override + protected void after() { + myServer.disconnect(); + }; + }; +} +``` + +### TestRule ### + +In JUnit 4.9, fields that can be annotated with either `@Rule` or `@ClassRule` +should be of type `TestRule`. The old `MethodRule` type, which only made sense +for method-level rules, will still work, but is deprecated. + +Most built-in Rules have been moved to the new type already, in a way that +should be transparent to most users. `TestWatchman` has been deprecated, +and replaced by `TestWatcher`, which has the same functionality, but implements +the new type. + +### Maven support ### + +Maven bundles have, in the past, been uploaded by kind volunteers. Starting +with this release, the JUnit team is attempting to perform this task ourselves. + +### LICENSE checked in ### + +The Common Public License that JUnit is released under is now included +in the source repository. + +### Bug fixes ### + +- github#98: assumeTrue() does not work with expected exceptions +- github#74: Categories + Parameterized + + In JUnit 4.8.2, the Categories runner would fail to run correctly + if any contained test class had a custom Runner with a structure + significantly different from the built-in Runner. With this fix, + such classes can be assigned one or more categories at the class level, + and will be run correctly. Trying to assign categories to methods within + such a class will flag an error. + +- github#38: ParentRunner filters more than once + + Thanks to `@reinholdfuereder` + +- github#248: protected BlockJUnit4ClassRunner#rules method removed from 4.8.2 +- github#187: Accidental dependency on Java 6 + +Thanks to `@kcooney` for: + +- github#163: Bad comparison failure message when using assertEquals(String, String) +- github#227: ParentRunner now assumes that getChildren() returns a modifiable list + +### Minor changes ### + +- Backed out unused folder "experimental-use-of-antunit", replaced by + bash-based script at build_tests.sh +- Various Javadoc fixes + +Thanks to `@kcooney` for: + +- Made MultipleFailureException public, to assist extension writers. +- github#240: Add "test" target to build.xml, for faster ant-driven testing. +- github#247: Give InitializationError a useful message diff --git a/doc/ReleaseNotes4.9.txt b/doc/ReleaseNotes4.9.txt new file mode 100644 index 000000000000..a9d7d6033877 --- /dev/null +++ b/doc/ReleaseNotes4.9.txt @@ -0,0 +1 @@ +Please see ReleaseNotes4.9.md diff --git a/doc/building-junit.txt b/doc/building-junit.txt new file mode 100644 index 000000000000..325a27ed8c2b --- /dev/null +++ b/doc/building-junit.txt @@ -0,0 +1,98 @@ +Steps to build junit: + +- Must be manual + - Write release notes +- Not too tedious: + - Push to github (junit-team) + - Run the mvn clean install + - If not done, update src/main/config/settings.xml in /private/.../settings.xml on CloudBees' webdav share. + - If not done, copy GnuPG keys in to ${gpg.homedir}. See settings.xml. + - Perform Maven deployment of a snapshot or release version in Jenkins + Remember that the version specified in the pom.xml indicates the version + to be deployed, with -SNAPSHOT indicating that this is an unofficial + pre-release version towards the goal of the version without the -SNAPSHOT + + - (to deploy gpg signed snapshot version) + + $ mvn -Pjunit-release clean deploy + + - (to cut a release of the current targetted version) + + $ mvn -B release:prepare release:perform + + This will result in the current pom.xml version having -SNAPSHOT removed + and the release cut from that version. The version will then be incremented + and -SNAPSHOT added back in anticipation of the next release version. + + - (to cut a release of while changing the version from the current target) + + $ mvn -B -DreleaseVersion=5.0 release:prepare release:perform + + This will ignore the current version in the pom.xml, set it to 5.0 and + the release cut from that 5.0 version. Then 5.0 will be incremented (to 5.1) + and -SNAPSHOT added back in anticipation of the next release version. + + - (to deploy specified release version and next target release in non-interactive mode -B) + An example with the next development version and deploying release version: + + $ mvn -B -DreleaseVersion=4.12 -DdevelopmentVersion=4.13-SNAPSHOT release:prepare release:perform + + - If you are not an official release manager, and you want to cut a release of + JUnit for use within your organization, use the following command + + $ mvn -DpushChanges=false -DlocalCheckout '-Darguments=-Dgpg.skip=true -DaltDeploymentRepository=my-company-repo-id::default::my-company-repo-url' -B -DreleaseVersion=4.12-mycompany-1 release:prepare release:perform + + where + - my-company-repo-id is the of your company's entry in your + settings.xml with the credentials to deploy to your company's Maven repository + - my-company-repo-url is the deployment URL of your company's Maven repository + - 4.12-mycompany-1 is the version you are deploying, be sure to namespace + the version so that you don't conflict with others, hence why the text "mycompany" + is included in the example version number. + + - Promote the maven artifacts and close staging repository if released successfully +- Tedious: + - Update SourceForge if major release + - Update javadocs on github site (and "latest" link) + - Update javadocs on junit.org + - Put release notes on github. + - Announce on blog, user list, dev list, announce list, junit.org, twitter +- Profit! + + +=================================================================================== +== Internal template of Maven settings used by JUnit build machine. == +== settings.xml == +=================================================================================== + + + + + junit-snapshot-repo + + + + + junit-releases-repo + + + + + + + junit-release + + + ... + false + true + /private/.../.gnupg + /private/.../.gnupg/pubring.gpg + /private/.../.gnupg/secring.gpg + + + + +=================================================================================== diff --git a/doc/cookstour/Image1.gif b/doc/cookstour/Image1.gif new file mode 100644 index 0000000000000000000000000000000000000000..398d4ccce7e2ba35ada1bb748bcf480ea7dd7c9f GIT binary patch literal 1820 zcmZ?wbhEHbe8&*O@SOn!8o;;#Of>*`4Ise6!qPLP=g*%%Q>IJ-%8!E45E#-SaNxj! z|3DA?XZR1MfHaT=1UevJf%1X_$A1P<4jGRP3l27O2y4Zh*s$<$yMVIS9FL8Qj&@5J zXWcomaq;nf1?Mgq&rK>GENa1AE-N=JJv~83SgB*@q_l%GO^f-CbOt+~pKDlewB_ff z6@gtY{dqoIg^o+Gr0)z{Z0Y?n%1C88YJ;tb08KkKc~-u^arZ^`~X-QOSAIByMKTji@WweZ%_33uJDy{g#Y)8rVQ^sVyq z(!@gxrq=QC7Mi@gydrpY+}T}QUtiyle0rYm?rm>xv-_UE*1OyMd8EL_w?(X{bE_h?#e^bAGdwza?ad~xoeO=Pmqczuy zTDhj}tN9(an(bNE&!1^s?_;-LD`&3yJ};TID|AYt#>Od<>Gr(OCEfkshAP%d#I1N3 zCt0*(VXIsl$DHr4bdMxm^Xg$ZAuKbrKwP)*LU-K}dy zQ?@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`C#a%2i?PV7!)X$uTTlQ?aUH z&SA6kq{LCMA&rphwpk|MyJVv9bEKW=?-8x7I;Wx!&2G!WD(_cpnDbJA4qjLQy@CmP zqIHQe7GaNOZ}G9sc_MJP1;0Y{>6zs(KaM@2Hvi`m`1Eb!Znb8uDrf0U%XpuAa%jat zr;G8#9Egc7)Jm4ke;fll$PWqWSA+8?>*+V(Db;&H)i+1UFbf4>G2CF;a2oXq<9OUX zNd34oM(=dhW-I* z)9>cT0S0EzR$YL<+9*L9ndPTakqHS_q#ki4vBJCZ(+^BcECL-k@%52dao3-SG{gyC zC7bWLx>RbFSWZ{@-ND8VgWVlot0TF4!&yE^w|ry}(hH%pB6Yma3MQS9XKr3^rgw3r)ZHz>q=+*em_ zL2cy7)%jAtH_O&Z5u>lo@VSB^J?hAaaTIX7BuV(CP?L~_Ft~numU!>PMtY}-nI@hQ ze)sg#^LHmECY4o$R28M+*8y3B)<)wwfUlDLGOsDNme!8;xz zAu;jjS9OyqLbfw7(1_$DTi-ijmb#mvZ2dj)%-VYek0$gDOyFuM?c?#|kR0OW^`-Q^ zMHNq*OJTMy>)GucOpWV52HfR>bH?@-XXQ@Zw<5SzS*_EXdu#L5rCQ>R)`PrLfh1Gl zCU{7F)+9h5SE?Qw-c<9k@k3i^^(;0$Vt@J8eA^_^db_b;f5pqDeTquiZfW2D8i;f> I=HW5;A6Q0$zW@LL literal 0 HcmV?d00001 diff --git a/doc/cookstour/Image4.gif b/doc/cookstour/Image4.gif new file mode 100644 index 0000000000000000000000000000000000000000..b0b1f2b2b4f6b89ee85746849586a05cf2eb9fe3 GIT binary patch literal 3694 zcmeH``9BkmAIGCGMp6SMJG~b8?kqGe@!&BOPvY4s%P+F%@%cHhgH#$x%_x z99d&3RH9KS=E$-3txvw`uU!ZvWQ3Dxc<1Vij*ReCS{z8Sfx{37fem|x4*uB62@st@HvQB znHxhWHJQfk?|hiMUE*DMXSr?X#^P~%R$R;qH;NC>eOSEI9L*3IE>PK*i>(2tOH@SM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DyjY`EE0ze>cj@mVofB44;lRr@&wW~ literal 0 HcmV?d00001 diff --git a/doc/cookstour/Image5.gif b/doc/cookstour/Image5.gif new file mode 100644 index 0000000000000000000000000000000000000000..5393c637226eb4885ae69c234ad96e2e12e90ea5 GIT binary patch literal 4858 zcmeH`_ct4i_s45fNDtw`(Ee7vFO}uXFBs-+Rve;lAJJTwS1!lCpy=?cSy1OaBt{U&Z_TwpMmKP&&^e+m5mO`yBGoBHQ^>Lu!b@<;!4e~|ju(!al;&P=_; z%Pgq(y08b%%muI>eqGduyeg{yO0S`KAd&BZ$EV?jlA+YUwa|jV#!_;ogek$A+*me> zz3(*g3fNRWhF1!pd?GhhXwyG(qGi)>uAC^*^I^9^*}H3302wrI46AFHGgve^){e{o z;C1#bP&R|$n)ybzF>iU+qpw!2;HeQC)nkvPmS+c)4doVlQ@9~jpG__8$1;P#(((r2 zL!Bih62#f9|e4P zt*>B-yUX3ttbZ9rgxGu<&di*y?GQQG{7_<0@MuqYplX(eD-f3_{Gn);E|Dr^+|_Y< z@MWsnZoI4W{P@Qjw!+9xIiNDShc}zBRKL>mlHrS`1C@q(8Fns=D1;r#&zr#5bx2%s zoZ_I>c$7osDnc+ghd2Hvf+UO*$p+;mNQCJ*qNN@+J0{-0dE}TR#|~OcW=_yuiB{n! ztv!DT7%p+pqy;*s>D{baPkYM0u%2piro@+`Fs3Jlw6NVS&VJxRc8Rx*sxrxOwAF^@ zx|N5TSq`+gzry<#4`6Wm10m&FFwHHDZ)v(17~npNOs#f`H}93y8G`gR^}miXy- z2x_nTDK4kb8--pCz2pt6(hrp##*`^D&SR@^#RN%%NEsZD#p^*T;A>4Yf4h1uX_IiL z##yrcxfPQ0qkv`NuhT71qzD*i)#Du`)zFG~!dvgRFz;B|)rhLim+ox;N}PCkXNR;N zb;mL#xV%}~|LaFx*R1X0X>YI66yut_=b4ap_;q_$vJD8 zcgD3f2k*~P-W`mqGfDsapv~*`b3*TS?a#@lir;@undnL%PMcYJ1;PK`ow-q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dgxpGLlhke6Wnlkh;m?OG3 zw76S1cVrAyD|+^Z;Z^%yv6ykj?{D4Z-=7x0zXkjtC(x!ZISx(7h;$EREews*Chcwv zxKjK3{qFgPPnnVi)YS%D_=kFnhwOJ>*{Tl$?5AhuCJoeU{Sv2>_{L0+hToNp5`mOX zHA)vrcEpbo6+?MHI;wb{VkSg+HAV?%oe7PhI1^^l7iThm&twbCLe*z;1q#oeJ@erI E0EJvg)&Kwi literal 0 HcmV?d00001 diff --git a/doc/cookstour/cookstour.htm b/doc/cookstour/cookstour.htm new file mode 100644 index 000000000000..597dcd8462ea --- /dev/null +++ b/doc/cookstour/cookstour.htm @@ -0,0 +1,668 @@ + + + + + + + + JUnit: A Cook’s Tour + + + +

+JUnit A Cook's +Tour

+
Note: this article is based on JUnit 3.8.x. +
+

1. Introduction +

In an earlier article (see Test Infected: Programmers +Love Writing Tests, Java Report, July 1998, Volume 3, Number 7), we described +how to use a simple framework to write repeatable tests. In this article, +we will take a peek under the covers and show you how the framework itself +is constructed. +

We carefully studied the JUnit framework and reflected +on how we constructed it. We found lessons at many different levels. In +this article we will try communicate them all at once, a hopeless task, +but at least we will do it in the context of showing you the design and +construction of a piece of software with proven value. +

We open with a discussion of the goals of the framework. +The goals will reappear in many small details during the presentation of +the framework itself. Following this, we present the design and implementation +of the framework. The design will be described in terms of patterns (surprise, +surprise), the implementation as a literate program. We conclude with a +few choice thoughts about framework development. +

2. Goals +

What are the goals of JUnit? +

First, we have to get back to the assumptions of development. +If a program feature lacks an automated test, we assume it doesn’t work. +This seems much safer than the prevailing assumption, that if a developer +assures us a program feature works, then it works now and forever. +

From this perspective, developers aren’t done when they +write and debug the code, they must also write tests that demonstrate that +the program works. However, everybody is too busy, they have too much to +do, they don’t have enough time, to screw around with testing. I have too +much code to write already, how am I supposed write test code, too? Answer +me that, Mr. Hard-case Project Manager. +

So, the number one goal is to write a framework within +which we have some glimmer of hope that developers will actually write +tests. The framework has to use familiar tools, so there is little new +to learn. It has to require no more work than absolutely necessary to write +a new test. It has to eliminate duplicated effort. +

If this was all tests had to do, you would be done just +by writing expressions in a debugger. However, this isn’t sufficient for +testing. Telling me that your program works now doesn’t help me, because +it doesn’t assure me that your program will work one minute from now after +I integrate, and it doesn’t assure me that your program will still work +in five years, when you are long gone. +

So, the second goal of testing is creating tests that +retain their value over time. Someone other than the original author has +to be able to execute the tests and interpret the results. It should be +possible to combine tests from various authors and run them together without +fear of interference. +

Finally, it has to be possible to leverage existing tests +to create new ones. Creating a setup or fixture is expensive and a framework +has to enable reusing fixtures to run different tests. Oh, is that all? +

3. The Design of JUnit +

The design of JUnit will be presented in a style first +used in (see "Patterns Generate Architectures", Kent Beck and Ralph Johnson, +ECOOP 94). The idea is to explain the design of a system by starting with +nothing and applying patterns, one after another, until you have the architecture +of the system. We will present the architectural problem to be solved, +summarize the pattern that solves it, and then show how the pattern was +applied to JUnit. +

3.1 Getting started- TestCase +

First we have to make an object to represent our basic +concept, the TestCase. Developers often have tests cases in mind, but they +realize them in many different ways- +

    +
  • +print statements,
  • + +
  • +debugger expressions,
  • + +
  • +test scripts.
  • +
+If we want to make manipulating tests easy, we have to make +them objects. This takes a test that was only implicit in the developer’s +mind and makes it concrete, supporting our goal of creating tests that +retain their value over time. At the same time, object developers are used +to, well, developing with objects, so the decision to make tests into objects +supports our goal of making test writing more inviting (or at least less +imposing). +

The Command pattern (see Gamma, E., et al. Design Patterns: +Elements of Reusable Object-Oriented Software, Addison-Wesley, Reading, +MA, 1995) fits our needs quite nicely. Quoting from the intent, "Encapsulate +a request as an object, thereby letting you… queue or log requests…" Command +tells us to create an object for an operation and give it a method "execute". +Here is the code for the class definition of TestCase: +

+public abstract class TestCase +implements Test { +
    … +
}
+
+Because we expect this class to be reused through inheritance, +we declare it "public abstract". For now, ignore the fact that it implements +the Test interface. For the purposes of our current design, you can think +of TestCase as a lone class. +

Every TestCase is created with a name, so if a test fails, +you can identify which test failed. +

+public abstract class TestCase +implements Test { +
    private final String +fName; +

    public TestCase(String +name) { +
        +fName= name; +
    } +

    public abstract +void run(); +
        +… +
}

+
+To illustrate the evolution of JUnit, we use diagrams that +show snapshots of the architecture. The notation we use is simple. It annotates +classes with shaded boxes containing the associated pattern. When the role +of the class in the pattern is obvious then only the pattern name is shown. +If the role isn’t clear then the shaded box is augmented by the name of +the participant this class corresponds to. This notation minimizes the +clutter in diagrams and was first shown in (see Gamma, E., Applying Design +Patterns in Java, in Java Gems, SIGS Reference Library, 1997) Figure 1 +shows this notation applied to TestCase. Since we are dealing with a single +class and there can be no ambiguities just the pattern name is shown. +
+

+

Figure 1 TestCase applies Command

+ +

3.2 Blanks to fill in- run() +

The next problem to solve is giving the developer a convenient +"place" to put their fixture code and their test code. The declaration +of TestCase as abstract says that the developer is expected to reuse TestCase +by subclassing. However, if all we could do was provide a superclass with +one variable and no behavior, we wouldn’t be doing much to satisfy our +first goal, making tests easier to write. +

Fortunately, there is a common structure to all tests- +they set up a test fixture, run some code against the fixture, check some +results, and then clean up the fixture. This means that each test will +run with a fresh fixture and the results of one test can’t influence the +result of another. This supports the goal of maximizing the value of the +tests. +

Template Method addresses our problem quite nicely. Quoting +from the intent, "Define the skeleton of an algorithm in an operation, +deferring some steps to subclasses. Template Method lets subclasses redefine +certain steps of an algorithm without changing the algorithm’s structure." +This is exactly right. We want the developer to be able to separately consider +how to write the fixture (set up and tear down) code and how to write the +testing code. The execution of this sequence, however, will remain the +same for all tests, no matter how the fixture code is written or how the +testing code is written. +

Here is the template method: +

+public void run() { +
    setUp(); +
    runTest(); +
    tearDown(); +
}
+
+The default implementations of these methods do nothing: + +protected void runTest() { +
} +

protected void setUp() { +
} +

protected void tearDown() { +
}

+
+Since setUp and tearDown are intended to be overridden but +will be called by the framework we declare them as protected. The second +snapshot of our tour is depicted in Figure 2. +
+

+

Figure 2 TestCase.run() applies Template Method

+ +

3.3 Reporting results- TestResult +

If a TestCase runs in a forest, does anyone care about +the result? Sure- you run tests to make sure they run. After the test has +run, you want a record, a summary of what did and didn’t work. +

If tests had equal chances of succeeding or failing, or +if we only ever ran one test, we could just set a flag in the TestCase +object and go look at the flag when the test completed. However, tests +are (intended to be) highly asymmetric- they usually work. Therefore, we +only want to record the failures and a highly condensed summary of the +successes. +

The Smalltalk Best Practice Patterns (see Beck, K. Smalltalk +Best Practice Patterns, Prentice Hall, 1996) has a pattern that is applicable. +It is called Collecting Parameter. It suggests that when you need +to collect results over several methods, you should add a parameter to +the method and pass an object that will collect the results for you. We +create a new object, TestResult, to collect the results of running tests. +

+public class TestResult extends +Object { +
    protected int fRunTests; +

    public TestResult() +{ +
       +fRunTests= 0; +
    } +
}

+
+This simple version of TestResult only counts the number +of tests run. To use it, we have to add a parameter to the TestCase.run() +method and notify the TestResult that the test is running: + +public void run(TestResult +result) { +
    result.startTest(this); +
    setUp(); +
    runTest(); +
    tearDown(); +
}
+
+And the TestResult has to keep track of the number of tests +run: + +public synchronized void startTest(Test +test) { +
    fRunTests++; +
}
+
+We declare the TestResult method startTest as synchronized +so that a single TestResult can collect the results safely when the tests +are run in different threads. Finally, we want to retain the simple external +interface of TestCase, so we create a no-parameter version of run() that +creates its own TestResult: + +public TestResult run() { +
    TestResult result= +createResult(); +
    run(result); +
    return result; +
} +

protected TestResult createResult() +{ +
    return new TestResult(); +
}

+
+Figure 3 shows our next design snapshot. +
+

+

Figure 3: TestResult applies Collecting Parameter

+ +

If tests always ran correctly, then we wouldn’t have to +write them. Tests are interesting when they fail, especially if we didn’t +expect them to fail. What’s more, tests can fail in ways that we expect, +for example by computing an incorrect result, or they can fail in more +spectacular ways, for example by writing outside the bounds of an array. +No matter how the test fails we want to execute the following tests. +

JUnit distinguishes between failures and errors. +The possibility of a failure is anticipated and checked for with assertions. +Errors are unanticipated problems like an ArrayIndexOutOfBoundsException. +Failures are signaled with an AssertionFailedError error. To distinguish +an unanticipated error from a failure, failures are caught in an extra +catch clause (1). The second clause (2) catches all other exceptions and +ensures that our test run continues.. +

+public void run(TestResult +result) { +
    result.startTest(this); +
    setUp(); +
    try { +
        +runTest(); +
    } +
    catch (AssertionFailedError +e) { //1 +
        +result.addFailure(this, e); +
    } +

    catch (Throwable +e) { // 2 +
        +result.addError(this, e); +
    } +
    finally { +
        +tearDown(); +
    } +
}

+
+An AssertionFailedError is triggered by the assert methods +provided by TestCase. JUnit provides a set of assert methods for different +purposes. Here is the simplest one: + +protected void assertTrue(boolean +condition) { +
    if (!condition) +
        +throw new AssertionFailedError(); +
}
+
+The AssertionFailedError is not meant to be caught by the +client (a testing method inside a TestCase) but inside the Template Method +TestCase.run(). We therefore derive AssertionFailedError from Error. + +public class AssertionFailedError +extends Error { +
    public AssertionFailedError +() {} +
}
+
+The methods to collect the errors in TestResult are shown +below: + +public synchronized void addError(Test +test, Throwable t) { +
    fErrors.addElement(new +TestFailure(test, t)); +
} +

public synchronized void addFailure(Test +test, Throwable t) { +
    fFailures.addElement(new +TestFailure(test, t)); +
}

+
+TestFailure is a little framework internal helper class to +bind together the failed test and the signaled exception for later reporting. + +public class TestFailure extends +Object { +
    protected Test +fFailedTest; +
    protected Throwable +fThrownException; +
}
+
+The canonical form of collecting parameter requires us to +pass the collecting parameter to each method. If we followed this advice, +each of the testing methods would require a parameter for the TestResult. +This results in a "pollution" of these method signatures. As a benevolent +side effect of using exceptions to signal failures we can avoid this signature +pollution. A test case method, or a helper method called from it, can throw +an exception without having to know about the TestResult. As a refresher +here is a sample test method from our MoneyTest suite. It illustrates how +a testing method doesn’t have to know anything about a TestResult: + +public void testMoneyEquals() +{ +
    assertTrue(!f12CHF.equals(null)); +
    assertEquals(f12CHF, +f12CHF); +
    assertEquals(f12CHF, +new Money(12, "CHF")); +
    assertTrue(!f12CHF.equals(f14CHF)); +
}
+
+JUnit comes with different implementations of TestResult. +The default implementation counts the number of failures and errors and +collects the results. TextTestResult collects the results and presents +them in a textual form. Finally, UITestResult is used by the graphical +version of the JUnit Test Runner to update the graphical test status. +

TestResult is an extension point of the framework. Clients +can define their own custom TestResult classes, for example, an HTMLTestResult +reports the results as an HTML document. +

3.4 No stupid subclasses - TestCase again +

We have applied Command to represent a test. Command relies +on a single method like execute() (called run() in TestCase) to invoke +it. This simple interface allows us to invoke different implementations +of a command through the same interface. +

We need an interface to generically run our tests. However, +all test cases are implemented as different methods in the same class. +This avoids the unnecessary proliferation of classes. A given test case +class may implement many different methods, each defining a single test +case. Each test case has a descriptive name like testMoneyEquals or testMoneyAdd. +The test cases don’t conform to a simple command interface. Different instances +of the same Command class need to be invoked with different methods. Therefore +our next problem is make all the test cases look the same from the point +of view of the invoker of the test. +

Reviewing the problems addressed by available design patterns, +the Adapter pattern springs to mind. Adapter has the following intent "Convert +the interface of a class into another interface clients expect". This sounds +like a good match. Adapter tells us different ways to do this. One of them +is a class adapter, which uses subclassing to adapt the interface. For +example, to adapt testMoneyEquals to runTest we implement a subclass of +MoneyTest and override runTest to invoke testMoneyEquals. +

+public class TestMoneyEquals +extends MoneyTest { +
    public TestMoneyEquals() +{ super("testMoneyEquals"); } +
    protected void +runTest () { testMoneyEquals(); } +
}
+
+The use of subclassing requires us to implement a subclass +for each test case. This puts an additional burden on the tester. This +is against the JUnit goal that the framework should make it as simple as +possible to add a test case. In addition, creating a subclass for each +testing method results in class bloat. Many classes with only a single +method are not worth their costs and it will be difficult to come up with +meaningful names. +

Java provides anonymous inner classes which provide an +interesting Java-specific solution to the class naming problem. With anonymous +inner classes we can create an Adapter without having to invent a class +name: +

+TestCase test= new MoneyTest("testMoneyEquals +") { +
    protected void +runTest() { testMoneyEquals(); } +
};
+
+This is much more convenient than full subclassing. It preserves +compile-time type checking at the cost of some burden on the developer. +Smalltalk Best Practice Patterns describes another solution for the problem +of different instances behaving differently under the common heading of +pluggable behavior. The idea is to use a single class which can be +parameterized to perform different logic without requiring subclassing. +

The simplest form of pluggable behavior is the Pluggable +Selector. Pluggable Selector stores a Smalltalk method selector in +an instance variable. This idea is not limited to Smalltalk. It is also +applicable to Java. In Java there is no notion of a method selector. However, +the Java reflection API allows us to invoke a method from a string representing +the method’s name. We can use this feature to implement a pluggable selector +in Java. As an aside, we usually don’t use reflection in ordinary application +code. In our case we are dealing with an infrastructure framework and it +is therefore OK to wear the reflection hat. +

JUnit offers the client the choice of using pluggable +selector or implementing an anonymous adapter class as shown above. To +do so, we provide the pluggable selector as the default implementation +of the runTest method. In this case the name of the test case has to correspond +to the name of a test method. We use reflection to invoke the method as +shown below. First we look up the Method object. Once we have the method +object we can invoke it and pass its arguments. Since our test methods +take no arguments we can pass an empty argument array: +

+protected void runTest() throws +Throwable { +
    Method runMethod= +null; +
    try { +
        +runMethod= getClass().getMethod(fName, new Class[0]); +
    } catch (NoSuchMethodException +e) { +
        +assertTrue("Method \""+fName+"\" not found", false); +
    } +
    try { +
        +runMethod.invoke(this, new Class[0]); +
    } +
    // catch InvocationTargetException +and IllegalAccessException +
}
+
+The JDK 1.1 reflection API only allows us to find public +methods. For this reason you have to declare the test methods as public, +otherwise you will get a NoSuchMethodException. +

Here is the next design snapshot, with Adapter and Pluggable +Selector added. +

+

+

Figure 4: TestCase applies either Adapter with an anonymous +inner class or Pluggable Selector

+ +

3.5 Don’t care about one or many - TestSuite +

To get confidence in the state of a system we need to +run many tests. Up to this point JUnit can run a single test case and report +the result in a TestResult. Our next challenge is to extend it so that +it can run many different tests. This problem can be solved easily when +the invoker of the tests doesn’t have to care about whether it runs one +or many test cases. A popular pattern to pull out in such a situation is +Composite. To quote its intent "Compose objects into tree structures to +represent part-whole hierarchies. Composite lets clients treat individual +objects and compositions of objects uniformly." The point about part-whole +hierarchies is of interest here. We want to support suites of suites of +suites of tests. +

Composite introduces the following participants: +

    +
  • +Component: declares the interface we want to use to interact +with our tests.
  • + +
  • +Composite: implements this interface and maintains a collection +of tests.
  • + +
  • +Leaf: represents a test case in a composition that conforms +to the Component interface.
  • +
+The pattern tells us to introduce an abstract class which +defines the common interface for single and composite objects. The primary +purpose of the class is to define an interface. When applying Composite +in Java we prefer to define an interface and not an abstract class. Using +an interface avoids committing JUnit to a specific base class for tests. +All that is required is that the tests conform to this interface. We therefore +tweak the pattern description and introduce a Test interface: + +public interface Test { +
    public abstract +void run(TestResult result); +
}
+
+TestCase corresponds to a Leaf in Composite and implements +this interface as we have seen above. +

Next, we introduce the Composite participant. We name +the class TestSuite. A TestSuite keeps its child tests in a Vector: +

+public class TestSuite implements +Test +{ +
    private Vector +fTests= new Vector(); +
}
+
+The run() method delegates to its children: + +public void run(TestResult +result) { +
    for (Enumeration +e= fTests.elements(); e.hasMoreElements(); ) { +
        +Test test= (Test)e.nextElement(); +
        +test.run(result); +
    } +
}
+
+ +
+

Figure 5: TestSuite applies Composite

+ +

Finally, clients have to be able to add tests to a suite, +they can do so with the method addTest: +

+public void addTest(Test test) +{ +
    fTests.addElement(test); +
}
+
+Notice how all of the above code only depends on the Test +interface. Since both TestCase and TestSuite conform to the Test interface +we can recursively compose suites of test suites. All developers can create +their own TestSuites. We can run them all by creating a TestSuite composed +of those suites. +

Here is an example of creating a TestSuite: +

+public static Test suite() +{ +
    TestSuite suite= +new TestSuite(); +
    suite.addTest(new +MoneyTest("testMoneyEquals")); +
    suite.addTest(new +MoneyTest("testSimpleAdd")); +
}
+
+This works fine, but it requires us to add all the tests +to a suite manually. Early adopters of JUnit told us this was stupid. Whenever +you write a new test case you have to remember to add it to a static suite() +method, otherwise it will not be run. We added a convenience constructor +to TestSuite which takes the test case class as an argument. Its purpose +is to extract the test methods and create a suite containing them. The +test methods must follow the simple convention that they start with the +prefix "test" and take no arguments. The convenience constructor uses this +convention, constructing the test objects by using reflection to find the +testing methods. Using this constructor the above code is simplified to: + +public static Test suite() +{ +
    return new TestSuite(MoneyTest.class); +
}
+
+The original way is still useful when you want to run a subset +of the test cases only. +

3.6 Summary +

We are at the end of our cook’s tour through JUnit. The +following figure shows the design of JUnit at a glance explained with patterns. +

+

+

Figure 6: JUnit Patterns Summary

+ +

Notice how TestCase, the central abstraction in the framework, +is involved in four patterns. Pictures of mature object designs show this +same "pattern density". The star of the design has a rich set of relationships +with the supporting players. +

Here is another way of looking at all of the patterns +in JUnit. In this storyboard you see an abstract representation of the +effect of each of the patterns in turn. So, the Command pattern creates +the TestCase class, the Template Method pattern creates the run method, +and so on. (The notation of the storyboard is the notation of figure 6 +with all the text deleted). +

+

+

Figure 7: JUnit Pattern Storyboard

+ +

One point to notice about the storyboard is how the complexity +of the picture jumps when we apply Composite. This is pictorial corroboration +for our intuition that Composite is a powerful pattern, but that it "complicates +the picture." It should therefore be used with caution. +

4. Conclusion +

To conclude, let’s make some general observations: +

    +
  • +Patterns
  • + +
    We found discussing the design in terms of patterns to +be invaluable, both as we were developing the framework and as we try to +explain it to others. You are now in a perfect position to judge whether +describing a framework with patterns is effective. If you liked the discussion +above, try the same style of presentation for your own system. +
  • +Pattern density
  • + +
    There is a high pattern "density" around TestCase, which +is the key abstraction of JUnit. Designs with high pattern density are +easier to use but harder to change. We have found that such a high pattern +density around key abstractions is common for mature frameworks. The opposite +should be true of immature frameworks - they should have low pattern density. +Once you discover what problem you are really solving, then you can begin +to "compress" the solution, leading to a denser and denser field of patterns +where they provide leverage. +
  • +Eat your own dog food
  • + +
    As soon as we had the base unit testing functionality +implemented, we applied it ourselves. A TestTest verifies that the framework +reports the correct results for errors, successes, and failures. We found +this invaluable as we continued to evolve the design of the framework. +We found that the most challenging application of JUnit was testing its +own behavior. +
  • +Intersection, not union
  • + +
    There is a temptation in framework development to include +every feature you can. After all, you want to make the framework as valuable +as possible. However, there is a counteracting force- developers have to +decide to use your framework. The fewer features the framework has, the +easier it is to learn, the more likely a developer will use it. JUnit is +written in this style. It implements only those features absolutely essential +to running tests- running suites of tests, isolating the execution of tests +from each other, and running tests automatically. Sure, we couldn’t resist +adding some features but we were careful to put them into their own extensions +package (test.extensions). A notable member of this package is a TestDecorator +allowing execution of additional code before and after a test. +
  • +Framework writers read their code
  • + +
    We spent far more time reading the JUnit code than we +spent writing it, and nearly as much time removing duplicate functionality +as we spent adding new functionality. We experimented aggressively with +the design, adding new classes and moving responsibility around in as many +different ways as we could imagine. We were rewarded (and are still being +rewarded) for our monomania by a continuous flow of insights into JUnit, +testing, object design, framework development, and opportunities for further +articles.
+The latest version of JUnit can be downloaded from http://www.junit.org. +

5. Acknowledgements +

Thanks to John Vlissides, Ralph Johnson, and Nick Edgar +for careful reading and gentle correction. + + diff --git a/doc/homepage.html b/doc/homepage.html new file mode 100644 index 000000000000..69c6248102e4 --- /dev/null +++ b/doc/homepage.html @@ -0,0 +1,115 @@ + + +JUnit + + + + +

JUnit

+

JUnit is a simple framework to write repeatable tests. It is an instance of +the xUnit architecture for unit testing frameworks. +

+ +

+Getting Started

+ +To get started with unit testing and JUnit read the article: +JUnit Cookbook. +
This article describes basic test writing using JUnit 4. +

You find additional samples in the org.junit.samples package: +

    +
  • +SimpleTest.java - some simple test cases
  • + +
  • +VectorTest.java - test cases for java.util.Vector
  • +
+

JUnit 4.x only comes with a textual TestRunner. For graphical feedback, +most major IDE's support +JUnit 4. If necessary, you can run JUnit 4 tests in a JUnit 3 +environment by adding the following method to each test class: +

+public static Test suite() {
+   return new JUnit4TestAdapter(ThisClass.class);
+} 
+
+
+ +

+Documentation

+ +
JUnit Cookbook +
    A cookbook for implementing tests with JUnit. +
Javadoc +
    API documentation generated with javadoc. +
Frequently asked questions +
    Some frequently asked questions about using JUnit. + +
Release notes +
    Latest JUnit release notes +
License +
    The terms of the common public license used for JUnit.
+
+The following documents still describe JUnit 3.8. +
+
The JUnit 3.8 version of this homepage +
Test Infected - Programmers +Love Writing Tests +
    An article demonstrating the development process +with JUnit. + +
JUnit - A cooks tour +
+ +

JUnit Related Projects/Sites

+
    +
  • junit.org - a site for software + developers using JUnit. It provides instructions for how to integrate JUnit + with development tools like JBuilder and VisualAge/Java. As well as articles + about and extensions to JUnit.
  • +
  • XProgramming.com - + various implementations of the xUnit testing framework architecture. 
  • + +
+

Mailing Lists

+There are three junit mailing lists: + + +

Get Involved

+ JUnit celebrates programmers testing their own software. As a result + bugs, patches, and feature requests which include JUnit TestCases have a + better + chance of being addressed than those without. + +
+ JUnit is forged on + Sourceforge please use the tools provided for your submissions. + +
+ JUnit source code is now hosted on GitHub. + +
+ +hosted by SourceForge Logo + + + diff --git a/doc/index.htm b/doc/index.htm new file mode 100644 index 000000000000..dd19ff3383be --- /dev/null +++ b/doc/index.htm @@ -0,0 +1,21 @@ + + + + + + JUnit Documentation + + + +

+JUnit Documentation

+ +

+Kent Beck, Erich Gamma, David Saff

+ +
+We have just begun documenting the new JUnit 4 architecture. The cookbook has already been updated. You can find the javadoc here. +The JUnit home page is here. +
+ + diff --git a/doc/markdown.sh b/doc/markdown.sh new file mode 100644 index 000000000000..e235b638aa37 --- /dev/null +++ b/doc/markdown.sh @@ -0,0 +1 @@ +~/bin/Markdown.pl ReleaseNotes4.8.txt >ReleaseNotes4.8.html \ No newline at end of file diff --git a/doc/testinfected/IMG00001.GIF b/doc/testinfected/IMG00001.GIF new file mode 100644 index 0000000000000000000000000000000000000000..ca491c11954f25ee2c991f04a9f49979cd0e85cc GIT binary patch literal 6426 zcmX9=byO5>7atXcR}lmikdQ^CK~zc!89JmJBo>2^2I(546hyiahFn5Gx&#*K?(UKX zX{?=ZIN$Tfo;}ar`>T6*c4g&d9zQXOJtuJP1o-~}0RRF31i%0Q1_Uq=fI$HC4g>)Z z0zd@70ss~Sun>Sn&I%zAfFJ-u02lyZ5P%^7MgTkj;6VTn0eA#JP%sccAOJxyC?o)4 z00;vh7z}{HfEWyf!5|ov2Lv%7gaHu@7QkRZ3>Ly*5e$U#gBS?HKnMl~FffRLAq42Z=*SPX(i z^FSd%2n!-uEP%y=SS*CaB3KB`38jLt5Q2pPEDT~{2n!=vJb=Z6SUiNqBUm(1R1^YX z5i}#2019grXL;ak|JQIr60VoZMh&G^g=oNH!5C{e!7=&O5f)NN0KzI2h7=mF0#se@Ogz*rJM__dFXm}_;g5c4yqsgJ<0D{K=cnpZgKzIy-M|S~@ z6IBEvcr1X&f_N;1$0B$Lz(e4fObEfl03HVMFocH@JRZQ~K|CJ9;}JZ%P3S;SPY80h zN&t9f2sm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cmV?d00001 diff --git a/doc/testinfected/IMG00003.GIF b/doc/testinfected/IMG00003.GIF new file mode 100644 index 0000000000000000000000000000000000000000..2695af30ee349536f899a3d3afe5eb29e650381a GIT binary patch literal 5992 zcmX9=byO8?6JJ{}UO=Rg3rKfJBa5Ik2vU+45QR&LbiFRGgn%er7hyrVrJIY=AuSC` zNF&{_-*Ud^k3D;4XXY0(d(NYv^h8YDjQC;!un+wIfB*mi00LkD00ROT2*4l!8UsN9 zga8l$umFGs0W1Vyk@G|d1Rw~25C8@M7zAJlfDwQI00a;qKmY*&5VRQxAP|5c7_=n- zVgLvOAQ%jQ!GIVHgux&f6bA$`AcO%C3>Ls(K@1kcU=a+2;)56n!axWH1~4#)fgucx zUMwpdHa-^cxxi&kqEG2#5thEC^yD5Q~5i zstFB4AcTN00Ky;$Lm-TR1OOy}AOQji2#Bgj8z2yfAXrp7S`9#00KsAaEC$44AS?#K zqJE$)K?n;XSS*0Wf>ZU0W1t+VF(K&SOS10fLH>AB_LSTQIr${ zVG-0L;GEI9p{O1JwF6a-3Pbgr(>y1N<^d=S+7T^4^Ux4%-AQ*&T2!aua06+u~ zB0vxUfzTG1`!wwz*rE*LNFGAApnL@ zOVF+e3!Y~BG2uuKA0tgczn1I0O zYA4DFLrrRVmkt8Yr9KLK1n11gB<6pP@-ch~Q58nqRrd=DgHR!&s>n%W#f zC4`%3`}(Ez6V-*2@x8*d_DJ?;IY#Zp>7B9s79EL7B^lj#F{kB;_L9t=Wbhqv_vn-R zN`{J&oW>oc*#ntRzbJoJF3TCp)i1$Kc9i7~7h=B$)2o!P{!C>?;*C4Y^T#V*&vtxP zsVJB%u=+GcOsFWFZh$V`xTjiK^!xk!J6tARm0xFD!Z!SC_2}7g=;B(L*JgJ>HrzB2~u>Ytw{xHyG4wD>o+u9HJ^Tozmfm`mgE%|OW!{}*j||~ zbWa?^xRzQGN+4)9k-yOSq!Y1#q!bF z+=C_3^dhTelDBf({09pP++s>@^wMCwO8Q|&szO91#@;nYnC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>a6Lc-+kpozw0(zxRaPYZvyY3AvJU!u?G_onR;Ogo>+K$u28W#iL&Sb}*oM!3Z``ZFZhtyN!|q@f->?eR z# z18uzGNirH27r3@6ICtrEY+Q19qK0?TACC!7U8m|BuPeD3xWsdYMsD7jnZc + + + + + Test Infected: + + + +

+JUnit Test +Infected: Programmers Love Writing Tests

+
Note: this article describes JUnit 3.8.x. + +
+

Testing is not closely integrated with development. This prevents you +from measuring the progress of development- you can't tell when something +starts working or when something stops working. Using JUnit you +can cheaply and incrementally build a test suite that will help you measure +your progress, spot unintended side effects, and focus your development +efforts. +

+Contents

+ + + +

+The Problem

+Every programmer knows they should write tests for their code. Few do. +The universal response to "Why not?" is "I'm in too much of a hurry." This +quickly becomes a vicious cycle- the more pressure you feel, the fewer +tests you write. The fewer tests you write, the less productive you are +and the less stable your code becomes. The less productive and accurate +you are, the more pressure you feel. +

Programmers burn out from just such cycles. Breaking out requires an +outside influence. We found the outside influence we needed in a simple +testing framework that lets us do a little testing that makes a big difference. +

The best way to convince you of the value of writing your own tests +would be to sit down with you and do a bit of development. Along the way, +we would encounter new bugs, catch them with tests, fix them, have them +come back, fix them again, and so on. You would see the value of the immediate +feedback you get from writing and saving and rerunning your own unit tests. +

Unfortunately, this is an article, not an office overlooking charming +old-town Zürich, with the bustle of medieval commerce outside and +the thump of techno from the record store downstairs, so we'll have to +simulate the process of development. We'll write a simple program and its +tests, and show you the results of running the tests. This way you can +get a feel for the process we use and advocate without having to pay for +our presence. +

+Example

+As you read, pay attention to the interplay of the code and the tests. +The style here is to write a few lines of code, then a test that should +run, or even better, to write a test that won't run, then write the code +that will make it run. +

The program we write will solve the problem of representing arithmetic +with multiple currencies. Arithmetic between single currencies is trivial, +you can just add the two amounts. Simple numbers suffice. You can ignore +the presence of currencies altogether. +

Things get more interesting once multiple currencies are involved. You +cannot just convert one currency into another for doing arithmetic since +there is no single conversion rate- you may need to compare the value of +a portfolio at yesterday's rate and today's rate. +

Let's start simple and define a class Money +to represent a value in a single currency. We represent the amount by a +simple int. To get full accuracy you would probably use double or java.math.BigDecimal +to store arbitrary-precision signed decimal numbers. We represent a currency +as a string holding the ISO three letter abbreviation (USD, CHF, etc.). +In more complex implementations, currency might deserve its own object. +

class Money {
+    private int fAmount;
+    private String fCurrency;
+ +
    public Money(int amount, String currency) {
+        fAmount= amount;
+        fCurrency= currency;
+    }
+
+    public int amount() {
+        return fAmount;
+    }
+
+    public String currency() {
+        return fCurrency;
+    }
+}
+When you add two Moneys of the same currency, the +resulting Money has as its amount the sum of the other two amounts. +
public Money add(Money m) {
+    return new Money(amount()+m.amount(), currency());
+}
+Now, instead of just coding on, we want to get immediate feedback and practice +"code a little, test a little, code a little, test a little". To implement +our tests we use the JUnit framework. To write tests you need to get the +latest +copy JUnit (or write your own equivalent- it's not so much work). +

JUnit defines how to structure your test cases and provides the tools +to run them. You implement a test in a subclass of TestCase. To test our +Money implementation we therefore define MoneyTest +as a subclass of TestCase. In Java, classes are contained in packages and +we have to decide where to put MoneyTest. Our current practice is to put +MoneyTest in the same package as the classes under test. In this way a +test case has access to the package private methods. We add a test method +testSimpleAdd, that will exercise the simple version of Money.add() +above. A JUnit test method is an ordinary method without any parameters. +

public class MoneyTest extends TestCase {
+    //…
+    public void testSimpleAdd() {
+        Money m12CHF= new Money(12, "CHF");  // (1)
+        Money m14CHF= new Money(14, "CHF");        
+        Money expected= new Money(26, "CHF");
+        Money result= m12CHF.add(m14CHF);    // (2)
+        Assert.assertTrue(expected.equals(result));     // (3)
+    }
+}
+The testSimpleAdd() test case consists of: +
    +
  1. +Code which creates the objects we will interact +with during the test. This testing context is commonly referred to as a +test's fixture. All we need for the testSimpleAdd test are some +Money objects.
  2. + +
  3. +Code which exercises the objects in the fixture.
  4. + +
  5. +Code which verifies the result.
  6. +
+Before we can verify the result we have to digress a little since we need +a way to test that two Money objects are equal. The Java idiom to do so +is to override the method equals defined in Object. Before we implement +equals let's a write a test for equals in MoneyTest. +
public void testEquals() {
+    Money m12CHF= new Money(12, "CHF");
+    Money m14CHF= new Money(14, "CHF");
+
+    Assert.assertTrue(!m12CHF.equals(null));
+    Assert.assertEquals(m12CHF, m12CHF);
+    Assert.assertEquals(m12CHF, new Money(12, "CHF")); // (1)
+    Assert.assertTrue(!m12CHF.equals(m14CHF));
+}
+The equals method in Object returns true when both objects are the same. +However, Money is a value object. Two Monies are considered equal +if they have the same currency and value. To test this property we have +added a test (1) to verify that Monies are equal +when they have the same value but are not the same object. +

Next let's write the equals method in Money: +

public boolean equals(Object anObject) {
+    if (anObject instanceof Money) {
+        Money aMoney= (Money)anObject;
+        return aMoney.currency().equals(currency())
+            && amount() == aMoney.amount();
+    }
+    return false;
+}
+Since equals can receive any kind of object as its argument we first have +to check its type before we cast it as a Money. As an aside, it is a recommended +practice to also override the method hashCode whenever you override method +equals. However, we want to get back to our test case. +

With an equals method in hand we can verify the outcome of testSimpleAdd. +In JUnit you do so by a calling +Assert.assertTrue, +which triggers a failure that is recorded by JUnit when the argument isn't +true. Since assertions for equality are very common, there is also +an Assert.assertEquals convenience method. In addition to testing for equality +with equals, it reports the printed value of the two objects in the case they +differ. This lets us immediately see why a test failed in a JUnit test +result report. The value a string representation created by +the toString converter method. +There are +other asertXXXX variants not discussed here. +

Now that we have implemented two test cases we notice some code duplication +for setting-up the tests. It would be nice to reuse some of this test set-up +code. In other words, we would like to have a common fixture for running +the tests. With JUnit you can do so by storing the fixture's objects in +instance variables of your +TestCase +subclass and initialize them by overridding +the setUp method. The symmetric operation to setUp is tearDown which you +can override to clean up the test fixture at the end of a test. Each test +runs in its own fixture and JUnit calls setUp and tearDown for each test +so that there can be no side effects among test runs. +

public class MoneyTest extends TestCase {
+    private Money f12CHF;
+    private Money f14CHF;   
+
+    protected void setUp() {
+        f12CHF= new Money(12, "CHF");
+        f14CHF= new Money(14, "CHF");
+    }
+}
+We can rewrite the two test case methods, removing the common setup code: +
public void testEquals() {
+    Assert.assertTrue(!f12CHF.equals(null));
+    Assert.assertEquals(f12CHF, f12CHF);
+    Assert.assertEquals(f12CHF, new Money(12, "CHF"));
+    Assert.assertTrue(!f12CHF.equals(f14CHF));
+}
+
+public void testSimpleAdd() {
+    Money expected= new Money(26, "CHF");
+    Money result= f12CHF.add(f14CHF);
+    Assert.assertTrue(expected.equals(result));
+}
+Two additional steps are needed to run the two test cases: +
    +
  1. +define how to run an individual test case,
  2. + +
  3. +define how to run a test suite.
  4. +
+JUnit supports two ways of running single tests: +
    +
  • +static
  • + +
  • +dynamic
  • +
+In the static way you override the runTest method inherited from TestCase +and call the desired test case. A convenient way to do this is with an +anonymous inner class. Note that each test must be given a name, so you +can identify it if it fails. +
TestCase test= new MoneyTest("simple add") {
+    public void runTest() {
+        testSimpleAdd();
+    }
+};
+A template method[1] +in the superclass will make sure runTest is executed when the time comes. +

The dynamic way to create a test case to be run uses reflection to implement +runTest. It assumes the name of the test is the name of the test case method +to invoke. It dynamically finds and invokes the test method. To invoke +the testSimpleAdd test we therefore construct a MoneyTest as shown below: +

TestCase test= new MoneyTest("testSimpleAdd");
+The dynamic way is more compact to write but it is less static type safe. +An error in the name of the test case goes unnoticed until you run it and +get a NoSuchMethodException. Since both approaches have advantages, we +decided to leave the choice of which to use up to you. +

As the last step to getting both test cases to run together, we have +to define a test suite. In JUnit this requires the definition of a static +method called suite. The suite method is like a main method that is specialized +to run tests. Inside suite you add the tests to be run to a +TestSuite object +and return it. A TestSuite can run a collection of tests. TestSuite and +TestCase both implement an interface called Test which defines the methods +to run a test. This enables the creation of test suites by composing arbitrary +TestCases and TestSuites. In short TestSuite is a Composite [1]. +The code below illustrates the creation of a test suite with the dynamic +way to run a test. +

public static Test suite() {
+    TestSuite suite= new TestSuite();
+    suite.addTest(new MoneyTest("testEquals"));
+    suite.addTest(new MoneyTest("testSimpleAdd"));
+    return suite;
+}
+Since JUnit 2.0 there is an even simpler dynamic way. You only pass the +class with the tests to a TestSuite and it extracts the test methods automatically. +

public static Test suite() {
+    return new TestSuite(MoneyTest.class);
+}
+

Here is the corresponding code using the static way. +

public static Test suite() {
+    TestSuite suite= new TestSuite();
+    suite.addTest(
+        new MoneyTest("money equals") {
+            protected void runTest() { testEquals(); }
+        }
+    );
+    
+    suite.addTest(
+        new MoneyTest("simple add") {
+            protected void runTest() { testSimpleAdd(); }
+        }
+    );
+    return suite;
+}
+Now we are ready to run our tests. JUnit comes with a graphical  interface +to run tests. Type the name of your test class in the field at the top +of the window. Press the Run button. While the test is run JUnit shows +its progress with a progress bar below the input field. The bar is initially +green but turns into red as soon as there is an unsuccessful test. Failed +tests are shown in a list at the bottom. Figure 1 +shows the TestRunner window after we run our trivial test suite. +
+
Figure 1: A Successful Run
+ +

After having verified that the simple currency case works we move on +to multiple currencies. As mentioned above the problem of mixed currency +arithmetic is that there isn't a single exchange rate. To avoid this problem +we introduce a MoneyBag which 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. We can later evaluate a MoneyBag with different +exchange rates. +

A MoneyBag is represented as a list of Monies and provides different +constructors to create a MoneyBag. Note, that the constructors are package +private since MoneyBags are created behind the scenes when doing currency +arithmetic. +

class MoneyBag {
+    private Vector fMonies= new Vector();
+
+    MoneyBag(Money m1, Money m2) {
+        appendMoney(m1);
+        appendMoney(m2);
+    }
+
+    MoneyBag(Money bag[]) {
+        for (int i= 0; i < bag.length; i++)
+            appendMoney(bag[i]);
+    }
+}
+The method appendMoney is an internal helper method that adds a Money to +the list of Moneys and takes care of consolidating Monies with the same +currency. MoneyBag also needs an equals method together with a corresponding +test. We skip the implementation of equals and only show the testBagEquals +method. In a first step we extend the fixture to include two MoneyBags. +
protected void setUp() {
+    f12CHF= new Money(12, "CHF");
+    f14CHF= new Money(14, "CHF");
+    f7USD=  new Money( 7, "USD");
+    f21USD= new Money(21, "USD");
+    fMB1= new MoneyBag(f12CHF, f7USD);
+    fMB2= new MoneyBag(f14CHF, f21USD);
+}
+With this fixture the testBagEquals test case becomes: +
public void testBagEquals() {
+    Assert.assertTrue(!fMB1.equals(null));
+    Assert.assertEquals(fMB1, fMB1);
+    Assert.assertTrue(!fMB1.equals(f12CHF));
+    Assert.assertTrue(!f12CHF.equals(fMB1));
+    Assert.assertTrue(!fMB1.equals(fMB2));
+}
+Following "code a little, test a little" we run our extended test with +JUnit and verify that we are still doing fine. With MoneyBag in hand, we +can now fix the add method in Money. +
public Money add(Money m) {
+    if (m.currency().equals(currency()) )
+        return new Money(amount()+m.amount(), currency());
+    return new MoneyBag(this, m);
+}
+As defined above this method will not compile since it expects a Money +and not a MoneyBag as its return value. With the introduction of MoneyBag +there are now two representations for Moneys which we would like to hide +from the client code. To do so we introduce an interface IMoney that both +representations implement. Here is the IMoney interface: +
interface IMoney {
+    public abstract IMoney add(IMoney aMoney);
+    //…
+}
+To fully hide the different representations from the client we have to +support arithmetic between all combinations of Moneys with MoneyBags. Before +we code on, we therefore define a couple more test cases. The expected +MoneyBag results use the convenience constructor shown above, initializing +a MoneyBag from an array. +
public void testMixedSimpleAdd() { 
+    // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} 
+    Money bag[]= { f12CHF, f7USD }; 
+    MoneyBag expected= new MoneyBag(bag); 
+    Assert.assertEquals(expected, f12CHF.add(f7USD)); 
+}
+The other tests follow the same pattern: + +
  • +testBagSimpleAdd - to add a MoneyBag to a simple Money
  • + +
  • +testSimpleBagAdd - to add a simple Money to a MoneyBag
  • + +
  • +testBagBagAdd - to add two MoneyBags
  • +
    +Next, we extend our test suite accordingly: +
    public static Test suite() {
    +    TestSuite suite= new TestSuite();
    +    suite.addTest(new MoneyTest("testMoneyEquals"));
    +    suite.addTest(new MoneyTest("testBagEquals"));
    +    suite.addTest(new MoneyTest("testSimpleAdd"));
    +    suite.addTest(new MoneyTest("testMixedSimpleAdd"));
    +    suite.addTest(new MoneyTest("testBagSimpleAdd"));
    +    suite.addTest(new MoneyTest("testSimpleBagAdd"));
    +    suite.addTest(new MoneyTest("testBagBagAdd"));
    +    return suite;
    +}
    +Having defined the test cases we can start to implement them. The implementation +challenge here is dealing with all the different combinations of Money +with MoneyBag. Double dispatch [2] +is an elegant way to solve this problem. The idea behind double dispatch +is to use an additional call to discover the kind of argument we are dealing +with. We call a method on the argument with the name of the original method +followed by the class name of the receiver. The add method in Money and +MoneyBag becomes: +
    class Money implements IMoney {
    +    public IMoney add(IMoney m) {
    +        return m.addMoney(this);
    +    }
    +    //…
    +}
    + +
    class MoneyBag implements IMoney {
    +    public IMoney add(IMoney m) {
    +        return m.addMoneyBag(this);
    +    }
    +    //…
    +}
    +In order to get this to compile we need to extend the interface of IMoney +with the two helper methods: +
    interface IMoney {
    +//…
    +    IMoney addMoney(Money aMoney);
    +    IMoney addMoneyBag(MoneyBag aMoneyBag);
    +}
    +To complete the implementation of double dispatch, we have to implement +these methods in Money and MoneyBag. This is the implementation in Money. +
    public IMoney addMoney(Money m) {
    +    if (m.currency().equals(currency()) )
    +        return new Money(amount()+m.amount(), currency());
    +    return new MoneyBag(this, m);
    +}
    +
    +public IMoney addMoneyBag(MoneyBag s) {
    +    return s.addMoney(this);
    +}
    +Here is the implemenation in MoneyBag which assumes additional constructors +to create a MoneyBag from a Money and a MoneyBag and from two MoneyBags. +
    public IMoney addMoney(Money m) {
    +    return new MoneyBag(m, this);
    +}
    +
    +public IMoney addMoneyBag(MoneyBag s) {
    +    return new MoneyBag(s, this);
    +}
    +We run the tests, and they pass. However, while reflecting on the implementation +we discover another interesting case. What happens when as the result of +an addition a MoneyBag turns into a bag with only one Money? For example, +adding -12 CHF to a Moneybag holding 7 USD and 12 CHF results in a bag +with just 7 USD. Obviously, such a bag should be equal with a single Money +of 7 USD. To verify the problem let's implement a test case and run it. +
    public void testSimplify() {
    +    // {[12 CHF][7 USD]} + [-12 CHF] == [7 USD]
    +    Money expected= new Money(7, "USD");
    +    Assert.assertEquals(expected, fMB1.add(new Money(-12, "CHF")));
    +}
    +When you are developing in this style you will often have a thought and +turn immediately to writing a test, rather than going straight to the code. +

    It comes to no surprise that our test run ends with a red progress bar +indicating the failure. So we fix the code in MoneyBag to get back to a +green state. +

    public IMoney addMoney(Money m) {
    +    return (new MoneyBag(m, this)).simplify();
    +}
    +
    +public IMoney addMoneyBag(MoneyBag s) {
    +    return (new MoneyBag(s, this)).simplify();
    +}
    +
    +private IMoney simplify() {
    +    if (fMonies.size() == 1)
    +        return (IMoney)fMonies.firstElement()
    +    return this;
    +}
    +Now we run our tests again and voila we end up with green. +

    The code above solves only a small portion of the multi-currency arithmetic +problem. We have to represent different exchange rates, print formatting, +and the other arithmetic operations, and do it all with reasonable speed. +However, we hope you can see how you could develop the rest of the objects +one test at a time- a little test, a little code, a little test, a little +code. +

    In particular, review how in the development above: +

      +
    • +We wrote the first test, testSimpleAdd, immediately after we had written +add(). In general, your development will go much smoother if you write +tests a little at a time as you develop. It is at the moment that you are +coding that you are imagining how that code will work. That's the perfect +time to capture your thoughts in a test.
    • + +
    • +We refactored the existing tests, testSimpleAdd and testEqual, as soon +as we introduced the common setUp code. Test code is just like model code +in working best if it is factored well. When you see you have the same +test code in two places, try to find a way to refactor it so it only appears +once.
    • + +
    • +We created a suite method, then extended it when we applied Double Dispatch. +Keeping old tests running is just as important as making new ones run. +The ideal is to always run all of your tests. Sometimes that will be too +slow to do 10 times an hour. Make sure you run all of your tests at least +daily.
    • + +
    • +We created a new test immediately when we thought of the requirement that +a one element MoneyBag should just return its element. It can be difficult +to learn to switch gears like this, but we have found it valuable. When +you are struck by an idea of what your system should do, defer thinking +about the implementation. Instead, first write the test. Then run it (you +never know, it might already work). Then work on the implementation.
    • +
    + +

    +Testing Practices

    +Martin Fowler makes this easy for you. He says, "Whenever you are tempted +to type something into a print statement or a debugger expression, write +it as a test instead." At first you will find that you have to create a +new fixtures all the time, and testing will seem to slow you down a little. +Soon, however, you will begin reusing your library of fixtures and new +tests will usually be as simple as adding a method to an existing TestCase +subclass. +

    You can always write more tests. However, you will quickly find that +only a fraction of the tests you can imagine are actually useful. What +you want is to write tests that fail even though you think they should +work, or tests that succeed even though you think they should fail. Another +way to think of it is in cost/benefit terms. You want to write tests that +will pay you back with information. +

    Here are a couple of the times that you will receive a reasonable return +on your testing investment: +

      +
    • +During Development- When you need to add new functionality to the system, +write the tests first. Then, you will be done developing when the test +runs.
    • + +
    • +During Debugging- When someone discovers a defect in your code, first write +a test that will succeed if the code is working. Then debug until the test +succeeds.
    • +
    +One word of caution about your tests. Once you get them running, make sure +they stay running. There is a huge difference between having your suite +running and having it broken. Ideally, you would run every test in your +suite every time you change a method. Practically, your suite will soon +grow too large to run all the time. Try to optimize your setup code so +you can run all the tests. Or, at the very least, create special suites +that contain all the tests that might possibly be affected by your current +development. Then, run the suite every time you compile. And make sure +you run every test at least once a day: overnight, during lunch, during +one of those long meetings…. +

    +Conclusion

    +This article only scratches the surface of testing. However, it focuses +on a style of testing that with a remarkably small investment will make +you a faster, more productive, more predictable, and less stressed developer. +

    Once you've been test infected, your attitude toward development is +likely to change. Here are some of the changes we have noticed: +

    There is a huge difference between tests that are all running correctly +and tests that aren't. Part of being test infected is not being able to +go home if your tests aren't 100%. If you run your suite ten or a hundred +times an hour, though, you won't be able to create enough havoc to make +you late for supper. +

    Sometimes you just won't feel like writing tests, especially at first. +Don't. However, pay attention to how much more trouble you get into, how +much more time you spend debugging, and how much more stress you feel when +you don't have tests. We have been amazed at how much more fun programming +is and how much more aggressive we are willing to be and how much less +stress we feel when we are supported by tests. The difference is dramatic +enough to keep us writing tests even when we don't feel like it. +

    You will be able to refactor much more aggressively once you have the +tests. You won't understand at first just how much you can do, though. +Try to catch yourself saying, "Oh, I see, I should have designed this thus +and so. I can't change it now. I don't want to break anything." When you +say this, save a copy of your current code and give yourself a couple of +hours to clean up. (This part works best you can get a buddy to look over +your shoulder while you work.) Make your changes, all the while running +your tests. You will be surprised at how much ground you can cover in a +couple of hours if you aren't worrying every second about what you might +be breaking. +

    For example, we switched from the Vector-based implementation of MoneyBag +to one based on HashTable. We were able to make the switch very quickly +and confidently because we had so many tests to rely on. If the tests all +worked, we were sure we hadn't changed the answers the system produced +at all. +

    You will want to get the rest of your team writing tests. The best way +we have found to spread the test infection is through direct contact. The +next time someone asks you for help debugging, get them to talk about the +problem in terms of a fixture and expected results. Then say, "I'd like +to write down what you just told me in a form we can use." Have them watch +while you write one little test. Run it. Fix it. Write another. Pretty +soon they will be writing their own. +

    So- give JUnit a try. If you make it better, please send us the changes +so we can spread them around. Our next article will double click on the +JUnit framework itself. We will show you how it is constructed, and talk +a little about our philosophy of framework development. +

    We would like to thank Martin Fowler, as good a programmer as any analyst +can ever hope to be, for his helpful comments in spite of being subjected +to early versions of JUnit. +

    +References

    + +
      +
    1. +Gamma, E., +et al. Design Patterns: Elements of Reusable Object-Oriented Software, +Addison-Wesley, Reading, MA, 1995
    2. + +
    3. +Beck, K. Smalltalk +Best Practice Patterns, Prentice Hall, 1996
    4. +
    + +
    + + diff --git a/epl-v10.html b/epl-v10.html new file mode 100644 index 000000000000..3998fcebeebe --- /dev/null +++ b/epl-v10.html @@ -0,0 +1,261 @@ + + + + + + +Eclipse Public License - Version 1.0 + + + + + + +

    Eclipse Public License - v 1.0

    + +

    THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE +PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR +DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS +AGREEMENT.

    + +

    1. DEFINITIONS

    + +

    "Contribution" means:

    + +

    a) in the case of the initial Contributor, the initial +code and documentation distributed under this Agreement, and

    +

    b) in the case of each subsequent Contributor:

    +

    i) changes to the Program, and

    +

    ii) additions to the Program;

    +

    where such changes and/or additions to the Program +originate from and are distributed by that particular Contributor. A +Contribution 'originates' from a Contributor if it was added to the +Program by such Contributor itself or anyone acting on such +Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in +conjunction with the Program under their own license agreement, and (ii) +are not derivative works of the Program.

    + +

    "Contributor" means any person or entity that distributes +the Program.

    + +

    "Licensed Patents" mean patent claims licensable by a +Contributor which are necessarily infringed by the use or sale of its +Contribution alone or when combined with the Program.

    + +

    "Program" means the Contributions distributed in accordance +with this Agreement.

    + +

    "Recipient" means anyone who receives the Program under +this Agreement, including all Contributors.

    + +

    2. GRANT OF RIGHTS

    + +

    a) Subject to the terms of this Agreement, each +Contributor hereby grants Recipient a non-exclusive, worldwide, +royalty-free copyright license to reproduce, prepare derivative works +of, publicly display, publicly perform, distribute and sublicense the +Contribution of such Contributor, if any, and such derivative works, in +source code and object code form.

    + +

    b) Subject to the terms of this Agreement, each +Contributor hereby grants Recipient a non-exclusive, worldwide, +royalty-free patent license under Licensed Patents to make, use, sell, +offer to sell, import and otherwise transfer the Contribution of such +Contributor, if any, in source code and object code form. This patent +license shall apply to the combination of the Contribution and the +Program if, at the time the Contribution is added by the Contributor, +such addition of the Contribution causes such combination to be covered +by the Licensed Patents. The patent license shall not apply to any other +combinations which include the Contribution. No hardware per se is +licensed hereunder.

    + +

    c) Recipient understands that although each Contributor +grants the licenses to its Contributions set forth herein, no assurances +are provided by any Contributor that the Program does not infringe the +patent or other intellectual property rights of any other entity. Each +Contributor disclaims any liability to Recipient for claims brought by +any other entity based on infringement of intellectual property rights +or otherwise. As a condition to exercising the rights and licenses +granted hereunder, each Recipient hereby assumes sole responsibility to +secure any other intellectual property rights needed, if any. For +example, if a third party patent license is required to allow Recipient +to distribute the Program, it is Recipient's responsibility to acquire +that license before distributing the Program.

    + +

    d) Each Contributor represents that to its knowledge it +has sufficient copyright rights in its Contribution, if any, to grant +the copyright license set forth in this Agreement.

    + +

    3. REQUIREMENTS

    + +

    A Contributor may choose to distribute the Program in object code +form under its own license agreement, provided that:

    + +

    a) it complies with the terms and conditions of this +Agreement; and

    + +

    b) its license agreement:

    + +

    i) effectively disclaims on behalf of all Contributors +all warranties and conditions, express and implied, including warranties +or conditions of title and non-infringement, and implied warranties or +conditions of merchantability and fitness for a particular purpose;

    + +

    ii) effectively excludes on behalf of all Contributors +all liability for damages, including direct, indirect, special, +incidental and consequential damages, such as lost profits;

    + +

    iii) states that any provisions which differ from this +Agreement are offered by that Contributor alone and not by any other +party; and

    + +

    iv) states that source code for the Program is available +from such Contributor, and informs licensees how to obtain it in a +reasonable manner on or through a medium customarily used for software +exchange.

    + +

    When the Program is made available in source code form:

    + +

    a) it must be made available under this Agreement; and

    + +

    b) a copy of this Agreement must be included with each +copy of the Program.

    + +

    Contributors may not remove or alter any copyright notices contained +within the Program.

    + +

    Each Contributor must identify itself as the originator of its +Contribution, if any, in a manner that reasonably allows subsequent +Recipients to identify the originator of the Contribution.

    + +

    4. COMMERCIAL DISTRIBUTION

    + +

    Commercial distributors of software may accept certain +responsibilities with respect to end users, business partners and the +like. While this license is intended to facilitate the commercial use of +the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create +potential liability for other Contributors. Therefore, if a Contributor +includes the Program in a commercial product offering, such Contributor +("Commercial Contributor") hereby agrees to defend and +indemnify every other Contributor ("Indemnified Contributor") +against any losses, damages and costs (collectively "Losses") +arising from claims, lawsuits and other legal actions brought by a third +party against the Indemnified Contributor to the extent caused by the +acts or omissions of such Commercial Contributor in connection with its +distribution of the Program in a commercial product offering. The +obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In +order to qualify, an Indemnified Contributor must: a) promptly notify +the Commercial Contributor in writing of such claim, and b) allow the +Commercial Contributor to control, and cooperate with the Commercial +Contributor in, the defense and any related settlement negotiations. The +Indemnified Contributor may participate in any such claim at its own +expense.

    + +

    For example, a Contributor might include the Program in a commercial +product offering, Product X. That Contributor is then a Commercial +Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance +claims and warranties are such Commercial Contributor's responsibility +alone. Under this section, the Commercial Contributor would have to +defend claims against the other Contributors related to those +performance claims and warranties, and if a court requires any other +Contributor to pay any damages as a result, the Commercial Contributor +must pay those damages.

    + +

    5. NO WARRANTY

    + +

    EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS +PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, +ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY +OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and +distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement , including but not limited to +the risks and costs of program errors, compliance with applicable laws, +damage to or loss of data, programs or equipment, and unavailability or +interruption of operations.

    + +

    6. DISCLAIMER OF LIABILITY

    + +

    EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT +NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR +DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

    + +

    7. GENERAL

    + +

    If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this Agreement, and without further action +by the parties hereto, such provision shall be reformed to the minimum +extent necessary to make such provision valid and enforceable.

    + +

    If Recipient institutes patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that the +Program itself (excluding combinations of the Program with other +software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the +date such litigation is filed.

    + +

    All Recipient's rights under this Agreement shall terminate if it +fails to comply with any of the material terms or conditions of this +Agreement and does not cure such failure in a reasonable period of time +after becoming aware of such noncompliance. If all Recipient's rights +under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive.

    + +

    Everyone is permitted to copy and distribute copies of this +Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The +Agreement Steward reserves the right to publish new versions (including +revisions) of this Agreement from time to time. No one other than the +Agreement Steward has the right to modify this Agreement. The Eclipse +Foundation is the initial Agreement Steward. The Eclipse Foundation may +assign the responsibility to serve as the Agreement Steward to a +suitable separate entity. Each new version of the Agreement will be +given a distinguishing version number. The Program (including +Contributions) may always be distributed subject to the version of the +Agreement under which it was received. In addition, after a new version +of the Agreement is published, Contributor may elect to distribute the +Program (including its Contributions) under the new version. Except as +expressly stated in Sections 2(a) and 2(b) above, Recipient receives no +rights or licenses to the intellectual property of any Contributor under +this Agreement, whether expressly, by implication, estoppel or +otherwise. All rights in the Program not expressly granted under this +Agreement are reserved.

    + +

    This Agreement is governed by the laws of the State of New York and +the intellectual property laws of the United States of America. No party +to this Agreement will bring a legal action under this Agreement more +than one year after the cause of action arose. Each party waives its +rights to a jury trial in any resulting litigation.

    + + + + \ No newline at end of file diff --git a/lib/hamcrest-core-1.3-sources.jar b/lib/hamcrest-core-1.3-sources.jar new file mode 100644 index 0000000000000000000000000000000000000000..c3c110b4dab6b916fc1ab30eaff8e16391d90d50 GIT binary patch literal 32624 zcmaI7190W*(mk9^Y} z{p)A->hAS)%S(ZPLIVLo0s(z3I_3xZ%L@t!6i7xyS%6MLR+Qm=3YUwt{61 zdq6<~eYr>d_hVjYwD5SVqr>G&%C>AwtZPhNxIn$6xFq@xjRx$H?)StB?!&x1qtqTk zTz5~;DCsgL9yds{8mF7geted8OxrobjUiAz zd59g%xe#Q=%nyEBTM-FQXCB^0!1Gcobyb>-5$le_ka2&R=u)IAD_O!i@V}l92#ED> zt^oafK3fMsZRlX^==2xUKb-a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@x_!xEH6~IS%J)kN8BALITem~gjG3ZYx7d?Pr07V2qpnqgGe>pZE zv+lbLSYrKwRSM{V-&y|>Tz?F^e?wrs><1VP;LH36*xy1w|Et-6rH~(>`G5n_euDz* zO94M0u<-2z3JkCV{2ld28QjOf`_=>2g?#|B00iBB13p%XeT=zpH(;^U2aE|JFy`OV zsgG&*4+Shd`9L!x0iyj^yWeAg)#)BE;Q&wBZ}0XO=8;w%@G}96t3AN5sDNOKu*%nSNYas%zXy{SH?VGti}F} z`K?X{7zbQL@qmky_%rT5ODZ0t@4Esx2l@d`C;MmgLq;?(3pkh;9 zq5do049o?Niau};U;L5#?-=Q0R^3GC#5fZ`he5&9>W|6}O=lLC8_AD}R%e}X>V%K)>0oxcyPd|=i;%iw>zf*(`w zUmMtA`9Kvn2YSMPsQ>A{d=5^bfv($L#wD2i{OWu=Q;J5A5Hz o*N^XU|NOxF&WC$s+5z3;_nw0U>;mo`9`qnPfX$Mv{rzA64{N)<=Kufz literal 0 HcmV?d00001 diff --git a/lib/hamcrest-core-1.3.jar b/lib/hamcrest-core-1.3.jar new file mode 100644 index 0000000000000000000000000000000000000000..9d5fe16e3dd37ebe79a36f61f5d0e1a69a653a8a GIT binary patch literal 45024 zcmaI81C*p&lQmqnZQHhOn_aeT+qTtZ+wQVmUAC*b%)j2bGxN>8@64Yo^W@64;>nfg zWbD|nBO+5l8W;o$00062fW7oo0N{VzAOS!CWJOg3X(i>v=s(8+02Kby6as+l+w|#c zNwVhK91suy0OkAnzfENYJ+q&~~XcVMg@)Q>u853k!`i`Ur45 zyu5Cd37@2HgH)`Wy1`l;*oM6)AovI`MZ*5P^GAe-{5dEZG0FFgLIHB7%e7m@~IKQ2JFQMZ<9=GfFm*%A&yCZ2FhNHwGWyrhp(buKg?hqDS+*3t9 zd{fJ?i!iu3WWuibV>u(s!C7Y9Ec@WNo2&8wt$(Q78NE9faKyXMFZx?z#3g=W!ggoW zxBju_^2Gk#d1;@npM{AJMlo8%y|Ejj#qPY!E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qNS-Waf40g^|n1mgYm9{q=S0k~=4Y|uy)w%VB}WNv6M3Y?4-iTa><77Ce& z^ykU`S87slW#HVE$jV5x|JTaS$Ycqw4xH!^S)I1d|5tTqcVcj=F(me~!CBb9$2enT z;xTYL!3lYgKyBl*fd5F(14e-pa3E1d=4YXPrQ-l|z@hs{PM!7HoYR5)U>-PV8p%W4 zKb!aG5Na?R94v=q|FA!s{g2Q&Fbo_PgM{h3oDBm9$$*Jq_j4ps(erHLZ)bEc3hbPV zMA`fN0rlHe7t8`XKq6UskI!Zy-66p&u)i6SB?>=_^+)eBFc|C`g9Oh7p9wz0QwGcg zyG|gPR8RlRJncvUW`a%ZNTy=gpP68TJD3W##UiQp5oc1*w9JC3U>g>a8W|0u{$7ur zVbKC(!S(?p_UZFKVgGC`0Mo&Hf=K#y{GaHjCnW#aAq2z0+e=9Jg{1!hetNU%#x)GU UgpPtD2z>DYYp}SJr5?)v0beu;=l}o! literal 0 HcmV?d00001 diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000000..38d502d049e1 --- /dev/null +++ b/pom.xml @@ -0,0 +1,576 @@ + + + 4.0.0 + + junit + junit + 4.13-SNAPSHOT + + JUnit + JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck. + http://junit.org + 2002 + + JUnit + http://www.junit.org + + + + Eclipse Public License 1.0 + http://www.eclipse.org/legal/epl-v10.html + repo + + + + + + dsaff + David Saff + david@saff.net + + + kcooney + Kevin Cooney + kcooney@google.com + + + stefanbirkner + Stefan Birkner + mail@stefan-birkner.de + + + marcphilipp + Marc Philipp + mail@marcphilipp.de + + + + + JUnit contributors + JUnit + junit@yahoogroups.com + https://github.com/junit-team/junit4/graphs/contributors + + developers + + + + + + + JUnit Mailing List + junit@yahoogroups.com + https://groups.yahoo.com/neo/groups/junit/info + + + + + 3.0.4 + + + + scm:git:git://github.com/junit-team/junit4.git + scm:git:git@github.com:junit-team/junit4.git + http://github.com/junit-team/junit4/tree/master + HEAD + + + github + https://github.com/junit-team/junit4/issues + + + jenkins + https://junit.ci.cloudbees.com/ + + + https://github.com/junit-team/junit4/wiki/Download-and-Install + + junit-snapshot-repo + Nexus Snapshot Repository + https://oss.sonatype.org/content/repositories/snapshots/ + + + junit-releases-repo + Nexus Release Repository + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + junit.github.io + gitsite:git@github.com/junit-team/junit4.git + + + + + 1.5 + 2.19.1 + 1.3 + ISO-8859-1 + + 67893CC4 + + + + + org.hamcrest + hamcrest-core + ${hamcrestVersion} + + + + org.hamcrest + hamcrest-library + ${hamcrestVersion} + test + + + + + + + ${project.basedir}/src/main/resources + + + ${project.basedir} + + LICENSE-junit.txt + + + + + + + + maven-enforcer-plugin + 1.4 + + + enforce-versions + initialize + + enforce + + + true + + + + Current version of Maven ${maven.version} required to build the project + should be ${project.prerequisites.maven}, or higher! + + [${project.prerequisites.maven},) + + + Current JDK version ${java.version} should be ${jdkVersion}, or higher! + + ${jdkVersion} + + + Best Practice is to never define repositories in pom.xml (use a repository + manager instead). + + + + No Snapshots Dependencies Allowed! + + + + + + + + + com.google.code.maven-replacer-plugin + replacer + 1.5.3 + + + process-sources + + replace + + + + + false + ${project.build.sourceDirectory}/junit/runner/Version.java.template + ${project.build.sourceDirectory}/junit/runner/Version.java + false + @version@ + ${project.version} + + + + + maven-compiler-plugin + 3.3 + + ${project.build.sourceEncoding} + ${jdkVersion} + ${jdkVersion} + ${jdkVersion} + ${jdkVersion} + 1.5 + true + true + true + true + + -Xlint:unchecked + + 128m + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.14 + + + signature-check + test + + check + + + + org.codehaus.mojo.signature + java15 + 1.0 + + + + + + + + maven-surefire-plugin + ${surefireVersion} + + org/junit/tests/AllTests.java + true + false + + + + org.apache.maven.surefire + surefire-junit47 + ${surefireVersion} + + + + + + maven-source-plugin + 2.4 + + + + maven-javadoc-plugin + 2.10.3 + + ${basedir}/src/main/javadoc/stylesheet.css + protected + false + false + false + true + true + true + JUnit API + UTF-8 + en + ${jdkVersion} + + + api_${jdkVersion} + http://docs.oracle.com/javase/${jdkVersion}.0/docs/api/ + + + junit.*,*.internal.* + true + 32m + 128m + true + true + + org.hamcrest:hamcrest-core:* + + + + + maven-release-plugin + 2.5.2 + + forked-path + false + -Pgenerate-docs,junit-release ${arguments} + r@{project.version} + + + + maven-site-plugin + 3.4 + + + com.github.stephenc.wagon + wagon-gitsite + 0.4.1 + + + org.apache.maven.doxia + doxia-module-markdown + 1.5 + + + + + maven-jar-plugin + 2.6 + + + false + + true + + + + + + maven-clean-plugin + 2.6.1 + + + maven-deploy-plugin + 2.8.2 + + + maven-install-plugin + 2.5.2 + + + maven-resources-plugin + 2.7 + + + + + + + + maven-project-info-reports-plugin + 2.8 + + false + + + + + + index + dependency-info + modules + license + project-team + scm + issue-tracking + mailing-list + dependency-management + dependencies + dependency-convergence + cim + distribution-management + + + + + + maven-javadoc-plugin + 2.10.1 + + javadoc/latest + ${basedir}/src/main/javadoc/stylesheet.css + protected + false + false + false + true + true + true + JUnit API + UTF-8 + en + ${jdkVersion} + + + api_${jdkVersion} + http://docs.oracle.com/javase/${jdkVersion}.0/docs/api/ + + + junit.*,*.internal.* + true + 32m + 128m + true + true + + org.hamcrest:hamcrest-core:* + + + + + + javadoc + + + + + + + + + + junit-release + + + + + + maven-gpg-plugin + 1.6 + + + gpg-sign + verify + + sign + + + + + + + + + generate-docs + + + + + maven-source-plugin + + + attach-sources + prepare-package + + jar-no-fork + + + + + + maven-javadoc-plugin + + + attach-javadoc + package + + jar + + + + + + + + + restrict-doclint + + + [1.8,) + + + + + maven-compiler-plugin + + + -Xlint:unchecked + -Xdoclint:accessibility,reference,syntax + + + + + maven-javadoc-plugin + + -Xdoclint:accessibility -Xdoclint:reference + + + + + + + + maven-javadoc-plugin + + -Xdoclint:accessibility -Xdoclint:reference + + + + + + + fast-tests + + + + maven-surefire-plugin + + classes + 2 + + + + + + + diff --git a/src/changes/changes.xml b/src/changes/changes.xml new file mode 100644 index 000000000000..e2631b19f28b --- /dev/null +++ b/src/changes/changes.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/junit/extensions/ActiveTestSuite.java b/src/main/java/junit/extensions/ActiveTestSuite.java new file mode 100644 index 000000000000..95c5e2e71062 --- /dev/null +++ b/src/main/java/junit/extensions/ActiveTestSuite.java @@ -0,0 +1,70 @@ +package junit.extensions; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; + +/** + * A TestSuite for active Tests. It runs each + * test in a separate thread and waits until all + * threads have terminated. + * -- Aarhus Radisson Scandinavian Center 11th floor + */ +public class ActiveTestSuite extends TestSuite { + private volatile int fActiveTestDeathCount; + + public ActiveTestSuite() { + } + + public ActiveTestSuite(Class theClass) { + super(theClass); + } + + public ActiveTestSuite(String name) { + super(name); + } + + public ActiveTestSuite(Class theClass, String name) { + super(theClass, name); + } + + @Override + public void run(TestResult result) { + fActiveTestDeathCount = 0; + super.run(result); + waitUntilFinished(); + } + + @Override + public void runTest(final Test test, final TestResult result) { + Thread t = new Thread() { + @Override + public void run() { + try { + // inlined due to limitation in VA/Java + //ActiveTestSuite.super.runTest(test, result); + test.run(result); + } finally { + ActiveTestSuite.this.runFinished(); + } + } + }; + t.start(); + } + + synchronized void waitUntilFinished() { + while (fActiveTestDeathCount < testCount()) { + try { + wait(); + } catch (InterruptedException e) { + return; // ignore + } + } + } + + synchronized public void runFinished() { + fActiveTestDeathCount++; + notifyAll(); + } +} \ No newline at end of file diff --git a/src/main/java/junit/extensions/RepeatedTest.java b/src/main/java/junit/extensions/RepeatedTest.java new file mode 100644 index 000000000000..22c690a9401b --- /dev/null +++ b/src/main/java/junit/extensions/RepeatedTest.java @@ -0,0 +1,39 @@ +package junit.extensions; + +import junit.framework.Test; +import junit.framework.TestResult; + +/** + * A Decorator that runs a test repeatedly. + */ +public class RepeatedTest extends TestDecorator { + private int fTimesRepeat; + + public RepeatedTest(Test test, int repeat) { + super(test); + if (repeat < 0) { + throw new IllegalArgumentException("Repetition count must be >= 0"); + } + fTimesRepeat = repeat; + } + + @Override + public int countTestCases() { + return super.countTestCases() * fTimesRepeat; + } + + @Override + public void run(TestResult result) { + for (int i = 0; i < fTimesRepeat; i++) { + if (result.shouldStop()) { + break; + } + super.run(result); + } + } + + @Override + public String toString() { + return super.toString() + "(repeated)"; + } +} \ No newline at end of file diff --git a/src/main/java/junit/extensions/TestDecorator.java b/src/main/java/junit/extensions/TestDecorator.java new file mode 100644 index 000000000000..a3c5e08c548e --- /dev/null +++ b/src/main/java/junit/extensions/TestDecorator.java @@ -0,0 +1,43 @@ +package junit.extensions; + +import junit.framework.Assert; +import junit.framework.Test; +import junit.framework.TestResult; + +/** + * A Decorator for Tests. Use TestDecorator as the base class for defining new + * test decorators. Test decorator subclasses can be introduced to add behaviour + * before or after a test is run. + */ +@SuppressWarnings("deprecation") +public class TestDecorator extends Assert implements Test { + protected Test fTest; + + public TestDecorator(Test test) { + fTest = test; + } + + /** + * The basic run behaviour. + */ + public void basicRun(TestResult result) { + fTest.run(result); + } + + public int countTestCases() { + return fTest.countTestCases(); + } + + public void run(TestResult result) { + basicRun(result); + } + + @Override + public String toString() { + return fTest.toString(); + } + + public Test getTest() { + return fTest; + } +} \ No newline at end of file diff --git a/src/main/java/junit/extensions/TestSetup.java b/src/main/java/junit/extensions/TestSetup.java new file mode 100644 index 000000000000..fcdca8cc51bd --- /dev/null +++ b/src/main/java/junit/extensions/TestSetup.java @@ -0,0 +1,42 @@ +package junit.extensions; + +import junit.framework.Protectable; +import junit.framework.Test; +import junit.framework.TestResult; + +/** + * A Decorator to set up and tear down additional fixture state. Subclass + * TestSetup and insert it into your tests when you want to set up additional + * state once before the tests are run. + */ +public class TestSetup extends TestDecorator { + + public TestSetup(Test test) { + super(test); + } + + @Override + public void run(final TestResult result) { + Protectable p = new Protectable() { + public void protect() throws Exception { + setUp(); + basicRun(result); + tearDown(); + } + }; + result.runProtected(this, p); + } + + /** + * Sets up the fixture. Override to set up additional fixture state. + */ + protected void setUp() throws Exception { + } + + /** + * Tears down the fixture. Override to tear down the additional fixture + * state. + */ + protected void tearDown() throws Exception { + } +} \ No newline at end of file diff --git a/src/main/java/junit/extensions/package-info.java b/src/main/java/junit/extensions/package-info.java new file mode 100644 index 000000000000..a1c5bb4c9573 --- /dev/null +++ b/src/main/java/junit/extensions/package-info.java @@ -0,0 +1,4 @@ +/** + * Provides extended functionality for JUnit v3.x. + */ +package junit.extensions; \ No newline at end of file diff --git a/src/main/java/junit/framework/Assert.java b/src/main/java/junit/framework/Assert.java new file mode 100644 index 000000000000..663461c7ab79 --- /dev/null +++ b/src/main/java/junit/framework/Assert.java @@ -0,0 +1,339 @@ +package junit.framework; + +/** + * A set of assert methods. Messages are only displayed when an assert fails. + * + * @deprecated Please use {@link org.junit.Assert} instead. + */ +@Deprecated +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertTrue(String message, boolean condition) { + if (!condition) { + fail(message); + } + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertTrue(boolean condition) { + assertTrue(null, condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws + * an AssertionFailedError with the given message. + */ + static public void assertFalse(String message, boolean condition) { + assertTrue(message, !condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws + * an AssertionFailedError. + */ + static public void assertFalse(boolean condition) { + assertFalse(null, condition); + } + + /** + * Fails a test with the given message. + */ + static public void fail(String message) { + if (message == null) { + throw new AssertionFailedError(); + } + throw new AssertionFailedError(message); + } + + /** + * Fails a test with no message. + */ + static public void fail() { + fail(null); + } + + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, Object expected, Object actual) { + if (expected == null && actual == null) { + return; + } + if (expected != null && expected.equals(actual)) { + return; + } + failNotEquals(message, expected, actual); + } + + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + static public void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two Strings are equal. + */ + static public void assertEquals(String message, String expected, String actual) { + if (expected == null && actual == null) { + return; + } + if (expected != null && expected.equals(actual)) { + return; + } + String cleanMessage = message == null ? "" : message; + throw new ComparisonFailure(cleanMessage, expected, actual); + } + + /** + * Asserts that two Strings are equal. + */ + static public void assertEquals(String expected, String actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two doubles are equal concerning a delta. If they are not + * an AssertionFailedError is thrown with the given message. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, double expected, double actual, double delta) { + if (Double.compare(expected, actual) == 0) { + return; + } + if (!(Math.abs(expected - actual) <= delta)) { + failNotEquals(message, new Double(expected), new Double(actual)); + } + } + + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that two floats are equal concerning a positive delta. If they + * are not an AssertionFailedError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored. + */ + static public void assertEquals(String message, float expected, float actual, float delta) { + if (Float.compare(expected, actual) == 0) { + return; + } + if (!(Math.abs(expected - actual) <= delta)) { + failNotEquals(message, new Float(expected), new Float(actual)); + } + } + + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + static public void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that two longs are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, long expected, long actual) { + assertEquals(message, Long.valueOf(expected), Long.valueOf(actual)); + } + + /** + * Asserts that two longs are equal. + */ + static public void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two booleans are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, boolean expected, boolean actual) { + assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual)); + } + + /** + * Asserts that two booleans are equal. + */ + static public void assertEquals(boolean expected, boolean actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two bytes are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, byte expected, byte actual) { + assertEquals(message, Byte.valueOf(expected), Byte.valueOf(actual)); + } + + /** + * Asserts that two bytes are equal. + */ + static public void assertEquals(byte expected, byte actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two chars are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, char expected, char actual) { + assertEquals(message, Character.valueOf(expected), Character.valueOf(actual)); + } + + /** + * Asserts that two chars are equal. + */ + static public void assertEquals(char expected, char actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two shorts are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, short expected, short actual) { + assertEquals(message, Short.valueOf(expected), Short.valueOf(actual)); + } + + /** + * Asserts that two shorts are equal. + */ + static public void assertEquals(short expected, short actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two ints are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertEquals(String message, int expected, int actual) { + assertEquals(message, Integer.valueOf(expected), Integer.valueOf(actual)); + } + + /** + * Asserts that two ints are equal. + */ + static public void assertEquals(int expected, int actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that an object isn't null. + */ + static public void assertNotNull(Object object) { + assertNotNull(null, object); + } + + /** + * Asserts that an object isn't null. If it is + * an AssertionFailedError is thrown with the given message. + */ + static public void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + /** + * Asserts that an object is null. If it isn't an {@link AssertionError} is + * thrown. + * Message contains: Expected: but was: object + * + * @param object Object to check or null + */ + static public void assertNull(Object object) { + if (object != null) { + assertNull("Expected: but was: " + object.toString(), object); + } + } + + /** + * Asserts that an object is null. If it is not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertNull(String message, Object object) { + assertTrue(message, object == null); + } + + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown with the given message. + */ + static public void assertSame(String message, Object expected, Object actual) { + if (expected == actual) { + return; + } + failNotSame(message, expected, actual); + } + + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + static public void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object an AssertionFailedError is thrown with the + * given message. + */ + static public void assertNotSame(String message, Object expected, Object actual) { + if (expected == actual) { + failSame(message); + } + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object an AssertionFailedError is thrown. + */ + static public void assertNotSame(Object expected, Object actual) { + assertNotSame(null, expected, actual); + } + + static public void failSame(String message) { + String formatted = (message != null) ? message + " " : ""; + fail(formatted + "expected not same"); + } + + static public void failNotSame(String message, Object expected, Object actual) { + String formatted = (message != null) ? message + " " : ""; + fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); + } + + static public void failNotEquals(String message, Object expected, Object actual) { + fail(format(message, expected, actual)); + } + + public static String format(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null && message.length() > 0) { + formatted = message + " "; + } + return formatted + "expected:<" + expected + "> but was:<" + actual + ">"; + } +} diff --git a/src/main/java/junit/framework/AssertionFailedError.java b/src/main/java/junit/framework/AssertionFailedError.java new file mode 100644 index 000000000000..e11fbec9f16a --- /dev/null +++ b/src/main/java/junit/framework/AssertionFailedError.java @@ -0,0 +1,29 @@ +package junit.framework; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends AssertionError { + + private static final long serialVersionUID = 1L; + + /** + * Constructs a new AssertionFailedError without a detail message. + */ + public AssertionFailedError() { + } + + /** + * Constructs a new AssertionFailedError with the specified detail message. + * A null message is replaced by an empty String. + * @param message the detail message. The detail message is saved for later + * retrieval by the {@code Throwable.getMessage()} method. + */ + public AssertionFailedError(String message) { + super(defaultString(message)); + } + + private static String defaultString(String message) { + return message == null ? "" : message; + } +} \ No newline at end of file diff --git a/src/main/java/junit/framework/ComparisonCompactor.java b/src/main/java/junit/framework/ComparisonCompactor.java new file mode 100644 index 000000000000..81ddd5bda514 --- /dev/null +++ b/src/main/java/junit/framework/ComparisonCompactor.java @@ -0,0 +1,78 @@ +package junit.framework; + +public class ComparisonCompactor { + + private static final String ELLIPSIS = "..."; + private static final String DELTA_END = "]"; + private static final String DELTA_START = "["; + + private int fContextLength; + private String fExpected; + private String fActual; + private int fPrefix; + private int fSuffix; + + public ComparisonCompactor(int contextLength, String expected, String actual) { + fContextLength = contextLength; + fExpected = expected; + fActual = actual; + } + + @SuppressWarnings("deprecation") + public String compact(String message) { + if (fExpected == null || fActual == null || areStringsEqual()) { + return Assert.format(message, fExpected, fActual); + } + + findCommonPrefix(); + findCommonSuffix(); + String expected = compactString(fExpected); + String actual = compactString(fActual); + return Assert.format(message, expected, actual); + } + + private String compactString(String source) { + String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; + if (fPrefix > 0) { + result = computeCommonPrefix() + result; + } + if (fSuffix > 0) { + result = result + computeCommonSuffix(); + } + return result; + } + + private void findCommonPrefix() { + fPrefix = 0; + int end = Math.min(fExpected.length(), fActual.length()); + for (; fPrefix < end; fPrefix++) { + if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) { + break; + } + } + } + + private void findCommonSuffix() { + int expectedSuffix = fExpected.length() - 1; + int actualSuffix = fActual.length() - 1; + for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { + if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) { + break; + } + } + fSuffix = fExpected.length() - expectedSuffix; + } + + private String computeCommonPrefix() { + return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); + } + + private String computeCommonSuffix() { + int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); + return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); + } + + private boolean areStringsEqual() { + return fExpected.equals(fActual); + } +} diff --git a/src/main/java/junit/framework/ComparisonFailure.java b/src/main/java/junit/framework/ComparisonFailure.java new file mode 100644 index 000000000000..66433ef3e87b --- /dev/null +++ b/src/main/java/junit/framework/ComparisonFailure.java @@ -0,0 +1,56 @@ +package junit.framework; + +/** + * Thrown when an assert equals for Strings failed. + * + * Inspired by a patch from Alex Chaffee mailto:alex@purpletech.com + */ +public class ComparisonFailure extends AssertionFailedError { + private static final int MAX_CONTEXT_LENGTH = 20; + private static final long serialVersionUID = 1L; + + private String fExpected; + private String fActual; + + /** + * Constructs a comparison failure. + * + * @param message the identifying message or null + * @param expected the expected string value + * @param actual the actual string value + */ + public ComparisonFailure(String message, String expected, String actual) { + super(message); + fExpected = expected; + fActual = actual; + } + + /** + * Returns "..." in place of common prefix and "..." in + * place of common suffix between expected and actual. + * + * @see Throwable#getMessage() + */ + @Override + public String getMessage() { + return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); + } + + /** + * Gets the actual string value + * + * @return the actual string value + */ + public String getActual() { + return fActual; + } + + /** + * Gets the expected string value + * + * @return the expected string value + */ + public String getExpected() { + return fExpected; + } +} \ No newline at end of file diff --git a/src/main/java/junit/framework/JUnit4TestAdapter.java b/src/main/java/junit/framework/JUnit4TestAdapter.java new file mode 100644 index 000000000000..cbb66dbb064c --- /dev/null +++ b/src/main/java/junit/framework/JUnit4TestAdapter.java @@ -0,0 +1,86 @@ +package junit.framework; + +import java.util.List; + +import org.junit.Ignore; +import org.junit.runner.Describable; +import org.junit.runner.Description; +import org.junit.runner.Request; +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.runner.manipulation.Sortable; +import org.junit.runner.manipulation.Sorter; + +public class JUnit4TestAdapter implements Test, Filterable, Sortable, Describable { + private final Class fNewTestClass; + + private final Runner fRunner; + + private final JUnit4TestAdapterCache fCache; + + public JUnit4TestAdapter(Class newTestClass) { + this(newTestClass, JUnit4TestAdapterCache.getDefault()); + } + + public JUnit4TestAdapter(final Class newTestClass, JUnit4TestAdapterCache cache) { + fCache = cache; + fNewTestClass = newTestClass; + fRunner = Request.classWithoutSuiteMethod(newTestClass).getRunner(); + } + + public int countTestCases() { + return fRunner.testCount(); + } + + public void run(TestResult result) { + fRunner.run(fCache.getNotifier(result, this)); + } + + // reflective interface for Eclipse + public List getTests() { + return fCache.asTestList(getDescription()); + } + + // reflective interface for Eclipse + public Class getTestClass() { + return fNewTestClass; + } + + public Description getDescription() { + Description description = fRunner.getDescription(); + return removeIgnored(description); + } + + private Description removeIgnored(Description description) { + if (isIgnored(description)) { + return Description.EMPTY; + } + Description result = description.childlessCopy(); + for (Description each : description.getChildren()) { + Description child = removeIgnored(each); + if (!child.isEmpty()) { + result.addChild(child); + } + } + return result; + } + + private boolean isIgnored(Description description) { + return description.getAnnotation(Ignore.class) != null; + } + + @Override + public String toString() { + return fNewTestClass.getName(); + } + + public void filter(Filter filter) throws NoTestsRemainException { + filter.apply(fRunner); + } + + public void sort(Sorter sorter) { + sorter.apply(fRunner); + } +} \ No newline at end of file diff --git a/src/main/java/junit/framework/JUnit4TestAdapterCache.java b/src/main/java/junit/framework/JUnit4TestAdapterCache.java new file mode 100644 index 000000000000..603f26103309 --- /dev/null +++ b/src/main/java/junit/framework/JUnit4TestAdapterCache.java @@ -0,0 +1,77 @@ +package junit.framework; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.RunNotifier; + +public class JUnit4TestAdapterCache extends HashMap { + private static final long serialVersionUID = 1L; + private static final JUnit4TestAdapterCache fInstance = new JUnit4TestAdapterCache(); + + public static JUnit4TestAdapterCache getDefault() { + return fInstance; + } + + public Test asTest(Description description) { + if (description.isSuite()) { + return createTest(description); + } else { + if (!containsKey(description)) { + put(description, createTest(description)); + } + return get(description); + } + } + + Test createTest(Description description) { + if (description.isTest()) { + return new JUnit4TestCaseFacade(description); + } else { + TestSuite suite = new TestSuite(description.getDisplayName()); + for (Description child : description.getChildren()) { + suite.addTest(asTest(child)); + } + return suite; + } + } + + public RunNotifier getNotifier(final TestResult result, final JUnit4TestAdapter adapter) { + RunNotifier notifier = new RunNotifier(); + notifier.addListener(new RunListener() { + @Override + public void testFailure(Failure failure) throws Exception { + result.addError(asTest(failure.getDescription()), failure.getException()); + } + + @Override + public void testFinished(Description description) throws Exception { + result.endTest(asTest(description)); + } + + @Override + public void testStarted(Description description) throws Exception { + result.startTest(asTest(description)); + } + }); + return notifier; + } + + public List asTestList(Description description) { + if (description.isTest()) { + return Arrays.asList(asTest(description)); + } else { + List returnThis = new ArrayList(); + for (Description child : description.getChildren()) { + returnThis.add(asTest(child)); + } + return returnThis; + } + } + +} \ No newline at end of file diff --git a/src/main/java/junit/framework/JUnit4TestCaseFacade.java b/src/main/java/junit/framework/JUnit4TestCaseFacade.java new file mode 100644 index 000000000000..5fd8ac75206f --- /dev/null +++ b/src/main/java/junit/framework/JUnit4TestCaseFacade.java @@ -0,0 +1,30 @@ +package junit.framework; + +import org.junit.runner.Describable; +import org.junit.runner.Description; + +public class JUnit4TestCaseFacade implements Test, Describable { + private final Description fDescription; + + JUnit4TestCaseFacade(Description description) { + fDescription = description; + } + + @Override + public String toString() { + return getDescription().toString(); + } + + public int countTestCases() { + return 1; + } + + public void run(TestResult result) { + throw new RuntimeException( + "This test stub created only for informational purposes."); + } + + public Description getDescription() { + return fDescription; + } +} \ No newline at end of file diff --git a/src/main/java/junit/framework/Protectable.java b/src/main/java/junit/framework/Protectable.java new file mode 100644 index 000000000000..9f30b102da33 --- /dev/null +++ b/src/main/java/junit/framework/Protectable.java @@ -0,0 +1,14 @@ +package junit.framework; + +/** + * A Protectable can be run and can throw a Throwable. + * + * @see TestResult + */ +public interface Protectable { + + /** + * Run the the following method protected. + */ + public abstract void protect() throws Throwable; +} \ No newline at end of file diff --git a/src/main/java/junit/framework/Test.java b/src/main/java/junit/framework/Test.java new file mode 100644 index 000000000000..db95c6c7ad0e --- /dev/null +++ b/src/main/java/junit/framework/Test.java @@ -0,0 +1,18 @@ +package junit.framework; + +/** + * A Test can be run and collect its results. + * + * @see TestResult + */ +public interface Test { + /** + * Counts the number of test cases that will be run by this test. + */ + public abstract int countTestCases(); + + /** + * Runs a test and collects its result in a TestResult instance. + */ + public abstract void run(TestResult result); +} \ No newline at end of file diff --git a/src/main/java/junit/framework/TestCase.java b/src/main/java/junit/framework/TestCase.java new file mode 100644 index 000000000000..e428570c2358 --- /dev/null +++ b/src/main/java/junit/framework/TestCase.java @@ -0,0 +1,509 @@ +package junit.framework; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * A test case defines the fixture to run multiple tests. To define a test case
    + *
      + *
    1. implement a subclass of TestCase
    2. + *
    3. define instance variables that store the state of the fixture
    4. + *
    5. initialize the fixture state by overriding {@link #setUp()}
    6. + *
    7. clean-up after a test by overriding {@link #tearDown()}.
    8. + *
    + * Each test runs in its own fixture so there + * can be no side effects among test runs. + * Here is an example: + *
    + * public class MathTest extends TestCase {
    + *    protected double fValue1;
    + *    protected double fValue2;
    + *
    + *    protected void setUp() {
    + *       fValue1= 2.0;
    + *       fValue2= 3.0;
    + *    }
    + * }
    + * 
    + * + * For each test implement a method which interacts + * with the fixture. Verify the expected results with assertions specified + * by calling {@link junit.framework.Assert#assertTrue(String, boolean)} with a boolean. + *
    + *    public void testAdd() {
    + *       double result= fValue1 + fValue2;
    + *       assertTrue(result == 5.0);
    + *    }
    + * 
    + * + * Once the methods are defined you can run them. The framework supports + * both a static type safe and more dynamic way to run a test. + * In the static way you override the runTest method and define the method to + * be invoked. A convenient way to do so is with an anonymous inner class. + *
    + * TestCase test= new MathTest("add") {
    + *    public void runTest() {
    + *       testAdd();
    + *    }
    + * };
    + * test.run();
    + * 
    + * The dynamic way uses reflection to implement {@link #runTest()}. It dynamically finds + * and invokes a method. + * In this case the name of the test case has to correspond to the test method + * to be run. + *
    + * TestCase test= new MathTest("testAdd");
    + * test.run();
    + * 
    + * + * The tests to be run can be collected into a TestSuite. JUnit provides + * different test runners which can run a test suite and collect the results. + * A test runner either expects a static method suite as the entry + * point to get a test to run or it will extract the suite automatically. + *
    + * public static Test suite() {
    + *    suite.addTest(new MathTest("testAdd"));
    + *    suite.addTest(new MathTest("testDivideByZero"));
    + *    return suite;
    + * }
    + * 
    + * + * @see TestResult + * @see TestSuite + */ +@SuppressWarnings("deprecation") +public abstract class TestCase extends Assert implements Test { + /** + * the name of the test case + */ + private String fName; + + /** + * No-arg constructor to enable serialization. This method + * is not intended to be used by mere mortals without calling setName(). + */ + public TestCase() { + fName = null; + } + + /** + * Constructs a test case with the given name. + */ + public TestCase(String name) { + fName = name; + } + + /** + * Counts the number of test cases executed by run(TestResult result). + */ + public int countTestCases() { + return 1; + } + + /** + * Creates a default TestResult object + * + * @see TestResult + */ + protected TestResult createResult() { + return new TestResult(); + } + + /** + * A convenience method to run this test, collecting the results with a + * default TestResult object. + * + * @see TestResult + */ + public TestResult run() { + TestResult result = createResult(); + run(result); + return result; + } + + /** + * Runs the test case and collects the results in TestResult. + */ + public void run(TestResult result) { + result.run(this); + } + + /** + * Runs the bare test sequence. + * + * @throws Throwable if any exception is thrown + */ + public void runBare() throws Throwable { + Throwable exception = null; + setUp(); + try { + runTest(); + } catch (Throwable running) { + exception = running; + } finally { + try { + tearDown(); + } catch (Throwable tearingDown) { + if (exception == null) exception = tearingDown; + } + } + if (exception != null) throw exception; + } + + /** + * Override to run the test and assert its state. + * + * @throws Throwable if any exception is thrown + */ + protected void runTest() throws Throwable { + assertNotNull("TestCase.fName cannot be null", fName); // Some VMs crash when calling getMethod(null,null); + Method runMethod = null; + try { + // use getMethod to get all public inherited + // methods. getDeclaredMethods returns all + // methods of this class but excludes the + // inherited ones. + runMethod = getClass().getMethod(fName, (Class[]) null); + } catch (NoSuchMethodException e) { + fail("Method \"" + fName + "\" not found"); + } + if (!Modifier.isPublic(runMethod.getModifiers())) { + fail("Method \"" + fName + "\" should be public"); + } + + try { + runMethod.invoke(this); + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + throw e.getTargetException(); + } catch (IllegalAccessException e) { + e.fillInStackTrace(); + throw e; + } + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError with the given message. + */ + public static void assertTrue(String message, boolean condition) { + Assert.assertTrue(message, condition); + } + + /** + * Asserts that a condition is true. If it isn't it throws + * an AssertionFailedError. + */ + public static void assertTrue(boolean condition) { + Assert.assertTrue(condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws + * an AssertionFailedError with the given message. + */ + public static void assertFalse(String message, boolean condition) { + Assert.assertFalse(message, condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws + * an AssertionFailedError. + */ + public static void assertFalse(boolean condition) { + Assert.assertFalse(condition); + } + + /** + * Fails a test with the given message. + */ + public static void fail(String message) { + Assert.fail(message); + } + + /** + * Fails a test with no message. + */ + public static void fail() { + Assert.fail(); + } + + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, Object expected, Object actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two objects are equal. If they are not + * an AssertionFailedError is thrown. + */ + public static void assertEquals(Object expected, Object actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two Strings are equal. + */ + public static void assertEquals(String message, String expected, String actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two Strings are equal. + */ + public static void assertEquals(String expected, String actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two doubles are equal concerning a delta. If they are not + * an AssertionFailedError is thrown with the given message. If the expected + * value is infinity then the delta value is ignored. + */ + public static void assertEquals(String message, double expected, double actual, double delta) { + Assert.assertEquals(message, expected, actual, delta); + } + + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + public static void assertEquals(double expected, double actual, double delta) { + Assert.assertEquals(expected, actual, delta); + } + + /** + * Asserts that two floats are equal concerning a positive delta. If they + * are not an AssertionFailedError is thrown with the given message. If the + * expected value is infinity then the delta value is ignored. + */ + public static void assertEquals(String message, float expected, float actual, float delta) { + Assert.assertEquals(message, expected, actual, delta); + } + + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. + */ + public static void assertEquals(float expected, float actual, float delta) { + Assert.assertEquals(expected, actual, delta); + } + + /** + * Asserts that two longs are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, long expected, long actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two longs are equal. + */ + public static void assertEquals(long expected, long actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two booleans are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, boolean expected, boolean actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two booleans are equal. + */ + public static void assertEquals(boolean expected, boolean actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two bytes are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, byte expected, byte actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two bytes are equal. + */ + public static void assertEquals(byte expected, byte actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two chars are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, char expected, char actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two chars are equal. + */ + public static void assertEquals(char expected, char actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two shorts are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, short expected, short actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two shorts are equal. + */ + public static void assertEquals(short expected, short actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that two ints are equal. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertEquals(String message, int expected, int actual) { + Assert.assertEquals(message, expected, actual); + } + + /** + * Asserts that two ints are equal. + */ + public static void assertEquals(int expected, int actual) { + Assert.assertEquals(expected, actual); + } + + /** + * Asserts that an object isn't null. + */ + public static void assertNotNull(Object object) { + Assert.assertNotNull(object); + } + + /** + * Asserts that an object isn't null. If it is + * an AssertionFailedError is thrown with the given message. + */ + public static void assertNotNull(String message, Object object) { + Assert.assertNotNull(message, object); + } + + /** + * Asserts that an object is null. If it isn't an {@link AssertionError} is + * thrown. + * Message contains: Expected: but was: object + * + * @param object Object to check or null + */ + public static void assertNull(Object object) { + Assert.assertNull(object); + } + + /** + * Asserts that an object is null. If it is not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertNull(String message, Object object) { + Assert.assertNull(message, object); + } + + /** + * Asserts that two objects refer to the same object. If they are not + * an AssertionFailedError is thrown with the given message. + */ + public static void assertSame(String message, Object expected, Object actual) { + Assert.assertSame(message, expected, actual); + } + + /** + * Asserts that two objects refer to the same object. If they are not + * the same an AssertionFailedError is thrown. + */ + public static void assertSame(Object expected, Object actual) { + Assert.assertSame(expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object an AssertionFailedError is thrown with the + * given message. + */ + public static void assertNotSame(String message, Object expected, Object actual) { + Assert.assertNotSame(message, expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object an AssertionFailedError is thrown. + */ + public static void assertNotSame(Object expected, Object actual) { + Assert.assertNotSame(expected, actual); + } + + public static void failSame(String message) { + Assert.failSame(message); + } + + public static void failNotSame(String message, Object expected, Object actual) { + Assert.failNotSame(message, expected, actual); + } + + public static void failNotEquals(String message, Object expected, Object actual) { + Assert.failNotEquals(message, expected, actual); + } + + public static String format(String message, Object expected, Object actual) { + return Assert.format(message, expected, actual); + } + + /** + * Sets up the fixture, for example, open a network connection. + * This method is called before a test is executed. + */ + protected void setUp() throws Exception { + } + + /** + * Tears down the fixture, for example, close a network connection. + * This method is called after a test is executed. + */ + protected void tearDown() throws Exception { + } + + /** + * Returns a string representation of the test case + */ + @Override + public String toString() { + return getName() + "(" + getClass().getName() + ")"; + } + + /** + * Gets the name of a TestCase + * + * @return the name of the TestCase + */ + public String getName() { + return fName; + } + + /** + * Sets the name of a TestCase + * + * @param name the name to set + */ + public void setName(String name) { + fName = name; + } +} diff --git a/src/main/java/junit/framework/TestFailure.java b/src/main/java/junit/framework/TestFailure.java new file mode 100644 index 000000000000..d1ddfbc29357 --- /dev/null +++ b/src/main/java/junit/framework/TestFailure.java @@ -0,0 +1,69 @@ +package junit.framework; + +import org.junit.internal.Throwables; + + +/** + * A {@code TestFailure} collects a failed test together with + * the caught exception. + * + * @see TestResult + */ +public class TestFailure { + protected Test fFailedTest; + protected Throwable fThrownException; + + /** + * Constructs a TestFailure with the given test and exception. + */ + public TestFailure(Test failedTest, Throwable thrownException) { + fFailedTest = failedTest; + fThrownException = thrownException; + } + + /** + * Gets the failed test. + */ + public Test failedTest() { + return fFailedTest; + } + + /** + * Gets the thrown exception. + */ + public Throwable thrownException() { + return fThrownException; + } + + /** + * Returns a short description of the failure. + */ + @Override + public String toString() { + return fFailedTest + ": " + fThrownException.getMessage(); + } + + /** + * Returns a String containing the stack trace of the error + * thrown by TestFailure. + */ + public String trace() { + return Throwables.getStacktrace(thrownException()); + } + + /** + * Returns a String containing the message from the thrown exception. + */ + public String exceptionMessage() { + return thrownException().getMessage(); + } + + /** + * Returns {@code true} if the error is considered a failure + * (i.e. if it is an instance of {@code AssertionFailedError}), + * {@code false} otherwise. + */ + public boolean isFailure() { + return thrownException() instanceof AssertionFailedError; + } +} \ No newline at end of file diff --git a/src/main/java/junit/framework/TestListener.java b/src/main/java/junit/framework/TestListener.java new file mode 100644 index 000000000000..32d1a7f23180 --- /dev/null +++ b/src/main/java/junit/framework/TestListener.java @@ -0,0 +1,26 @@ +package junit.framework; + +/** + * A Listener for test progress + */ +public interface TestListener { + /** + * An error occurred. + */ + public void addError(Test test, Throwable e); + + /** + * A failure occurred. + */ + public void addFailure(Test test, AssertionFailedError e); + + /** + * A test ended. + */ + public void endTest(Test test); + + /** + * A test started. + */ + public void startTest(Test test); +} \ No newline at end of file diff --git a/src/main/java/junit/framework/TestResult.java b/src/main/java/junit/framework/TestResult.java new file mode 100644 index 000000000000..83325424b5fe --- /dev/null +++ b/src/main/java/junit/framework/TestResult.java @@ -0,0 +1,185 @@ +package junit.framework; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +/** + * A TestResult collects the results of executing + * a test case. It is an instance of the Collecting Parameter pattern. + * The test framework distinguishes between failures and errors. + * A failure is anticipated and checked for with assertions. Errors are + * unanticipated problems like an {@link ArrayIndexOutOfBoundsException}. + * + * @see Test + */ +public class TestResult { + protected List fFailures; + protected List fErrors; + protected List fListeners; + protected int fRunTests; + private boolean fStop; + + public TestResult() { + fFailures = new ArrayList(); + fErrors = new ArrayList(); + fListeners = new ArrayList(); + fRunTests = 0; + fStop = false; + } + + /** + * Adds an error to the list of errors. The passed in exception + * caused the error. + */ + public synchronized void addError(Test test, Throwable e) { + fErrors.add(new TestFailure(test, e)); + for (TestListener each : cloneListeners()) { + each.addError(test, e); + } + } + + /** + * Adds a failure to the list of failures. The passed in exception + * caused the failure. + */ + public synchronized void addFailure(Test test, AssertionFailedError e) { + fFailures.add(new TestFailure(test, e)); + for (TestListener each : cloneListeners()) { + each.addFailure(test, e); + } + } + + /** + * Registers a TestListener + */ + public synchronized void addListener(TestListener listener) { + fListeners.add(listener); + } + + /** + * Unregisters a TestListener + */ + public synchronized void removeListener(TestListener listener) { + fListeners.remove(listener); + } + + /** + * Returns a copy of the listeners. + */ + private synchronized List cloneListeners() { + List result = new ArrayList(); + result.addAll(fListeners); + return result; + } + + /** + * Informs the result that a test was completed. + */ + public void endTest(Test test) { + for (TestListener each : cloneListeners()) { + each.endTest(test); + } + } + + /** + * Gets the number of detected errors. + */ + public synchronized int errorCount() { + return fErrors.size(); + } + + /** + * Returns an Enumeration for the errors + */ + public synchronized Enumeration errors() { + return Collections.enumeration(fErrors); + } + + + /** + * Gets the number of detected failures. + */ + public synchronized int failureCount() { + return fFailures.size(); + } + + /** + * Returns an Enumeration for the failures + */ + public synchronized Enumeration failures() { + return Collections.enumeration(fFailures); + } + + /** + * Runs a TestCase. + */ + protected void run(final TestCase test) { + startTest(test); + Protectable p = new Protectable() { + public void protect() throws Throwable { + test.runBare(); + } + }; + runProtected(test, p); + + endTest(test); + } + + /** + * Gets the number of run tests. + */ + public synchronized int runCount() { + return fRunTests; + } + + /** + * Runs a TestCase. + */ + public void runProtected(final Test test, Protectable p) { + try { + p.protect(); + } catch (AssertionFailedError e) { + addFailure(test, e); + } catch (ThreadDeath e) { // don't catch ThreadDeath by accident + throw e; + } catch (Throwable e) { + addError(test, e); + } + } + + /** + * Checks whether the test run should stop + */ + public synchronized boolean shouldStop() { + return fStop; + } + + /** + * Informs the result that a test will be started. + */ + public void startTest(Test test) { + final int count = test.countTestCases(); + synchronized (this) { + fRunTests += count; + } + for (TestListener each : cloneListeners()) { + each.startTest(test); + } + } + + /** + * Marks that the test run should stop. + */ + public synchronized void stop() { + fStop = true; + } + + /** + * Returns whether the entire test was successful or not. + */ + public synchronized boolean wasSuccessful() { + return failureCount() == 0 && errorCount() == 0; + } +} diff --git a/src/main/java/junit/framework/TestSuite.java b/src/main/java/junit/framework/TestSuite.java new file mode 100644 index 000000000000..513f6455b250 --- /dev/null +++ b/src/main/java/junit/framework/TestSuite.java @@ -0,0 +1,308 @@ +package junit.framework; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Vector; + +import org.junit.internal.MethodSorter; +import org.junit.internal.Throwables; + +/** + * A TestSuite is a Composite of Tests. + * It runs a collection of test cases. Here is an example using + * the dynamic test definition. + *
    + * TestSuite suite= new TestSuite();
    + * suite.addTest(new MathTest("testAdd"));
    + * suite.addTest(new MathTest("testDivideByZero"));
    + * 
    + *

    + * Alternatively, a TestSuite can extract the tests to be run automatically. + * To do so you pass the class of your TestCase class to the + * TestSuite constructor. + *

    + * TestSuite suite= new TestSuite(MathTest.class);
    + * 
    + *

    + * This constructor creates a suite with all the methods + * starting with "test" that take no arguments. + *

    + * A final option is to do the same for a large array of test classes. + *

    + * Class[] testClasses = { MathTest.class, AnotherTest.class }
    + * TestSuite suite= new TestSuite(testClasses);
    + * 
    + * + * @see Test + */ +public class TestSuite implements Test { + + /** + * ...as the moon sets over the early morning Merlin, Oregon + * mountains, our intrepid adventurers type... + */ + static public Test createTest(Class theClass, String name) { + Constructor constructor; + try { + constructor = getTestConstructor(theClass); + } catch (NoSuchMethodException e) { + return warning("Class " + theClass.getName() + " has no public constructor TestCase(String name) or TestCase()"); + } + Object test; + try { + if (constructor.getParameterTypes().length == 0) { + test = constructor.newInstance(new Object[0]); + if (test instanceof TestCase) { + ((TestCase) test).setName(name); + } + } else { + test = constructor.newInstance(new Object[]{name}); + } + } catch (InstantiationException e) { + return (warning("Cannot instantiate test case: " + name + " (" + Throwables.getStacktrace(e) + ")")); + } catch (InvocationTargetException e) { + return (warning("Exception in constructor: " + name + " (" + Throwables.getStacktrace(e.getTargetException()) + ")")); + } catch (IllegalAccessException e) { + return (warning("Cannot access test case: " + name + " (" + Throwables.getStacktrace(e) + ")")); + } + return (Test) test; + } + + /** + * Gets a constructor which takes a single String as + * its argument or a no arg constructor. + */ + public static Constructor getTestConstructor(Class theClass) throws NoSuchMethodException { + try { + return theClass.getConstructor(String.class); + } catch (NoSuchMethodException e) { + // fall through + } + return theClass.getConstructor(); + } + + /** + * Returns a test which will fail and log a warning message. + */ + public static Test warning(final String message) { + return new TestCase("warning") { + @Override + protected void runTest() { + fail(message); + } + }; + } + + private String fName; + + private Vector fTests = new Vector(10); // Cannot convert this to List because it is used directly by some test runners + + /** + * Constructs an empty TestSuite. + */ + public TestSuite() { + } + + /** + * Constructs a TestSuite from the given class. Adds all the methods + * starting with "test" as test cases to the suite. + * Parts of this method were written at 2337 meters in the Hueffihuette, + * Kanton Uri + */ + public TestSuite(final Class theClass) { + addTestsFromTestCase(theClass); + } + + private void addTestsFromTestCase(final Class theClass) { + fName = theClass.getName(); + try { + getTestConstructor(theClass); // Avoid generating multiple error messages + } catch (NoSuchMethodException e) { + addTest(warning("Class " + theClass.getName() + " has no public constructor TestCase(String name) or TestCase()")); + return; + } + + if (!Modifier.isPublic(theClass.getModifiers())) { + addTest(warning("Class " + theClass.getName() + " is not public")); + return; + } + + Class superClass = theClass; + List names = new ArrayList(); + while (Test.class.isAssignableFrom(superClass)) { + for (Method each : MethodSorter.getDeclaredMethods(superClass)) { + addTestMethod(each, names, theClass); + } + superClass = superClass.getSuperclass(); + } + if (fTests.size() == 0) { + addTest(warning("No tests found in " + theClass.getName())); + } + } + + /** + * Constructs a TestSuite from the given class with the given name. + * + * @see TestSuite#TestSuite(Class) + */ + public TestSuite(Class theClass, String name) { + this(theClass); + setName(name); + } + + /** + * Constructs an empty TestSuite. + */ + public TestSuite(String name) { + setName(name); + } + + /** + * Constructs a TestSuite from the given array of classes. + * + * @param classes {@link TestCase}s + */ + public TestSuite(Class... classes) { + for (Class each : classes) { + addTest(testCaseForClass(each)); + } + } + + private Test testCaseForClass(Class each) { + if (TestCase.class.isAssignableFrom(each)) { + return new TestSuite(each.asSubclass(TestCase.class)); + } else { + return warning(each.getCanonicalName() + " does not extend TestCase"); + } + } + + /** + * Constructs a TestSuite from the given array of classes with the given name. + * + * @see TestSuite#TestSuite(Class[]) + */ + public TestSuite(Class[] classes, String name) { + this(classes); + setName(name); + } + + /** + * Adds a test to the suite. + */ + public void addTest(Test test) { + fTests.add(test); + } + + /** + * Adds the tests from the given class to the suite + */ + public void addTestSuite(Class testClass) { + addTest(new TestSuite(testClass)); + } + + /** + * Counts the number of test cases that will be run by this test. + */ + public int countTestCases() { + int count = 0; + for (Test each : fTests) { + count += each.countTestCases(); + } + return count; + } + + /** + * Returns the name of the suite. Not all + * test suites have a name and this method + * can return null. + */ + public String getName() { + return fName; + } + + /** + * Runs the tests and collects their result in a TestResult. + */ + public void run(TestResult result) { + for (Test each : fTests) { + if (result.shouldStop()) { + break; + } + runTest(each, result); + } + } + + public void runTest(Test test, TestResult result) { + test.run(result); + } + + /** + * Sets the name of the suite. + * + * @param name the name to set + */ + public void setName(String name) { + fName = name; + } + + /** + * Returns the test at the given index + */ + public Test testAt(int index) { + return fTests.get(index); + } + + /** + * Returns the number of tests in this suite + */ + public int testCount() { + return fTests.size(); + } + + /** + * Returns the tests as an enumeration + */ + public Enumeration tests() { + return fTests.elements(); + } + + /** + */ + @Override + public String toString() { + if (getName() != null) { + return getName(); + } + return super.toString(); + } + + private void addTestMethod(Method m, List names, Class theClass) { + String name = m.getName(); + if (names.contains(name)) { + return; + } + if (!isPublicTestMethod(m)) { + if (isTestMethod(m)) { + addTest(warning("Test method isn't public: " + m.getName() + "(" + theClass.getCanonicalName() + ")")); + } + return; + } + names.add(name); + addTest(createTest(theClass, name)); + } + + private boolean isPublicTestMethod(Method m) { + return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); + } + + private boolean isTestMethod(Method m) { + return m.getParameterTypes().length == 0 && + m.getName().startsWith("test") && + m.getReturnType().equals(Void.TYPE); + } +} diff --git a/src/main/java/junit/framework/package-info.java b/src/main/java/junit/framework/package-info.java new file mode 100644 index 000000000000..153a1c856f0b --- /dev/null +++ b/src/main/java/junit/framework/package-info.java @@ -0,0 +1,4 @@ +/** + * Provides JUnit v3.x core classes. + */ +package junit.framework; \ No newline at end of file diff --git a/src/main/java/junit/runner/BaseTestRunner.java b/src/main/java/junit/runner/BaseTestRunner.java new file mode 100644 index 000000000000..e01772d14167 --- /dev/null +++ b/src/main/java/junit/runner/BaseTestRunner.java @@ -0,0 +1,325 @@ +package junit.runner; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.text.NumberFormat; +import java.util.Properties; + +import junit.framework.AssertionFailedError; +import junit.framework.Test; +import junit.framework.TestListener; +import junit.framework.TestSuite; + +import org.junit.internal.Throwables; + +/** + * Base class for all test runners. + * This class was born live on stage in Sardinia during XP2000. + */ +public abstract class BaseTestRunner implements TestListener { + public static final String SUITE_METHODNAME = "suite"; + + private static Properties fPreferences; + static int fgMaxMessageLength = 500; + static boolean fgFilterStack = true; + boolean fLoading = true; + + /* + * Implementation of TestListener + */ + public synchronized void startTest(Test test) { + testStarted(test.toString()); + } + + protected static void setPreferences(Properties preferences) { + fPreferences = preferences; + } + + protected static Properties getPreferences() { + if (fPreferences == null) { + fPreferences = new Properties(); + fPreferences.put("loading", "true"); + fPreferences.put("filterstack", "true"); + readPreferences(); + } + return fPreferences; + } + + public static void savePreferences() throws IOException { + FileOutputStream fos = new FileOutputStream(getPreferencesFile()); + try { + getPreferences().store(fos, ""); + } finally { + fos.close(); + } + } + + public static void setPreference(String key, String value) { + getPreferences().put(key, value); + } + + public synchronized void endTest(Test test) { + testEnded(test.toString()); + } + + public synchronized void addError(final Test test, final Throwable e) { + testFailed(TestRunListener.STATUS_ERROR, test, e); + } + + public synchronized void addFailure(final Test test, final AssertionFailedError e) { + testFailed(TestRunListener.STATUS_FAILURE, test, e); + } + + // TestRunListener implementation + + public abstract void testStarted(String testName); + + public abstract void testEnded(String testName); + + public abstract void testFailed(int status, Test test, Throwable e); + + /** + * Returns the Test corresponding to the given suite. This is + * a template method, subclasses override runFailed(), clearStatus(). + */ + public Test getTest(String suiteClassName) { + if (suiteClassName.length() <= 0) { + clearStatus(); + return null; + } + Class testClass = null; + try { + testClass = loadSuiteClass(suiteClassName); + } catch (ClassNotFoundException e) { + String clazz = e.getMessage(); + if (clazz == null) { + clazz = suiteClassName; + } + runFailed("Class not found \"" + clazz + "\""); + return null; + } catch (Exception e) { + runFailed("Error: " + e.toString()); + return null; + } + Method suiteMethod = null; + try { + suiteMethod = testClass.getMethod(SUITE_METHODNAME); + } catch (Exception e) { + // try to extract a test suite automatically + clearStatus(); + return new TestSuite(testClass); + } + if (!Modifier.isStatic(suiteMethod.getModifiers())) { + runFailed("Suite() method must be static"); + return null; + } + Test test = null; + try { + test = (Test) suiteMethod.invoke(null); // static method + if (test == null) { + return test; + } + } catch (InvocationTargetException e) { + runFailed("Failed to invoke suite():" + e.getTargetException().toString()); + return null; + } catch (IllegalAccessException e) { + runFailed("Failed to invoke suite():" + e.toString()); + return null; + } + + clearStatus(); + return test; + } + + /** + * Returns the formatted string of the elapsed time. + */ + public String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } + + /** + * Processes the command line arguments and + * returns the name of the suite class to run or null + */ + protected String processArguments(String[] args) { + String suiteName = null; + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-noloading")) { + setLoading(false); + } else if (args[i].equals("-nofilterstack")) { + fgFilterStack = false; + } else if (args[i].equals("-c")) { + if (args.length > i + 1) { + suiteName = extractClassName(args[i + 1]); + } else { + System.out.println("Missing Test class name"); + } + i++; + } else { + suiteName = args[i]; + } + } + return suiteName; + } + + /** + * Sets the loading behaviour of the test runner + */ + public void setLoading(boolean enable) { + fLoading = enable; + } + + /** + * Extract the class name from a String in VA/Java style + */ + public String extractClassName(String className) { + if (className.startsWith("Default package for")) { + return className.substring(className.lastIndexOf(".") + 1); + } + return className; + } + + /** + * Truncates a String to the maximum length. + */ + public static String truncate(String s) { + if (fgMaxMessageLength != -1 && s.length() > fgMaxMessageLength) { + s = s.substring(0, fgMaxMessageLength) + "..."; + } + return s; + } + + /** + * Override to define how to handle a failed loading of + * a test suite. + */ + protected abstract void runFailed(String message); + + /** + * Returns the loaded Class for a suite name. + */ + protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { + return Class.forName(suiteClassName); + } + + /** + * Clears the status message. + */ + protected void clearStatus() { // Belongs in the GUI TestRunner class + } + + protected boolean useReloadingTestSuiteLoader() { + return getPreference("loading").equals("true") && fLoading; + } + + private static File getPreferencesFile() { + String home = System.getProperty("user.home"); + return new File(home, "junit.properties"); + } + + private static void readPreferences() { + InputStream is = null; + try { + is = new FileInputStream(getPreferencesFile()); + setPreferences(new Properties(getPreferences())); + getPreferences().load(is); + } catch (IOException ignored) { + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e1) { + } + } + } + + public static String getPreference(String key) { + return getPreferences().getProperty(key); + } + + public static int getPreference(String key, int dflt) { + String value = getPreference(key); + int intValue = dflt; + if (value == null) { + return intValue; + } + try { + intValue = Integer.parseInt(value); + } catch (NumberFormatException ne) { + } + return intValue; + } + + /** + * Returns a filtered stack trace + */ + public static String getFilteredTrace(Throwable e) { + return BaseTestRunner.getFilteredTrace(Throwables.getStacktrace(e)); + } + + /** + * Filters stack frames from internal JUnit classes + */ + public static String getFilteredTrace(String stack) { + if (showStackRaw()) { + return stack; + } + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + StringReader sr = new StringReader(stack); + BufferedReader br = new BufferedReader(sr); + + String line; + try { + while ((line = br.readLine()) != null) { + if (!filterLine(line)) { + pw.println(line); + } + } + } catch (Exception IOException) { + return stack; // return the stack unfiltered + } + return sw.toString(); + } + + protected static boolean showStackRaw() { + return !getPreference("filterstack").equals("true") || fgFilterStack == false; + } + + static boolean filterLine(String line) { + String[] patterns = new String[]{ + "junit.framework.TestCase", + "junit.framework.TestResult", + "junit.framework.TestSuite", + "junit.framework.Assert.", // don't filter AssertionFailure + "junit.swingui.TestRunner", + "junit.awtui.TestRunner", + "junit.textui.TestRunner", + "java.lang.reflect.Method.invoke(" + }; + for (int i = 0; i < patterns.length; i++) { + if (line.indexOf(patterns[i]) > 0) { + return true; + } + } + return false; + } + + static { + fgMaxMessageLength = getPreference("maxmessage", fgMaxMessageLength); + } + +} diff --git a/src/main/java/junit/runner/TestRunListener.java b/src/main/java/junit/runner/TestRunListener.java new file mode 100644 index 000000000000..b5e22f57844f --- /dev/null +++ b/src/main/java/junit/runner/TestRunListener.java @@ -0,0 +1,25 @@ +package junit.runner; + +/** + * A listener interface for observing the + * execution of a test run. Unlike TestListener, + * this interface using only primitive objects, + * making it suitable for remote test execution. + */ +public interface TestRunListener { + /* test status constants*/ + public static final int STATUS_ERROR = 1; + public static final int STATUS_FAILURE = 2; + + public void testRunStarted(String testSuiteName, int testCount); + + public void testRunEnded(long elapsedTime); + + public void testRunStopped(long elapsedTime); + + public void testStarted(String testName); + + public void testEnded(String testName); + + public void testFailed(int status, String testName, String trace); +} diff --git a/src/main/java/junit/runner/Version.java b/src/main/java/junit/runner/Version.java new file mode 100644 index 000000000000..975ef7ce07cd --- /dev/null +++ b/src/main/java/junit/runner/Version.java @@ -0,0 +1,18 @@ +package junit.runner; + +/** + * This class defines the current version of JUnit + */ +public class Version { + private Version() { + // don't instantiate + } + + public static String id() { + return "4.13-SNAPSHOT"; + } + + public static void main(String[] args) { + System.out.println(id()); + } +} diff --git a/src/main/java/junit/runner/Version.java.template b/src/main/java/junit/runner/Version.java.template new file mode 100644 index 000000000000..3182cfdff399 --- /dev/null +++ b/src/main/java/junit/runner/Version.java.template @@ -0,0 +1,18 @@ +package junit.runner; + +/** + * This class defines the current version of JUnit + */ +public class Version { + private Version() { + // don't instantiate + } + + public static String id() { + return "@version@"; + } + + public static void main(String[] args) { + System.out.println(id()); + } +} diff --git a/src/main/java/junit/runner/package-info.java b/src/main/java/junit/runner/package-info.java new file mode 100644 index 000000000000..b746185f333e --- /dev/null +++ b/src/main/java/junit/runner/package-info.java @@ -0,0 +1,4 @@ +/** + * Provides JUnit v3.x test runners. + */ +package junit.runner; \ No newline at end of file diff --git a/src/main/java/junit/textui/ResultPrinter.java b/src/main/java/junit/textui/ResultPrinter.java new file mode 100644 index 000000000000..95f10f447950 --- /dev/null +++ b/src/main/java/junit/textui/ResultPrinter.java @@ -0,0 +1,137 @@ +package junit.textui; + +import java.io.PrintStream; +import java.text.NumberFormat; +import java.util.Enumeration; + +import junit.framework.AssertionFailedError; +import junit.framework.Test; +import junit.framework.TestFailure; +import junit.framework.TestListener; +import junit.framework.TestResult; +import junit.runner.BaseTestRunner; + +public class ResultPrinter implements TestListener { + PrintStream fWriter; + int fColumn = 0; + + public ResultPrinter(PrintStream writer) { + fWriter = writer; + } + + /* API for use by textui.TestRunner */ + + synchronized void print(TestResult result, long runTime) { + printHeader(runTime); + printErrors(result); + printFailures(result); + printFooter(result); + } + + void printWaitPrompt() { + getWriter().println(); + getWriter().println(" to continue"); + } + + /* Internal methods */ + + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printErrors(TestResult result) { + printDefects(result.errors(), result.errorCount(), "error"); + } + + protected void printFailures(TestResult result) { + printDefects(result.failures(), result.failureCount(), "failure"); + } + + protected void printDefects(Enumeration booBoos, int count, String type) { + if (count == 0) return; + if (count == 1) { + getWriter().println("There was " + count + " " + type + ":"); + } else { + getWriter().println("There were " + count + " " + type + "s:"); + } + for (int i = 1; booBoos.hasMoreElements(); i++) { + printDefect(booBoos.nextElement(), i); + } + } + + public void printDefect(TestFailure booBoo, int count) { // only public for testing purposes + printDefectHeader(booBoo, count); + printDefectTrace(booBoo); + } + + protected void printDefectHeader(TestFailure booBoo, int count) { + // I feel like making this a println, then adding a line giving the throwable a chance to print something + // before we get to the stack trace. + getWriter().print(count + ") " + booBoo.failedTest()); + } + + protected void printDefectTrace(TestFailure booBoo) { + getWriter().print(BaseTestRunner.getFilteredTrace(booBoo.trace())); + } + + protected void printFooter(TestResult result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.runCount() + " test" + (result.runCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.runCount() + + ", Failures: " + result.failureCount() + + ", Errors: " + result.errorCount()); + } + getWriter().println(); + } + + /** + * Returns the formatted string of the elapsed time. + * Duplicated from BaseTestRunner. Fix it. + */ + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } + + public PrintStream getWriter() { + return fWriter; + } + + /** + * @see junit.framework.TestListener#addError(Test, Throwable) + */ + public void addError(Test test, Throwable e) { + getWriter().print("E"); + } + + /** + * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError) + */ + public void addFailure(Test test, AssertionFailedError t) { + getWriter().print("F"); + } + + /** + * @see junit.framework.TestListener#endTest(Test) + */ + public void endTest(Test test) { + } + + /** + * @see junit.framework.TestListener#startTest(Test) + */ + public void startTest(Test test) { + getWriter().print("."); + if (fColumn++ >= 40) { + getWriter().println(); + fColumn = 0; + } + } + +} diff --git a/src/main/java/junit/textui/TestRunner.java b/src/main/java/junit/textui/TestRunner.java new file mode 100644 index 000000000000..913020af6b77 --- /dev/null +++ b/src/main/java/junit/textui/TestRunner.java @@ -0,0 +1,206 @@ +package junit.textui; + + +import java.io.PrintStream; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.framework.TestSuite; +import junit.runner.BaseTestRunner; +import junit.runner.Version; + +/** + * A command line based tool to run tests. + *
    + * java junit.textui.TestRunner [-wait] TestCaseClass
    + * 
    + *

    + * TestRunner expects the name of a TestCase class as argument. + * If this class defines a static suite method it + * will be invoked and the returned test is run. Otherwise all + * the methods starting with "test" having no arguments are run. + *

    + * When the wait command line argument is given TestRunner + * waits until the users types RETURN. + *

    + * TestRunner prints a trace as the tests are executed followed by a + * summary at the end. + */ +public class TestRunner extends BaseTestRunner { + private ResultPrinter fPrinter; + + public static final int SUCCESS_EXIT = 0; + public static final int FAILURE_EXIT = 1; + public static final int EXCEPTION_EXIT = 2; + + /** + * Constructs a TestRunner. + */ + public TestRunner() { + this(System.out); + } + + /** + * Constructs a TestRunner using the given stream for all the output + */ + public TestRunner(PrintStream writer) { + this(new ResultPrinter(writer)); + } + + /** + * Constructs a TestRunner using the given ResultPrinter all the output + */ + public TestRunner(ResultPrinter printer) { + fPrinter = printer; + } + + /** + * Runs a suite extracted from a TestCase subclass. + */ + static public void run(Class testClass) { + run(new TestSuite(testClass)); + } + + /** + * Runs a single test and collects its results. + * This method can be used to start a test run + * from your program. + *

    +     * public static void main (String[] args) {
    +     *    test.textui.TestRunner.run(suite());
    +     * }
    +     * 
    + */ + static public TestResult run(Test test) { + TestRunner runner = new TestRunner(); + return runner.doRun(test); + } + + /** + * Runs a single test and waits until the user + * types RETURN. + */ + static public void runAndWait(Test suite) { + TestRunner aTestRunner = new TestRunner(); + aTestRunner.doRun(suite, true); + } + + @Override + public void testFailed(int status, Test test, Throwable e) { + } + + @Override + public void testStarted(String testName) { + } + + @Override + public void testEnded(String testName) { + } + + /** + * Creates the TestResult to be used for the test run. + */ + protected TestResult createTestResult() { + return new TestResult(); + } + + public TestResult doRun(Test test) { + return doRun(test, false); + } + + public TestResult doRun(Test suite, boolean wait) { + TestResult result = createTestResult(); + result.addListener(fPrinter); + long startTime = System.currentTimeMillis(); + suite.run(result); + long endTime = System.currentTimeMillis(); + long runTime = endTime - startTime; + fPrinter.print(result, runTime); + + pause(wait); + return result; + } + + protected void pause(boolean wait) { + if (!wait) return; + fPrinter.printWaitPrompt(); + try { + System.in.read(); + } catch (Exception e) { + } + } + + public static void main(String[] args) { + TestRunner aTestRunner = new TestRunner(); + try { + TestResult r = aTestRunner.start(args); + if (!r.wasSuccessful()) { + System.exit(FAILURE_EXIT); + } + System.exit(SUCCESS_EXIT); + } catch (Exception e) { + System.err.println(e.getMessage()); + System.exit(EXCEPTION_EXIT); + } + } + + /** + * Starts a test run. Analyzes the command line arguments and runs the given + * test suite. + */ + public TestResult start(String[] args) throws Exception { + String testCase = ""; + String method = ""; + boolean wait = false; + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-wait")) { + wait = true; + } else if (args[i].equals("-c")) { + testCase = extractClassName(args[++i]); + } else if (args[i].equals("-m")) { + String arg = args[++i]; + int lastIndex = arg.lastIndexOf('.'); + testCase = arg.substring(0, lastIndex); + method = arg.substring(lastIndex + 1); + } else if (args[i].equals("-v")) { + System.err.println("JUnit " + Version.id() + " by Kent Beck and Erich Gamma"); + } else { + testCase = args[i]; + } + } + + if (testCase.equals("")) { + throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class"); + } + + try { + if (!method.equals("")) { + return runSingleMethod(testCase, method, wait); + } + Test suite = getTest(testCase); + return doRun(suite, wait); + } catch (Exception e) { + throw new Exception("Could not create and run test suite: " + e); + } + } + + protected TestResult runSingleMethod(String testCase, String method, boolean wait) throws Exception { + Class testClass = loadSuiteClass(testCase).asSubclass(TestCase.class); + Test test = TestSuite.createTest(testClass, method); + return doRun(test, wait); + } + + @Override + protected void runFailed(String message) { + System.err.println(message); + System.exit(FAILURE_EXIT); + } + + public void setPrinter(ResultPrinter printer) { + fPrinter = printer; + } + + +} \ No newline at end of file diff --git a/src/main/java/junit/textui/package-info.java b/src/main/java/junit/textui/package-info.java new file mode 100644 index 000000000000..2aa5176db775 --- /dev/null +++ b/src/main/java/junit/textui/package-info.java @@ -0,0 +1,4 @@ +/** + * Provides JUnit v3.x command line based tool to run tests. + */ +package junit.textui; \ No newline at end of file diff --git a/src/main/java/org/junit/After.java b/src/main/java/org/junit/After.java new file mode 100644 index 000000000000..eae7e3abf4c6 --- /dev/null +++ b/src/main/java/org/junit/After.java @@ -0,0 +1,41 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * If you allocate external resources in a {@link org.junit.Before} method you need to release them + * after the test runs. Annotating a public void method + * with @After causes that method to be run after the {@link org.junit.Test} method. All @After + * methods are guaranteed to run even if a {@link org.junit.Before} or {@link org.junit.Test} method throws an + * exception. The @After methods declared in superclasses will be run after those of the current + * class, unless they are overridden in the current class. + *

    + * Here is a simple example: + *

    + * public class Example {
    + *    File output;
    + *    @Before public void createOutputFile() {
    + *          output= new File(...);
    + *    }
    + *    @Test public void something() {
    + *          ...
    + *    }
    + *    @After public void deleteOutputFile() {
    + *          output.delete();
    + *    }
    + * }
    + * 
    + * + * @see org.junit.Before + * @see org.junit.Test + * @since 4.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface After { +} + diff --git a/src/main/java/org/junit/AfterClass.java b/src/main/java/org/junit/AfterClass.java new file mode 100644 index 000000000000..dba4109ba257 --- /dev/null +++ b/src/main/java/org/junit/AfterClass.java @@ -0,0 +1,42 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * If you allocate expensive external resources in a {@link org.junit.BeforeClass} method you need to release them + * after all the tests in the class have run. Annotating a public static void method + * with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass + * methods are guaranteed to run even if a {@link org.junit.BeforeClass} method throws an + * exception. The @AfterClass methods declared in superclasses will be run after those of the current + * class, unless they are shadowed in the current class. + *

    + * Here is a simple example: + *

    + * public class Example {
    + *    private static DatabaseConnection database;
    + *    @BeforeClass public static void login() {
    + *          database= ...;
    + *    }
    + *    @Test public void something() {
    + *          ...
    + *    }
    + *    @Test public void somethingElse() {
    + *          ...
    + *    }
    + *    @AfterClass public static void logout() {
    + *          database.logout();
    + *    }
    + * }
    + * 
    + * + * @see org.junit.BeforeClass + * @see org.junit.Test + * @since 4.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface AfterClass { +} diff --git a/src/main/java/org/junit/Assert.java b/src/main/java/org/junit/Assert.java new file mode 100755 index 000000000000..af242b45fc9e --- /dev/null +++ b/src/main/java/org/junit/Assert.java @@ -0,0 +1,1012 @@ +package org.junit; + +import org.hamcrest.Matcher; +import org.hamcrest.MatcherAssert; +import org.junit.function.ThrowingRunnable; +import org.junit.internal.ArrayComparisonFailure; +import org.junit.internal.ExactComparisonCriteria; +import org.junit.internal.InexactComparisonCriteria; + +/** + * A set of assertion methods useful for writing tests. Only failed assertions + * are recorded. These methods can be used directly: + * Assert.assertEquals(...), however, they read better if they + * are referenced through static import: + * + *
    + * import static org.junit.Assert.*;
    + *    ...
    + *    assertEquals(...);
    + * 
    + * + * @see AssertionError + * @since 4.0 + */ +public class Assert { + /** + * Protect constructor since it is a static only class + */ + protected Assert() { + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * {@link AssertionError} with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param condition condition to be checked + */ + public static void assertTrue(String message, boolean condition) { + if (!condition) { + fail(message); + } + } + + /** + * Asserts that a condition is true. If it isn't it throws an + * {@link AssertionError} without a message. + * + * @param condition condition to be checked + */ + public static void assertTrue(boolean condition) { + assertTrue(null, condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * {@link AssertionError} with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param condition condition to be checked + */ + public static void assertFalse(String message, boolean condition) { + assertTrue(message, !condition); + } + + /** + * Asserts that a condition is false. If it isn't it throws an + * {@link AssertionError} without a message. + * + * @param condition condition to be checked + */ + public static void assertFalse(boolean condition) { + assertFalse(null, condition); + } + + /** + * Fails a test with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @see AssertionError + */ + public static void fail(String message) { + if (message == null) { + throw new AssertionError(); + } + throw new AssertionError(message); + } + + /** + * Fails a test with no message. + */ + public static void fail() { + fail(null); + } + + /** + * Asserts that two objects are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. If + * expected and actual are null, + * they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expected expected value + * @param actual actual value + */ + public static void assertEquals(String message, Object expected, + Object actual) { + if (equalsRegardingNull(expected, actual)) { + return; + } + if (expected instanceof String && actual instanceof String) { + String cleanMessage = message == null ? "" : message; + throw new ComparisonFailure(cleanMessage, (String) expected, + (String) actual); + } else { + failNotEquals(message, expected, actual); + } + } + + private static boolean equalsRegardingNull(Object expected, Object actual) { + if (expected == null) { + return actual == null; + } + + return isEquals(expected, actual); + } + + private static boolean isEquals(Object expected, Object actual) { + return expected.equals(actual); + } + + /** + * Asserts that two objects are equal. If they are not, an + * {@link AssertionError} without a message is thrown. If + * expected and actual are null, + * they are considered equal. + * + * @param expected expected value + * @param actual the value to check against expected + */ + public static void assertEquals(Object expected, Object actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two objects are not equals. If they are, an + * {@link AssertionError} is thrown with the given message. If + * unexpected and actual are null, + * they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param unexpected unexpected value to check + * @param actual the value to check against unexpected + */ + public static void assertNotEquals(String message, Object unexpected, + Object actual) { + if (equalsRegardingNull(unexpected, actual)) { + failEquals(message, actual); + } + } + + /** + * Asserts that two objects are not equals. If they are, an + * {@link AssertionError} without a message is thrown. If + * unexpected and actual are null, + * they are considered equal. + * + * @param unexpected unexpected value to check + * @param actual the value to check against unexpected + */ + public static void assertNotEquals(Object unexpected, Object actual) { + assertNotEquals(null, unexpected, actual); + } + + private static void failEquals(String message, Object actual) { + String formatted = "Values should be different. "; + if (message != null) { + formatted = message + ". "; + } + + formatted += "Actual: " + actual; + fail(formatted); + } + + /** + * Asserts that two longs are not equals. If they are, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param unexpected unexpected value to check + * @param actual the value to check against unexpected + */ + public static void assertNotEquals(String message, long unexpected, long actual) { + if (unexpected == actual) { + failEquals(message, Long.valueOf(actual)); + } + } + + /** + * Asserts that two longs are not equals. If they are, an + * {@link AssertionError} without a message is thrown. + * + * @param unexpected unexpected value to check + * @param actual the value to check against unexpected + */ + public static void assertNotEquals(long unexpected, long actual) { + assertNotEquals(null, unexpected, actual); + } + + /** + * Asserts that two doubles are not equal to within a positive delta. + * If they are, an {@link AssertionError} is thrown with the given + * message. If the unexpected value is infinity then the delta value is + * ignored. NaNs are considered equal: + * assertNotEquals(Double.NaN, Double.NaN, *) fails + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param unexpected unexpected value + * @param actual the value to check against unexpected + * @param delta the maximum delta between unexpected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertNotEquals(String message, double unexpected, + double actual, double delta) { + if (!doubleIsDifferent(unexpected, actual, delta)) { + failEquals(message, Double.valueOf(actual)); + } + } + + /** + * Asserts that two doubles are not equal to within a positive delta. + * If they are, an {@link AssertionError} is thrown. If the unexpected + * value is infinity then the delta value is ignored.NaNs are considered + * equal: assertNotEquals(Double.NaN, Double.NaN, *) fails + * + * @param unexpected unexpected value + * @param actual the value to check against unexpected + * @param delta the maximum delta between unexpected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertNotEquals(double unexpected, double actual, double delta) { + assertNotEquals(null, unexpected, actual, delta); + } + + /** + * Asserts that two floats are not equal to within a positive delta. + * If they are, an {@link AssertionError} is thrown. If the unexpected + * value is infinity then the delta value is ignored.NaNs are considered + * equal: assertNotEquals(Float.NaN, Float.NaN, *) fails + * + * @param unexpected unexpected value + * @param actual the value to check against unexpected + * @param delta the maximum delta between unexpected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertNotEquals(float unexpected, float actual, float delta) { + assertNotEquals(null, unexpected, actual, delta); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. If + * expecteds and actuals are null, + * they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds Object array or array of arrays (multi-dimensional array) with + * expected values. + * @param actuals Object array or array of arrays (multi-dimensional array) with + * actual values + */ + public static void assertArrayEquals(String message, Object[] expecteds, + Object[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * {@link AssertionError} is thrown. If expected and + * actual are null, they are considered + * equal. + * + * @param expecteds Object array or array of arrays (multi-dimensional array) with + * expected values + * @param actuals Object array or array of arrays (multi-dimensional array) with + * actual values + */ + public static void assertArrayEquals(Object[] expecteds, Object[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two boolean arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. If + * expecteds and actuals are null, + * they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds boolean array with expected values. + * @param actuals boolean array with expected values. + */ + public static void assertArrayEquals(String message, boolean[] expecteds, + boolean[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two boolean arrays are equal. If they are not, an + * {@link AssertionError} is thrown. If expected and + * actual are null, they are considered + * equal. + * + * @param expecteds boolean array with expected values. + * @param actuals boolean array with expected values. + */ + public static void assertArrayEquals(boolean[] expecteds, boolean[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two byte arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds byte array with expected values. + * @param actuals byte array with actual values + */ + public static void assertArrayEquals(String message, byte[] expecteds, + byte[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two byte arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds byte array with expected values. + * @param actuals byte array with actual values + */ + public static void assertArrayEquals(byte[] expecteds, byte[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two char arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds char array with expected values. + * @param actuals char array with actual values + */ + public static void assertArrayEquals(String message, char[] expecteds, + char[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two char arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds char array with expected values. + * @param actuals char array with actual values + */ + public static void assertArrayEquals(char[] expecteds, char[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two short arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds short array with expected values. + * @param actuals short array with actual values + */ + public static void assertArrayEquals(String message, short[] expecteds, + short[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two short arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds short array with expected values. + * @param actuals short array with actual values + */ + public static void assertArrayEquals(short[] expecteds, short[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two int arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds int array with expected values. + * @param actuals int array with actual values + */ + public static void assertArrayEquals(String message, int[] expecteds, + int[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two int arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds int array with expected values. + * @param actuals int array with actual values + */ + public static void assertArrayEquals(int[] expecteds, int[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two long arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds long array with expected values. + * @param actuals long array with actual values + */ + public static void assertArrayEquals(String message, long[] expecteds, + long[] actuals) throws ArrayComparisonFailure { + internalArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two long arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds long array with expected values. + * @param actuals long array with actual values + */ + public static void assertArrayEquals(long[] expecteds, long[] actuals) { + assertArrayEquals(null, expecteds, actuals); + } + + /** + * Asserts that two double arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds double array with expected values. + * @param actuals double array with actual values + * @param delta the maximum delta between expecteds[i] and + * actuals[i] for which both numbers are still + * considered equal. + */ + public static void assertArrayEquals(String message, double[] expecteds, + double[] actuals, double delta) throws ArrayComparisonFailure { + new InexactComparisonCriteria(delta).arrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two double arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds double array with expected values. + * @param actuals double array with actual values + * @param delta the maximum delta between expecteds[i] and + * actuals[i] for which both numbers are still + * considered equal. + */ + public static void assertArrayEquals(double[] expecteds, double[] actuals, double delta) { + assertArrayEquals(null, expecteds, actuals, delta); + } + + /** + * Asserts that two float arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds float array with expected values. + * @param actuals float array with actual values + * @param delta the maximum delta between expecteds[i] and + * actuals[i] for which both numbers are still + * considered equal. + */ + public static void assertArrayEquals(String message, float[] expecteds, + float[] actuals, float delta) throws ArrayComparisonFailure { + new InexactComparisonCriteria(delta).arrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two float arrays are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expecteds float array with expected values. + * @param actuals float array with actual values + * @param delta the maximum delta between expecteds[i] and + * actuals[i] for which both numbers are still + * considered equal. + */ + public static void assertArrayEquals(float[] expecteds, float[] actuals, float delta) { + assertArrayEquals(null, expecteds, actuals, delta); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. If + * expecteds and actuals are null, + * they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds Object array or array of arrays (multi-dimensional array) with + * expected values. + * @param actuals Object array or array of arrays (multi-dimensional array) with + * actual values + */ + private static void internalArrayEquals(String message, Object expecteds, + Object actuals) throws ArrayComparisonFailure { + new ExactComparisonCriteria().arrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two doubles are equal to within a positive delta. + * If they are not, an {@link AssertionError} is thrown with the given + * message. If the expected value is infinity then the delta value is + * ignored. NaNs are considered equal: + * assertEquals(Double.NaN, Double.NaN, *) passes + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expected expected value + * @param actual the value to check against expected + * @param delta the maximum delta between expected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertEquals(String message, double expected, + double actual, double delta) { + if (doubleIsDifferent(expected, actual, delta)) { + failNotEquals(message, Double.valueOf(expected), Double.valueOf(actual)); + } + } + + /** + * Asserts that two floats are equal to within a positive delta. + * If they are not, an {@link AssertionError} is thrown with the given + * message. If the expected value is infinity then the delta value is + * ignored. NaNs are considered equal: + * assertEquals(Float.NaN, Float.NaN, *) passes + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expected expected value + * @param actual the value to check against expected + * @param delta the maximum delta between expected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertEquals(String message, float expected, + float actual, float delta) { + if (floatIsDifferent(expected, actual, delta)) { + failNotEquals(message, Float.valueOf(expected), Float.valueOf(actual)); + } + } + + /** + * Asserts that two floats are not equal to within a positive delta. + * If they are, an {@link AssertionError} is thrown with the given + * message. If the unexpected value is infinity then the delta value is + * ignored. NaNs are considered equal: + * assertNotEquals(Float.NaN, Float.NaN, *) fails + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param unexpected unexpected value + * @param actual the value to check against unexpected + * @param delta the maximum delta between unexpected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertNotEquals(String message, float unexpected, + float actual, float delta) { + if (!floatIsDifferent(unexpected, actual, delta)) { + failEquals(message, actual); + } + } + + private static boolean doubleIsDifferent(double d1, double d2, double delta) { + if (Double.compare(d1, d2) == 0) { + return false; + } + if ((Math.abs(d1 - d2) <= delta)) { + return false; + } + + return true; + } + + private static boolean floatIsDifferent(float f1, float f2, float delta) { + if (Float.compare(f1, f2) == 0) { + return false; + } + if ((Math.abs(f1 - f2) <= delta)) { + return false; + } + + return true; + } + + /** + * Asserts that two longs are equal. If they are not, an + * {@link AssertionError} is thrown. + * + * @param expected expected long value. + * @param actual actual long value + */ + public static void assertEquals(long expected, long actual) { + assertEquals(null, expected, actual); + } + + /** + * Asserts that two longs are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expected long expected value. + * @param actual long actual value + */ + public static void assertEquals(String message, long expected, long actual) { + if (expected != actual) { + failNotEquals(message, Long.valueOf(expected), Long.valueOf(actual)); + } + } + + /** + * @deprecated Use + * assertEquals(double expected, double actual, double delta) + * instead + */ + @Deprecated + public static void assertEquals(double expected, double actual) { + assertEquals(null, expected, actual); + } + + /** + * @deprecated Use + * assertEquals(String message, double expected, double actual, double delta) + * instead + */ + @Deprecated + public static void assertEquals(String message, double expected, + double actual) { + fail("Use assertEquals(expected, actual, delta) to compare floating-point numbers"); + } + + /** + * Asserts that two doubles are equal to within a positive delta. + * If they are not, an {@link AssertionError} is thrown. If the expected + * value is infinity then the delta value is ignored.NaNs are considered + * equal: assertEquals(Double.NaN, Double.NaN, *) passes + * + * @param expected expected value + * @param actual the value to check against expected + * @param delta the maximum delta between expected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertEquals(double expected, double actual, double delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that two floats are equal to within a positive delta. + * If they are not, an {@link AssertionError} is thrown. If the expected + * value is infinity then the delta value is ignored. NaNs are considered + * equal: assertEquals(Float.NaN, Float.NaN, *) passes + * + * @param expected expected value + * @param actual the value to check against expected + * @param delta the maximum delta between expected and + * actual for which both numbers are still + * considered equal. + */ + public static void assertEquals(float expected, float actual, float delta) { + assertEquals(null, expected, actual, delta); + } + + /** + * Asserts that an object isn't null. If it is an {@link AssertionError} is + * thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param object Object to check or null + */ + public static void assertNotNull(String message, Object object) { + assertTrue(message, object != null); + } + + /** + * Asserts that an object isn't null. If it is an {@link AssertionError} is + * thrown. + * + * @param object Object to check or null + */ + public static void assertNotNull(Object object) { + assertNotNull(null, object); + } + + /** + * Asserts that an object is null. If it is not, an {@link AssertionError} + * is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param object Object to check or null + */ + public static void assertNull(String message, Object object) { + if (object == null) { + return; + } + failNotNull(message, object); + } + + /** + * Asserts that an object is null. If it isn't an {@link AssertionError} is + * thrown. + * + * @param object Object to check or null + */ + public static void assertNull(Object object) { + assertNull(null, object); + } + + private static void failNotNull(String message, Object actual) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + fail(formatted + "expected null, but was:<" + actual + ">"); + } + + /** + * Asserts that two objects refer to the same object. If they are not, an + * {@link AssertionError} is thrown with the given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expected the expected object + * @param actual the object to compare to expected + */ + public static void assertSame(String message, Object expected, Object actual) { + if (expected == actual) { + return; + } + failNotSame(message, expected, actual); + } + + /** + * Asserts that two objects refer to the same object. If they are not the + * same, an {@link AssertionError} without a message is thrown. + * + * @param expected the expected object + * @param actual the object to compare to expected + */ + public static void assertSame(Object expected, Object actual) { + assertSame(null, expected, actual); + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an {@link AssertionError} is thrown with the + * given message. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param unexpected the object you don't expect + * @param actual the object to compare to unexpected + */ + public static void assertNotSame(String message, Object unexpected, + Object actual) { + if (unexpected == actual) { + failSame(message); + } + } + + /** + * Asserts that two objects do not refer to the same object. If they do + * refer to the same object, an {@link AssertionError} without a message is + * thrown. + * + * @param unexpected the object you don't expect + * @param actual the object to compare to unexpected + */ + public static void assertNotSame(Object unexpected, Object actual) { + assertNotSame(null, unexpected, actual); + } + + private static void failSame(String message) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + fail(formatted + "expected not same"); + } + + private static void failNotSame(String message, Object expected, + Object actual) { + String formatted = ""; + if (message != null) { + formatted = message + " "; + } + fail(formatted + "expected same:<" + expected + "> was not:<" + actual + + ">"); + } + + private static void failNotEquals(String message, Object expected, + Object actual) { + fail(format(message, expected, actual)); + } + + static String format(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null && !"".equals(message)) { + formatted = message + " "; + } + String expectedString = String.valueOf(expected); + String actualString = String.valueOf(actual); + if (expectedString.equals(actualString)) { + return formatted + "expected: " + + formatClassAndValue(expected, expectedString) + + " but was: " + formatClassAndValue(actual, actualString); + } else { + return formatted + "expected:<" + expectedString + "> but was:<" + + actualString + ">"; + } + } + + private static String formatClassAndValue(Object value, String valueString) { + String className = value == null ? "null" : value.getClass().getName(); + return className + "<" + valueString + ">"; + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * {@link AssertionError} is thrown with the given message. If + * expecteds and actuals are null, + * they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} (null + * okay) + * @param expecteds Object array or array of arrays (multi-dimensional array) with + * expected values. + * @param actuals Object array or array of arrays (multi-dimensional array) with + * actual values + * @deprecated use assertArrayEquals + */ + @Deprecated + public static void assertEquals(String message, Object[] expecteds, + Object[] actuals) { + assertArrayEquals(message, expecteds, actuals); + } + + /** + * Asserts that two object arrays are equal. If they are not, an + * {@link AssertionError} is thrown. If expected and + * actual are null, they are considered + * equal. + * + * @param expecteds Object array or array of arrays (multi-dimensional array) with + * expected values + * @param actuals Object array or array of arrays (multi-dimensional array) with + * actual values + * @deprecated use assertArrayEquals + */ + @Deprecated + public static void assertEquals(Object[] expecteds, Object[] actuals) { + assertArrayEquals(expecteds, actuals); + } + + /** + * Asserts that actual satisfies the condition specified by + * matcher. If not, an {@link AssertionError} is thrown with + * information about the matcher and failing value. Example: + * + *
    +     *   assertThat(0, is(1)); // fails:
    +     *     // failure message:
    +     *     // expected: is <1>
    +     *     // got value: <0>
    +     *   assertThat(0, is(not(1))) // passes
    +     * 
    + * + * org.hamcrest.Matcher does not currently document the meaning + * of its type parameter T. This method assumes that a matcher + * typed as Matcher<T> can be meaningfully applied only + * to values that could be assigned to a variable of type T. + * + * @param the static type accepted by the matcher (this can flag obvious + * compile-time problems such as {@code assertThat(1, is("a"))} + * @param actual the computed value being compared + * @param matcher an expression, built of {@link Matcher}s, specifying allowed + * values + * @see org.hamcrest.CoreMatchers + * @see org.hamcrest.MatcherAssert + * @deprecated use {@code org.hamcrest.junit.MatcherAssert.assertThat()} + */ + @Deprecated + public static void assertThat(T actual, Matcher matcher) { + assertThat("", actual, matcher); + } + + /** + * Asserts that actual satisfies the condition specified by + * matcher. If not, an {@link AssertionError} is thrown with + * the reason and information about the matcher and failing value. Example: + * + *
    +     *   assertThat("Help! Integers don't work", 0, is(1)); // fails:
    +     *     // failure message:
    +     *     // Help! Integers don't work
    +     *     // expected: is <1>
    +     *     // got value: <0>
    +     *   assertThat("Zero is one", 0, is(not(1))) // passes
    +     * 
    + * + * org.hamcrest.Matcher does not currently document the meaning + * of its type parameter T. This method assumes that a matcher + * typed as Matcher<T> can be meaningfully applied only + * to values that could be assigned to a variable of type T. + * + * @param reason additional information about the error + * @param the static type accepted by the matcher (this can flag obvious + * compile-time problems such as {@code assertThat(1, is("a"))} + * @param actual the computed value being compared + * @param matcher an expression, built of {@link Matcher}s, specifying allowed + * values + * @see org.hamcrest.CoreMatchers + * @see org.hamcrest.MatcherAssert + * @deprecated use {@code org.hamcrest.junit.MatcherAssert.assertThat()} + */ + @Deprecated + public static void assertThat(String reason, T actual, + Matcher matcher) { + MatcherAssert.assertThat(reason, actual, matcher); + } + + /** + * Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when + * executed. If it does not throw an exception, an {@link AssertionError} is thrown. If it + * throws the wrong type of exception, an {@code AssertionError} is thrown describing the + * mismatch; the exception that was actually thrown can be obtained by calling {@link + * AssertionError#getCause}. + * + * @param expectedThrowable the expected type of the exception + * @param runnable a function that is expected to throw an exception when executed + * @since 4.13 + */ + public static void assertThrows(Class expectedThrowable, ThrowingRunnable runnable) { + expectThrows(expectedThrowable, runnable); + } + + /** + * Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when + * executed. If it does, the exception object is returned. If it does not throw an exception, an + * {@link AssertionError} is thrown. If it throws the wrong type of exception, an {@code + * AssertionError} is thrown describing the mismatch; the exception that was actually thrown can + * be obtained by calling {@link AssertionError#getCause}. + * + * @param expectedThrowable the expected type of the exception + * @param runnable a function that is expected to throw an exception when executed + * @return the exception thrown by {@code runnable} + * @since 4.13 + */ + public static T expectThrows(Class expectedThrowable, ThrowingRunnable runnable) { + try { + runnable.run(); + } catch (Throwable actualThrown) { + if (expectedThrowable.isInstance(actualThrown)) { + @SuppressWarnings("unchecked") T retVal = (T) actualThrown; + return retVal; + } else { + String mismatchMessage = format("unexpected exception type thrown;", + expectedThrowable.getSimpleName(), actualThrown.getClass().getSimpleName()); + + // The AssertionError(String, Throwable) ctor is only available on JDK7. + AssertionError assertionError = new AssertionError(mismatchMessage); + assertionError.initCause(actualThrown); + throw assertionError; + } + } + String message = String.format("expected %s to be thrown, but nothing was thrown", + expectedThrowable.getSimpleName()); + throw new AssertionError(message); + } +} diff --git a/src/main/java/org/junit/Assume.java b/src/main/java/org/junit/Assume.java new file mode 100644 index 000000000000..86bca34aa16a --- /dev/null +++ b/src/main/java/org/junit/Assume.java @@ -0,0 +1,171 @@ +package org.junit; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.everyItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; + +import org.hamcrest.Matcher; + +/** + * A set of methods useful for stating assumptions about the conditions in which a test is meaningful. + * A failed assumption does not mean the code is broken, but that the test provides no useful information. Assume + * basically means "don't run this test if these conditions don't apply". The default JUnit runner skips tests with + * failing assumptions. Custom runners may behave differently. + *

    + * A good example of using assumptions is in Theories where they are needed to exclude certain datapoints that aren't suitable or allowed for a certain test case. + *

    + * Failed assumptions are usually not logged, because there may be many tests that don't apply to certain + * configurations. + * + *

    + * These methods can be used directly: Assume.assumeTrue(...), however, they + * read better if they are referenced through static import:
    + *

    + * import static org.junit.Assume.*;
    + *    ...
    + *    assumeTrue(...);
    + * 
    + *

    + * + * @see Theories + * + * @since 4.4 + */ +public class Assume { + + /** + * Do not instantiate. + * @deprecated since 4.13. + */ + @Deprecated + public Assume() { + } + + /** + * If called with an expression evaluating to {@code false}, the test will halt and be ignored. + */ + public static void assumeTrue(boolean b) { + assumeThat(b, is(true)); + } + + /** + * The inverse of {@link #assumeTrue(boolean)}. + */ + public static void assumeFalse(boolean b) { + assumeTrue(!b); + } + + /** + * If called with an expression evaluating to {@code false}, the test will halt and be ignored. + * + * @param b If false, the method will attempt to stop the test and ignore it by + * throwing {@link AssumptionViolatedException}. + * @param message A message to pass to {@link AssumptionViolatedException}. + */ + public static void assumeTrue(String message, boolean b) { + if (!b) throw new AssumptionViolatedException(message); + } + + /** + * The inverse of {@link #assumeTrue(String, boolean)}. + */ + public static void assumeFalse(String message, boolean b) { + assumeTrue(message, !b); + } + + /** + * If called with one or more null elements in objects, the test will halt and be ignored. + */ + public static void assumeNotNull(Object... objects) { + assumeThat(asList(objects), everyItem(notNullValue())); + } + + /** + * Call to assume that actual satisfies the condition specified by matcher. + * If not, the test halts and is ignored. + * Example: + *
    :
    +     *   assumeThat(1, is(1)); // passes
    +     *   foo(); // will execute
    +     *   assumeThat(0, is(1)); // assumption failure! test halts
    +     *   int x = 1 / 0; // will never execute
    +     * 
    + * + * @param the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} + * @param actual the computed value being compared + * @param matcher an expression, built of {@link Matcher}s, specifying allowed values + * @see org.hamcrest.CoreMatchers + * @see org.junit.matchers.JUnitMatchers + * @deprecated use {@code org.hamcrest.junit.MatcherAssume.assumeThat()} + */ + @Deprecated + public static void assumeThat(T actual, Matcher matcher) { + if (!matcher.matches(actual)) { + throw new AssumptionViolatedException(actual, matcher); + } + } + + /** + * Call to assume that actual satisfies the condition specified by matcher. + * If not, the test halts and is ignored. + * Example: + *
    :
    +     *   assumeThat("alwaysPasses", 1, is(1)); // passes
    +     *   foo(); // will execute
    +     *   assumeThat("alwaysFails", 0, is(1)); // assumption failure! test halts
    +     *   int x = 1 / 0; // will never execute
    +     * 
    + * + * @param the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} + * @param actual the computed value being compared + * @param matcher an expression, built of {@link Matcher}s, specifying allowed values + * @see org.hamcrest.CoreMatchers + * @see org.junit.matchers.JUnitMatchers + * @deprecated use {@code org.hamcrest.junit.MatcherAssume.assumeThat()} + */ + @Deprecated + public static void assumeThat(String message, T actual, Matcher matcher) { + if (!matcher.matches(actual)) { + throw new AssumptionViolatedException(message, actual, matcher); + } + } + + /** + * Use to assume that an operation completes normally. If {@code e} is non-null, the test will halt and be ignored. + * + * For example: + *
    +     * \@Test public void parseDataFile() {
    +     *   DataFile file;
    +     *   try {
    +     *     file = DataFile.open("sampledata.txt");
    +     *   } catch (IOException e) {
    +     *     // stop test and ignore if data can't be opened
    +     *     assumeNoException(e);
    +     *   }
    +     *   // ...
    +     * }
    +     * 
    + * + * @param e if non-null, the offending exception + */ + public static void assumeNoException(Throwable e) { + assumeThat(e, nullValue()); + } + + /** + * Attempts to halt the test and ignore it if Throwable e is + * not null. Similar to {@link #assumeNoException(Throwable)}, + * but provides an additional message that can explain the details + * concerning the assumption. + * + * @param e if non-null, the offending exception + * @param message Additional message to pass to {@link AssumptionViolatedException}. + * @see #assumeNoException(Throwable) + */ + public static void assumeNoException(String message, Throwable e) { + assumeThat(message, e, nullValue()); + } +} diff --git a/src/main/java/org/junit/AssumptionViolatedException.java b/src/main/java/org/junit/AssumptionViolatedException.java new file mode 100644 index 000000000000..38b703d1f49f --- /dev/null +++ b/src/main/java/org/junit/AssumptionViolatedException.java @@ -0,0 +1,48 @@ +package org.junit; + +import org.hamcrest.Matcher; + +/** + * An exception class used to implement assumptions (state in which a given test + * is meaningful and should or should not be executed). A test for which an assumption + * fails should not generate a test case failure. + * + * @see org.junit.Assume + * @since 4.12 + */ +@SuppressWarnings("deprecation") +public class AssumptionViolatedException extends org.junit.internal.AssumptionViolatedException { + private static final long serialVersionUID = 1L; + + /** + * An assumption exception with the given actual value and a matcher describing + * the expectation that failed. + */ + @Deprecated + public AssumptionViolatedException(T actual, Matcher matcher) { + super(actual, matcher); + } + + /** + * An assumption exception with a message with the given actual value and a + * matcher describing the expectation that failed. + */ + @Deprecated + public AssumptionViolatedException(String message, T expected, Matcher matcher) { + super(message, expected, matcher); + } + + /** + * An assumption exception with the given message only. + */ + public AssumptionViolatedException(String message) { + super(message); + } + + /** + * An assumption exception with the given message and a cause. + */ + public AssumptionViolatedException(String assumption, Throwable t) { + super(assumption, t); + } +} diff --git a/src/main/java/org/junit/Before.java b/src/main/java/org/junit/Before.java new file mode 100644 index 000000000000..def8adb47ad6 --- /dev/null +++ b/src/main/java/org/junit/Before.java @@ -0,0 +1,39 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * When writing tests, it is common to find that several tests need similar + * objects created before they can run. Annotating a public void method + * with @Before causes that method to be run before the {@link org.junit.Test} method. + * The @Before methods of superclasses will be run before those of the current class, + * unless they are overridden in the current class. No other ordering is defined. + *

    + * Here is a simple example: + *

    + * public class Example {
    + *    List empty;
    + *    @Before public void initialize() {
    + *       empty= new ArrayList();
    + *    }
    + *    @Test public void size() {
    + *       ...
    + *    }
    + *    @Test public void remove() {
    + *       ...
    + *    }
    + * }
    + * 
    + * + * @see org.junit.BeforeClass + * @see org.junit.After + * @since 4.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Before { +} + diff --git a/src/main/java/org/junit/BeforeClass.java b/src/main/java/org/junit/BeforeClass.java new file mode 100644 index 000000000000..8183fa0f0a14 --- /dev/null +++ b/src/main/java/org/junit/BeforeClass.java @@ -0,0 +1,37 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Sometimes several tests need to share computationally expensive setup + * (like logging into a database). While this can compromise the independence of + * tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method + * with @BeforeClass causes it to be run once before any of + * the test methods in the class. The @BeforeClass methods of superclasses + * will be run before those of the current class, unless they are shadowed in the current class. + *

    + * For example: + *

    + * public class Example {
    + *    @BeforeClass public static void onlyOnce() {
    + *       ...
    + *    }
    + *    @Test public void one() {
    + *       ...
    + *    }
    + *    @Test public void two() {
    + *       ...
    + *    }
    + * }
    + * 
    + * + * @see org.junit.AfterClass + * @since 4.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface BeforeClass { +} diff --git a/src/main/java/org/junit/ClassRule.java b/src/main/java/org/junit/ClassRule.java new file mode 100644 index 000000000000..02c40a713fce --- /dev/null +++ b/src/main/java/org/junit/ClassRule.java @@ -0,0 +1,87 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotates static fields that reference rules or methods that return them. A field must be public, + * static, and a subtype of {@link org.junit.rules.TestRule}. A method must be public static, and return + * a subtype of {@link org.junit.rules.TestRule}. + *

    + * The {@link org.junit.runners.model.Statement} passed + * to the {@link org.junit.rules.TestRule} will run any {@link BeforeClass} methods, + * then the entire body of the test class (all contained methods, if it is + * a standard JUnit test class, or all contained classes, if it is a + * {@link org.junit.runners.Suite}), and finally any {@link AfterClass} methods. + *

    + * The statement passed to the {@link org.junit.rules.TestRule} will never throw an exception, + * and throwing an exception from the {@link org.junit.rules.TestRule} will result in undefined + * behavior. This means that some {@link org.junit.rules.TestRule}s, such as + * {@link org.junit.rules.ErrorCollector}, + * {@link org.junit.rules.ExpectedException}, + * and {@link org.junit.rules.Timeout}, + * have undefined behavior when used as {@link ClassRule}s. + *

    + * If there are multiple + * annotated {@link ClassRule}s on a class, they will be applied in an order + * that depends on your JVM's implementation of the reflection API, which is + * undefined, in general. However, Rules defined by fields will always be applied + * before Rules defined by methods. + *

    + * For example, here is a test suite that connects to a server once before + * all the test classes run, and disconnects after they are finished: + *

    + * @RunWith(Suite.class)
    + * @SuiteClasses({A.class, B.class, C.class})
    + * public class UsesExternalResource {
    + *     public static Server myServer= new Server();
    + *
    + *     @ClassRule
    + *     public static ExternalResource resource= new ExternalResource() {
    + *       @Override
    + *       protected void before() throws Throwable {
    + *          myServer.connect();
    + *      }
    + *
    + *      @Override
    + *      protected void after() {
    + * 	        myServer.disconnect();
    + *      }
    + *   };
    + * }
    + * 
    + *

    + * and the same using a method + *

    + * @RunWith(Suite.class)
    + * @SuiteClasses({A.class, B.class, C.class})
    + * public class UsesExternalResource {
    + *     public static Server myServer= new Server();
    + *
    + *     @ClassRule
    + *     public static ExternalResource getResource() {
    + *         return new ExternalResource() {
    + *             @Override
    + *             protected void before() throws Throwable {
    + *                 myServer.connect();
    + *             }
    + *
    + *             @Override
    + *             protected void after() {
    + *                 myServer.disconnect();
    + *             }
    + *         };
    + *     }
    + * }
    + * 
    + *

    + * For more information and more examples, see {@link org.junit.rules.TestRule}. + * + * @since 4.9 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD}) +public @interface ClassRule { +} diff --git a/src/main/java/org/junit/ComparisonFailure.java b/src/main/java/org/junit/ComparisonFailure.java new file mode 100644 index 000000000000..d1daa863c3f3 --- /dev/null +++ b/src/main/java/org/junit/ComparisonFailure.java @@ -0,0 +1,171 @@ +package org.junit; + +/** + * Thrown when an {@link org.junit.Assert#assertEquals(Object, Object) assertEquals(String, String)} fails. + * Create and throw a ComparisonFailure manually if you want to show users the + * difference between two complex strings. + *

    + * Inspired by a patch from Alex Chaffee (alex@purpletech.com) + * + * @since 4.0 + */ +public class ComparisonFailure extends AssertionError { + /** + * The maximum length for expected and actual strings. If it is exceeded, the strings should be shortened. + * + * @see ComparisonCompactor + */ + private static final int MAX_CONTEXT_LENGTH = 20; + private static final long serialVersionUID = 1L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private String fExpected; + private String fActual; + + /** + * Constructs a comparison failure. + * + * @param message the identifying message or null + * @param expected the expected string value + * @param actual the actual string value + */ + public ComparisonFailure(String message, String expected, String actual) { + super(message); + this.fExpected = expected; + this.fActual = actual; + } + + /** + * Returns "..." in place of common prefix and "..." in place of common suffix between expected and actual. + * + * @see Throwable#getMessage() + */ + @Override + public String getMessage() { + return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); + } + + /** + * Returns the actual string value + * + * @return the actual string value + */ + public String getActual() { + return fActual; + } + + /** + * Returns the expected string value + * + * @return the expected string value + */ + public String getExpected() { + return fExpected; + } + + private static class ComparisonCompactor { + private static final String ELLIPSIS = "..."; + private static final String DIFF_END = "]"; + private static final String DIFF_START = "["; + + /** + * The maximum length for expected and actual strings to show. When + * contextLength is exceeded, the Strings are shortened. + */ + private final int contextLength; + private final String expected; + private final String actual; + + /** + * @param contextLength the maximum length of context surrounding the difference between the compared strings. + * When context length is exceeded, the prefixes and suffixes are compacted. + * @param expected the expected string value + * @param actual the actual string value + */ + public ComparisonCompactor(int contextLength, String expected, String actual) { + this.contextLength = contextLength; + this.expected = expected; + this.actual = actual; + } + + public String compact(String message) { + if (expected == null || actual == null || expected.equals(actual)) { + return Assert.format(message, expected, actual); + } else { + DiffExtractor extractor = new DiffExtractor(); + String compactedPrefix = extractor.compactPrefix(); + String compactedSuffix = extractor.compactSuffix(); + return Assert.format(message, + compactedPrefix + extractor.expectedDiff() + compactedSuffix, + compactedPrefix + extractor.actualDiff() + compactedSuffix); + } + } + + private String sharedPrefix() { + int end = Math.min(expected.length(), actual.length()); + for (int i = 0; i < end; i++) { + if (expected.charAt(i) != actual.charAt(i)) { + return expected.substring(0, i); + } + } + return expected.substring(0, end); + } + + private String sharedSuffix(String prefix) { + int suffixLength = 0; + int maxSuffixLength = Math.min(expected.length() - prefix.length(), + actual.length() - prefix.length()) - 1; + for (; suffixLength <= maxSuffixLength; suffixLength++) { + if (expected.charAt(expected.length() - 1 - suffixLength) + != actual.charAt(actual.length() - 1 - suffixLength)) { + break; + } + } + return expected.substring(expected.length() - suffixLength); + } + + private class DiffExtractor { + private final String sharedPrefix; + private final String sharedSuffix; + + /** + * Can not be instantiated outside {@link org.junit.ComparisonFailure.ComparisonCompactor}. + */ + private DiffExtractor() { + sharedPrefix = sharedPrefix(); + sharedSuffix = sharedSuffix(sharedPrefix); + } + + public String expectedDiff() { + return extractDiff(expected); + } + + public String actualDiff() { + return extractDiff(actual); + } + + public String compactPrefix() { + if (sharedPrefix.length() <= contextLength) { + return sharedPrefix; + } + return ELLIPSIS + sharedPrefix.substring(sharedPrefix.length() - contextLength); + } + + public String compactSuffix() { + if (sharedSuffix.length() <= contextLength) { + return sharedSuffix; + } + return sharedSuffix.substring(0, contextLength) + ELLIPSIS; + } + + private String extractDiff(String source) { + return DIFF_START + source.substring(sharedPrefix.length(), source.length() - sharedSuffix.length()) + + DIFF_END; + } + } + } +} diff --git a/src/main/java/org/junit/FixMethodOrder.java b/src/main/java/org/junit/FixMethodOrder.java new file mode 100644 index 000000000000..aaa0313e710c --- /dev/null +++ b/src/main/java/org/junit/FixMethodOrder.java @@ -0,0 +1,41 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.runners.MethodSorters; + +/** + * This class allows the user to choose the order of execution of the methods within a test class. + * + *

    The default order of execution of JUnit tests within a class is deterministic but not predictable. + * The order of execution is not guaranteed for Java 7 (and some previous versions), and can even change + * from run to run, so the order of execution was changed to be deterministic (in JUnit 4.11) + * + *

    It is recommended that test methods be written so that they are independent of the order that they are executed. + * However, there may be a number of dependent tests either through error or by design. + * This class allows the user to specify the order of execution of test methods. + * + *

    For possibilities, see {@link MethodSorters} + * + * Here is an example: + * + *

    + * @FixMethodOrder(MethodSorters.NAME_ASCENDING)
    + * public class MyTest {
    + * }
    + * 
    + * + * @see org.junit.runners.MethodSorters + * @since 4.11 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface FixMethodOrder { + /** + * Optionally specify value to have the methods executed in a particular order + */ + MethodSorters value() default MethodSorters.DEFAULT; +} diff --git a/src/main/java/org/junit/Ignore.java b/src/main/java/org/junit/Ignore.java new file mode 100644 index 000000000000..db23581073bd --- /dev/null +++ b/src/main/java/org/junit/Ignore.java @@ -0,0 +1,40 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with + * {@link org.junit.Test} that are also annotated with @Ignore will not be executed as tests. + * Also, you can annotate a class containing test methods with @Ignore and none of the containing + * tests will be executed. Native JUnit 4 test runners should report the number of ignored tests along with the + * number of tests that ran and the number of tests that failed. + * + *

    For example: + *

    + *    @Ignore @Test public void something() { ...
    + * 
    + * @Ignore takes an optional default parameter if you want to record why a test is being ignored: + *
    + *    @Ignore("not ready yet") @Test public void something() { ...
    + * 
    + * @Ignore can also be applied to the test class: + *
    + *      @Ignore public class IgnoreMe {
    + *          @Test public void test1() { ... }
    + *          @Test public void test2() { ... }
    + *         }
    + * 
    + * + * @since 4.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +public @interface Ignore { + /** + * The optional reason why the test is ignored. + */ + String value() default ""; +} diff --git a/src/main/java/org/junit/Rule.java b/src/main/java/org/junit/Rule.java new file mode 100644 index 000000000000..711235c5a7f3 --- /dev/null +++ b/src/main/java/org/junit/Rule.java @@ -0,0 +1,70 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotates fields that reference rules or methods that return a rule. A field must be public, not + * static, and a subtype of {@link org.junit.rules.TestRule} (preferred) or + * {@link org.junit.rules.MethodRule}. A method must be public, not static, + * and must return a subtype of {@link org.junit.rules.TestRule} (preferred) or + * {@link org.junit.rules.MethodRule}. + *

    + * The {@link org.junit.runners.model.Statement} passed + * to the {@link org.junit.rules.TestRule} will run any {@link Before} methods, + * then the {@link Test} method, and finally any {@link After} methods, + * throwing an exception if any of these fail. If there are multiple + * annotated {@link Rule}s on a class, they will be applied in order of fields first, then methods. + * However, if there are multiple fields (or methods) they will be applied in an order + * that depends on your JVM's implementation of the reflection API, which is + * undefined, in general. Rules defined by fields will always be applied + * before Rules defined by methods. You can use a {@link org.junit.rules.RuleChain} if you want + * to have control over the order in which the Rules are applied. + *

    + * For example, here is a test class that creates a temporary folder before + * each test method, and deletes it after each: + *

    + * public static class HasTempFolder {
    + *     @Rule
    + *     public TemporaryFolder folder= new TemporaryFolder();
    + *
    + *     @Test
    + *     public void testUsingTempFolder() throws IOException {
    + *         File createdFile= folder.newFile("myfile.txt");
    + *         File createdFolder= folder.newFolder("subfolder");
    + *         // ...
    + *     }
    + * }
    + * 
    + *

    + * And the same using a method. + *

    + * public static class HasTempFolder {
    + *     private TemporaryFolder folder= new TemporaryFolder();
    + *
    + *     @Rule
    + *     public TemporaryFolder getFolder() {
    + *         return folder;
    + *     }
    + *
    + *     @Test
    + *     public void testUsingTempFolder() throws IOException {
    + *         File createdFile= folder.newFile("myfile.txt");
    + *         File createdFolder= folder.newFolder("subfolder");
    + *         // ...
    + *     }
    + * }
    + * 
    + *

    + * For more information and more examples, see + * {@link org.junit.rules.TestRule}. + * + * @since 4.7 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD}) +public @interface Rule { + +} \ No newline at end of file diff --git a/src/main/java/org/junit/Test.java b/src/main/java/org/junit/Test.java new file mode 100644 index 000000000000..a003b2e6794b --- /dev/null +++ b/src/main/java/org/junit/Test.java @@ -0,0 +1,98 @@ +package org.junit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The Test annotation tells JUnit that the public void method + * to which it is attached can be run as a test case. To run the method, + * JUnit first constructs a fresh instance of the class then invokes the + * annotated method. Any exceptions thrown by the test will be reported + * by JUnit as a failure. If no exceptions are thrown, the test is assumed + * to have succeeded. + *

    + * A simple test looks like this: + *

    + * public class Example {
    + *    @Test
    + *    public void method() {
    + *       org.junit.Assert.assertTrue( new ArrayList().isEmpty() );
    + *    }
    + * }
    + * 
    + *

    + * The Test annotation supports two optional parameters. + * The first, expected, declares that a test method should throw + * an exception. If it doesn't throw an exception or if it throws a different exception + * than the one declared, the test fails. For example, the following test succeeds: + *

    + *    @Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
    + *       new ArrayList<Object>().get(1);
    + *    }
    + * 
    + * If the exception's message or one of its properties should be verified, the + * {@link org.junit.rules.ExpectedException ExpectedException} rule can be used. Further + * information about exception testing can be found at the + * JUnit Wiki. + *

    + * The second optional parameter, timeout, causes a test to fail if it takes + * longer than a specified amount of clock time (measured in milliseconds). The following test fails: + *

    + *    @Test(timeout=100) public void infinity() {
    + *       while(true);
    + *    }
    + * 
    + * Warning: while timeout is useful to catch and terminate + * infinite loops, it should not be considered deterministic. The + * following test may or may not fail depending on how the operating system + * schedules threads: + *
    + *    @Test(timeout=100) public void sleep100() {
    + *       Thread.sleep(100);
    + *    }
    + * 
    + * THREAD SAFETY WARNING: Test methods with a timeout parameter are run in a thread other than the + * thread which runs the fixture's @Before and @After methods. This may yield different behavior for + * code that is not thread safe when compared to the same test method without a timeout parameter. + * Consider using the {@link org.junit.rules.Timeout} rule instead, which ensures a test method is run on the + * same thread as the fixture's @Before and @After methods. + * + * @since 4.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface Test { + + /** + * Default empty exception. + */ + static class None extends Throwable { + private static final long serialVersionUID = 1L; + + private None() { + } + } + + /** + * Optionally specify expected, a Throwable, to cause a test method to succeed if + * and only if an exception of the specified class is thrown by the method. If the Throwable's + * message or one of its properties should be verified, the + * {@link org.junit.rules.ExpectedException ExpectedException} rule can be used instead. + */ + Class expected() default None.class; + + /** + * Optionally specify timeout in milliseconds to cause a test method to fail if it + * takes longer than that number of milliseconds. + *

    + * THREAD SAFETY WARNING: Test methods with a timeout parameter are run in a thread other than the + * thread which runs the fixture's @Before and @After methods. This may yield different behavior for + * code that is not thread safe when compared to the same test method without a timeout parameter. + * Consider using the {@link org.junit.rules.Timeout} rule instead, which ensures a test method is run on the + * same thread as the fixture's @Before and @After methods. + *

    + */ + long timeout() default 0L; +} diff --git a/src/main/java/org/junit/experimental/ParallelComputer.java b/src/main/java/org/junit/experimental/ParallelComputer.java new file mode 100644 index 000000000000..97da0f759f48 --- /dev/null +++ b/src/main/java/org/junit/experimental/ParallelComputer.java @@ -0,0 +1,67 @@ +package org.junit.experimental; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import org.junit.runner.Computer; +import org.junit.runner.Runner; +import org.junit.runners.ParentRunner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; +import org.junit.runners.model.RunnerScheduler; + +public class ParallelComputer extends Computer { + private final boolean classes; + + private final boolean methods; + + public ParallelComputer(boolean classes, boolean methods) { + this.classes = classes; + this.methods = methods; + } + + public static Computer classes() { + return new ParallelComputer(true, false); + } + + public static Computer methods() { + return new ParallelComputer(false, true); + } + + private static Runner parallelize(Runner runner) { + if (runner instanceof ParentRunner) { + ((ParentRunner) runner).setScheduler(new RunnerScheduler() { + private final ExecutorService fService = Executors.newCachedThreadPool(); + + public void schedule(Runnable childStatement) { + fService.submit(childStatement); + } + + public void finished() { + try { + fService.shutdown(); + fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + e.printStackTrace(System.err); + } + } + }); + } + return runner; + } + + @Override + public Runner getSuite(RunnerBuilder builder, java.lang.Class[] classes) + throws InitializationError { + Runner suite = super.getSuite(builder, classes); + return this.classes ? parallelize(suite) : suite; + } + + @Override + protected Runner getRunner(RunnerBuilder builder, Class testClass) + throws Throwable { + Runner runner = super.getRunner(builder, testClass); + return methods ? parallelize(runner) : runner; + } +} diff --git a/src/main/java/org/junit/experimental/categories/Categories.java b/src/main/java/org/junit/experimental/categories/Categories.java new file mode 100644 index 000000000000..34bf78c1606f --- /dev/null +++ b/src/main/java/org/junit/experimental/categories/Categories.java @@ -0,0 +1,356 @@ +package org.junit.experimental.categories; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.junit.runner.Description; +import org.junit.runner.manipulation.Filter; +import org.junit.runner.manipulation.NoTestsRemainException; +import org.junit.runners.Suite; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; + +/** + * From a given set of test classes, runs only the classes and methods that are + * annotated with either the category given with the @IncludeCategory + * annotation, or a subtype of that category. + *

    + * Note that, for now, annotating suites with {@code @Category} has no effect. + * Categories must be annotated on the direct method or class. + *

    + * Example: + *

    + * public interface FastTests {
    + * }
    + *
    + * public interface SlowTests {
    + * }
    + *
    + * public interface SmokeTests
    + * }
    + *
    + * public static class A {
    + *     @Test
    + *     public void a() {
    + *         fail();
    + *     }
    + *
    + *     @Category(SlowTests.class)
    + *     @Test
    + *     public void b() {
    + *     }
    + *
    + *     @Category({FastTests.class, SmokeTests.class})
    + *     @Test
    + *     public void c() {
    + *     }
    + * }
    + *
    + * @Category({SlowTests.class, FastTests.class})
    + * public static class B {
    + *     @Test
    + *     public void d() {
    + *     }
    + * }
    + *
    + * @RunWith(Categories.class)
    + * @IncludeCategory(SlowTests.class)
    + * @SuiteClasses({A.class, B.class})
    + * // Note that Categories is a kind of Suite
    + * public static class SlowTestSuite {
    + *     // Will run A.b and B.d, but not A.a and A.c
    + * }
    + * 
    + *

    + * Example to run multiple categories: + *

    + * @RunWith(Categories.class)
    + * @IncludeCategory({FastTests.class, SmokeTests.class})
    + * @SuiteClasses({A.class, B.class})
    + * public static class FastOrSmokeTestSuite {
    + *     // Will run A.c and B.d, but not A.b because it is not any of FastTests or SmokeTests
    + * }
    + * 
    + * + * @version 4.12 + * @see Categories at JUnit wiki + */ +public class Categories extends Suite { + + @Retention(RetentionPolicy.RUNTIME) + public @interface IncludeCategory { + /** + * Determines the tests to run that are annotated with categories specified in + * the value of this annotation or their subtypes unless excluded with {@link ExcludeCategory}. + */ + Class[] value() default {}; + + /** + * If true, runs tests annotated with any of the categories in + * {@link IncludeCategory#value()}. Otherwise, runs tests only if annotated with all of the categories. + */ + boolean matchAny() default true; + } + + @Retention(RetentionPolicy.RUNTIME) + public @interface ExcludeCategory { + /** + * Determines the tests which do not run if they are annotated with categories specified in the + * value of this annotation or their subtypes regardless of being included in {@link IncludeCategory#value()}. + */ + Class[] value() default {}; + + /** + * If true, the tests annotated with any of the categories in {@link ExcludeCategory#value()} + * do not run. Otherwise, the tests do not run if and only if annotated with all categories. + */ + boolean matchAny() default true; + } + + public static class CategoryFilter extends Filter { + private final Set> included; + private final Set> excluded; + private final boolean includedAny; + private final boolean excludedAny; + + public static CategoryFilter include(boolean matchAny, Class... categories) { + if (hasNull(categories)) { + throw new NullPointerException("has null category"); + } + return categoryFilter(matchAny, createSet(categories), true, null); + } + + public static CategoryFilter include(Class category) { + return include(true, category); + } + + public static CategoryFilter include(Class... categories) { + return include(true, categories); + } + + public static CategoryFilter exclude(boolean matchAny, Class... categories) { + if (hasNull(categories)) { + throw new NullPointerException("has null category"); + } + return categoryFilter(true, null, matchAny, createSet(categories)); + } + + public static CategoryFilter exclude(Class category) { + return exclude(true, category); + } + + public static CategoryFilter exclude(Class... categories) { + return exclude(true, categories); + } + + public static CategoryFilter categoryFilter(boolean matchAnyInclusions, Set> inclusions, + boolean matchAnyExclusions, Set> exclusions) { + return new CategoryFilter(matchAnyInclusions, inclusions, matchAnyExclusions, exclusions); + } + + protected CategoryFilter(boolean matchAnyIncludes, Set> includes, + boolean matchAnyExcludes, Set> excludes) { + includedAny = matchAnyIncludes; + excludedAny = matchAnyExcludes; + included = copyAndRefine(includes); + excluded = copyAndRefine(excludes); + } + + /** + * @see #toString() + */ + @Override + public String describe() { + return toString(); + } + + /** + * Returns string in the form "[included categories] - [excluded categories]", where both + * sets have comma separated names of categories. + * + * @return string representation for the relative complement of excluded categories set + * in the set of included categories. Examples: + *
      + *
    • "categories [all]" for all included categories and no excluded ones; + *
    • "categories [all] - [A, B]" for all included categories and given excluded ones; + *
    • "categories [A, B] - [C, D]" for given included categories and given excluded ones. + *
    + * @see Class#toString() name of category + */ + @Override public String toString() { + StringBuilder description= new StringBuilder("categories ") + .append(included.isEmpty() ? "[all]" : included); + if (!excluded.isEmpty()) { + description.append(" - ").append(excluded); + } + return description.toString(); + } + + @Override + public boolean shouldRun(Description description) { + if (hasCorrectCategoryAnnotation(description)) { + return true; + } + + for (Description each : description.getChildren()) { + if (shouldRun(each)) { + return true; + } + } + + return false; + } + + private boolean hasCorrectCategoryAnnotation(Description description) { + final Set> childCategories= categories(description); + + // If a child has no categories, immediately return. + if (childCategories.isEmpty()) { + return included.isEmpty(); + } + + if (!excluded.isEmpty()) { + if (excludedAny) { + if (matchesAnyParentCategories(childCategories, excluded)) { + return false; + } + } else { + if (matchesAllParentCategories(childCategories, excluded)) { + return false; + } + } + } + + if (included.isEmpty()) { + // Couldn't be excluded, and with no suite's included categories treated as should run. + return true; + } else { + if (includedAny) { + return matchesAnyParentCategories(childCategories, included); + } else { + return matchesAllParentCategories(childCategories, included); + } + } + } + + /** + * @return true if at least one (any) parent category match a child, otherwise false. + * If empty parentCategories, returns false. + */ + private boolean matchesAnyParentCategories(Set> childCategories, Set> parentCategories) { + for (Class parentCategory : parentCategories) { + if (hasAssignableTo(childCategories, parentCategory)) { + return true; + } + } + return false; + } + + /** + * @return false if at least one parent category does not match children, otherwise true. + * If empty parentCategories, returns true. + */ + private boolean matchesAllParentCategories(Set> childCategories, Set> parentCategories) { + for (Class parentCategory : parentCategories) { + if (!hasAssignableTo(childCategories, parentCategory)) { + return false; + } + } + return true; + } + + private static Set> categories(Description description) { + Set> categories= new HashSet>(); + Collections.addAll(categories, directCategories(description)); + Collections.addAll(categories, directCategories(parentDescription(description))); + return categories; + } + + private static Description parentDescription(Description description) { + Class testClass= description.getTestClass(); + return testClass == null ? null : Description.createSuiteDescription(testClass); + } + + private static Class[] directCategories(Description description) { + if (description == null) { + return new Class[0]; + } + + Category annotation= description.getAnnotation(Category.class); + return annotation == null ? new Class[0] : annotation.value(); + } + + private static Set> copyAndRefine(Set> classes) { + Set> c= new HashSet>(); + if (classes != null) { + c.addAll(classes); + } + c.remove(null); + return c; + } + + private static boolean hasNull(Class... classes) { + if (classes == null) return false; + for (Class clazz : classes) { + if (clazz == null) { + return true; + } + } + return false; + } + } + + public Categories(Class klass, RunnerBuilder builder) throws InitializationError { + super(klass, builder); + try { + Set> included= getIncludedCategory(klass); + Set> excluded= getExcludedCategory(klass); + boolean isAnyIncluded= isAnyIncluded(klass); + boolean isAnyExcluded= isAnyExcluded(klass); + + filter(CategoryFilter.categoryFilter(isAnyIncluded, included, isAnyExcluded, excluded)); + } catch (NoTestsRemainException e) { + throw new InitializationError(e); + } + } + + private static Set> getIncludedCategory(Class klass) { + IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class); + return createSet(annotation == null ? null : annotation.value()); + } + + private static boolean isAnyIncluded(Class klass) { + IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class); + return annotation == null || annotation.matchAny(); + } + + private static Set> getExcludedCategory(Class klass) { + ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class); + return createSet(annotation == null ? null : annotation.value()); + } + + private static boolean isAnyExcluded(Class klass) { + ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class); + return annotation == null || annotation.matchAny(); + } + + private static boolean hasAssignableTo(Set> assigns, Class to) { + for (final Class from : assigns) { + if (to.isAssignableFrom(from)) { + return true; + } + } + return false; + } + + private static Set> createSet(Class... t) { + final Set> set= new HashSet>(); + if (t != null) { + Collections.addAll(set, t); + } + return set; + } +} diff --git a/src/main/java/org/junit/experimental/categories/Category.java b/src/main/java/org/junit/experimental/categories/Category.java new file mode 100644 index 000000000000..8eae83677c94 --- /dev/null +++ b/src/main/java/org/junit/experimental/categories/Category.java @@ -0,0 +1,48 @@ +package org.junit.experimental.categories; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import org.junit.validator.ValidateWith; + +/** + * Marks a test class or test method as belonging to one or more categories of tests. + * The value is an array of arbitrary classes. + * + * This annotation is only interpreted by the Categories runner (at present). + * + * For example: + *
    + * public interface FastTests {}
    + * public interface SlowTests {}
    + *
    + * public static class A {
    + * @Test
    + * public void a() {
    + * fail();
    + * }
    + *
    + * @Category(SlowTests.class)
    + * @Test
    + * public void b() {
    + * }
    + * }
    + *
    + * @Category({SlowTests.class, FastTests.class})
    + * public static class B {
    + * @Test
    + * public void c() {
    + *
    + * }
    + * }
    + * 
    + * + * For more usage, see code example on {@link Categories}. + */ +@Retention(RetentionPolicy.RUNTIME) +@Inherited +@ValidateWith(CategoryValidator.class) +public @interface Category { + Class[] value(); +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java b/src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java new file mode 100644 index 000000000000..cee1ae724595 --- /dev/null +++ b/src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java @@ -0,0 +1,47 @@ +package org.junit.experimental.categories; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.internal.Classes; +import org.junit.runner.FilterFactory; +import org.junit.runner.FilterFactoryParams; +import org.junit.runner.manipulation.Filter; + +/** + * Implementation of FilterFactory for Category filtering. + */ +abstract class CategoryFilterFactory implements FilterFactory { + /** + * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given a + * {@link FilterFactoryParams} argument. + * + * @param params Parameters needed to create the {@link Filter} + */ + public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { + try { + return createFilter(parseCategories(params.getArgs())); + } catch (ClassNotFoundException e) { + throw new FilterNotCreatedException(e); + } + } + + /** + * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given an array of classes. + * + * @param categories Category classes. + */ + protected abstract Filter createFilter(List> categories); + + private List> parseCategories(String categories) throws ClassNotFoundException { + List> categoryClasses = new ArrayList>(); + + for (String category : categories.split(",")) { + Class categoryClass = Classes.getClass(category); + + categoryClasses.add(categoryClass); + } + + return categoryClasses; + } +} diff --git a/src/main/java/org/junit/experimental/categories/CategoryValidator.java b/src/main/java/org/junit/experimental/categories/CategoryValidator.java new file mode 100644 index 000000000000..491d8accb586 --- /dev/null +++ b/src/main/java/org/junit/experimental/categories/CategoryValidator.java @@ -0,0 +1,62 @@ +package org.junit.experimental.categories; + +import static java.util.Arrays.asList; +import static java.util.Collections.unmodifiableList; +import static java.util.Collections.unmodifiableSet; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.runners.model.FrameworkMethod; +import org.junit.validator.AnnotationValidator; + +/** + * Validates that there are no errors in the use of the {@code Category} + * annotation. If there is, a {@code Throwable} object will be added to the list + * of errors. + * + * @since 4.12 + */ +public final class CategoryValidator extends AnnotationValidator { + + @SuppressWarnings("unchecked") + private static final Set> INCOMPATIBLE_ANNOTATIONS = unmodifiableSet(new HashSet>( + asList(BeforeClass.class, AfterClass.class, Before.class, After.class))); + + /** + * Adds to {@code errors} a throwable for each problem detected. Looks for + * {@code BeforeClass}, {@code AfterClass}, {@code Before} and {@code After} + * annotations. + * + * @param method the method that is being validated + * @return A list of exceptions detected + * + * @since 4.12 + */ + @Override + public List validateAnnotatedMethod(FrameworkMethod method) { + List errors = new ArrayList(); + Annotation[] annotations = method.getAnnotations(); + for (Annotation annotation : annotations) { + for (Class clazz : INCOMPATIBLE_ANNOTATIONS) { + if (annotation.annotationType().isAssignableFrom(clazz)) { + addErrorMessage(errors, clazz); + } + } + } + return unmodifiableList(errors); + } + + private void addErrorMessage(List errors, Class clazz) { + String message = String.format("@%s can not be combined with @Category", + clazz.getSimpleName()); + errors.add(new Exception(message)); + } +} diff --git a/src/main/java/org/junit/experimental/categories/ExcludeCategories.java b/src/main/java/org/junit/experimental/categories/ExcludeCategories.java new file mode 100644 index 000000000000..8ccb6b5eec04 --- /dev/null +++ b/src/main/java/org/junit/experimental/categories/ExcludeCategories.java @@ -0,0 +1,52 @@ +package org.junit.experimental.categories; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.experimental.categories.Categories.CategoryFilter; +import org.junit.runner.manipulation.Filter; + +/** + * {@link org.junit.runner.FilterFactory} to exclude categories. + * + * The {@link Filter} that is created will filter out tests that are categorized with any of the + * given categories. + * + * Usage from command line: + * + * --filter=org.junit.experimental.categories.ExcludeCategories=pkg.of.Cat1,pkg.of.Cat2 + * + * + * Usage from API: + * + * new ExcludeCategories().createFilter(Cat1.class, Cat2.class); + * + */ +public final class ExcludeCategories extends CategoryFilterFactory { + /** + * Creates a {@link Filter} which is only passed by tests that are + * not categorized with any of the specified categories. + * + * @param categories Category classes. + */ + @Override + protected Filter createFilter(List> categories) { + return new ExcludesAny(categories); + } + + private static class ExcludesAny extends CategoryFilter { + public ExcludesAny(List> categories) { + this(new HashSet>(categories)); + } + + public ExcludesAny(Set> categories) { + super(true, null, true, categories); + } + + @Override + public String describe() { + return "excludes " + super.describe(); + } + } +} diff --git a/src/main/java/org/junit/experimental/categories/IncludeCategories.java b/src/main/java/org/junit/experimental/categories/IncludeCategories.java new file mode 100644 index 000000000000..38eb6934c812 --- /dev/null +++ b/src/main/java/org/junit/experimental/categories/IncludeCategories.java @@ -0,0 +1,52 @@ +package org.junit.experimental.categories; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.experimental.categories.Categories.CategoryFilter; +import org.junit.runner.manipulation.Filter; + +/** + * {@link org.junit.runner.FilterFactory} to include categories. + * + * The {@link Filter} that is created will filter out tests that are categorized with any of the + * given categories. + * + * Usage from command line: + * + * --filter=org.junit.experimental.categories.IncludeCategories=pkg.of.Cat1,pkg.of.Cat2 + * + * + * Usage from API: + * + * new IncludeCategories().createFilter(Cat1.class, Cat2.class); + * + */ +public final class IncludeCategories extends CategoryFilterFactory { + /** + * Creates a {@link Filter} which is only passed by tests that are + * categorized with any of the specified categories. + * + * @param categories Category classes. + */ + @Override + protected Filter createFilter(List> categories) { + return new IncludesAny(categories); + } + + private static class IncludesAny extends CategoryFilter { + public IncludesAny(List> categories) { + this(new HashSet>(categories)); + } + + public IncludesAny(Set> categories) { + super(true, categories, true, null); + } + + @Override + public String describe() { + return "includes " + super.describe(); + } + } +} diff --git a/src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java b/src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java new file mode 100644 index 000000000000..116d7559d049 --- /dev/null +++ b/src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java @@ -0,0 +1,15 @@ +package org.junit.experimental.max; + +/** + * Thrown when Max cannot read the MaxCore serialization + */ +public class CouldNotReadCoreException extends Exception { + private static final long serialVersionUID = 1L; + + /** + * Constructs + */ + public CouldNotReadCoreException(Throwable e) { + super(e); + } +} diff --git a/src/main/java/org/junit/experimental/max/MaxCore.java b/src/main/java/org/junit/experimental/max/MaxCore.java new file mode 100644 index 000000000000..625cade5b1ea --- /dev/null +++ b/src/main/java/org/junit/experimental/max/MaxCore.java @@ -0,0 +1,181 @@ +package org.junit.experimental.max; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import junit.framework.TestSuite; +import org.junit.internal.requests.SortingRequest; +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.internal.runners.JUnit38ClassRunner; +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.runners.Suite; +import org.junit.runners.model.InitializationError; + +/** + * A replacement for JUnitCore, which keeps track of runtime and failure history, and reorders tests + * to maximize the chances that a failing test occurs early in the test run. + * + * The rules for sorting are: + *
      + *
    1. Never-run tests first, in arbitrary order + *
    2. Group remaining tests by the date at which they most recently failed. + *
    3. Sort groups such that the most recent failure date is first, and never-failing tests are at the end. + *
    4. Within a group, run the fastest tests first. + *
    + */ +public class MaxCore { + private static final String MALFORMED_JUNIT_3_TEST_CLASS_PREFIX = "malformed JUnit 3 test class: "; + + /** + * Create a new MaxCore from a serialized file stored at storedResults + * + * @deprecated use storedLocally() + */ + @Deprecated + public static MaxCore forFolder(String folderName) { + return storedLocally(new File(folderName)); + } + + /** + * Create a new MaxCore from a serialized file stored at storedResults + */ + public static MaxCore storedLocally(File storedResults) { + return new MaxCore(storedResults); + } + + private final MaxHistory history; + + private MaxCore(File storedResults) { + history = MaxHistory.forFolder(storedResults); + } + + /** + * Run all the tests in class. + * + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(Class testClass) { + return run(Request.aClass(testClass)); + } + + /** + * Run all the tests contained in request. + * + * @param request the request describing tests + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(Request request) { + return run(request, new JUnitCore()); + } + + /** + * Run all the tests contained in request. + * + * This variant should be used if {@code core} has attached listeners that this + * run should notify. + * + * @param request the request describing tests + * @param core a JUnitCore to delegate to. + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(Request request, JUnitCore core) { + core.addListener(history.listener()); + return core.run(sortRequest(request).getRunner()); + } + + /** + * @return a new Request, which contains all of the same tests, but in a new order. + */ + public Request sortRequest(Request request) { + if (request instanceof SortingRequest) { + // We'll pay big karma points for this + return request; + } + List leaves = findLeaves(request); + Collections.sort(leaves, history.testComparator()); + return constructLeafRequest(leaves); + } + + private Request constructLeafRequest(List leaves) { + final List runners = new ArrayList(); + for (Description each : leaves) { + runners.add(buildRunner(each)); + } + return new Request() { + @Override + public Runner getRunner() { + try { + return new Suite((Class) null, runners) { + }; + } catch (InitializationError e) { + return new ErrorReportingRunner(null, e); + } + } + }; + } + + private Runner buildRunner(Description each) { + if (each.toString().equals("TestSuite with 0 tests")) { + return Suite.emptySuite(); + } + if (each.toString().startsWith(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX)) { + // This is cheating, because it runs the whole class + // to get the warning for this method, but we can't do better, + // because JUnit 3.8's + // thrown away which method the warning is for. + return new JUnit38ClassRunner(new TestSuite(getMalformedTestClass(each))); + } + Class type = each.getTestClass(); + if (type == null) { + throw new RuntimeException("Can't build a runner from description [" + each + "]"); + } + String methodName = each.getMethodName(); + if (methodName == null) { + return Request.aClass(type).getRunner(); + } + return Request.method(type, methodName).getRunner(); + } + + private Class getMalformedTestClass(Description each) { + try { + return Class.forName(each.toString().replace(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX, "")); + } catch (ClassNotFoundException e) { + return null; + } + } + + /** + * @param request a request to run + * @return a list of method-level tests to run, sorted in the order + * specified in the class comment. + */ + public List sortedLeavesForTest(Request request) { + return findLeaves(sortRequest(request)); + } + + private List findLeaves(Request request) { + List results = new ArrayList(); + findLeaves(null, request.getRunner().getDescription(), results); + return results; + } + + private void findLeaves(Description parent, Description description, List results) { + if (description.getChildren().isEmpty()) { + if (description.toString().equals("warning(junit.framework.TestSuite$1)")) { + results.add(Description.createSuiteDescription(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX + parent)); + } else { + results.add(description); + } + } else { + for (Description each : description.getChildren()) { + findLeaves(description, each, results); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/max/MaxHistory.java b/src/main/java/org/junit/experimental/max/MaxHistory.java new file mode 100644 index 000000000000..273b07947553 --- /dev/null +++ b/src/main/java/org/junit/experimental/max/MaxHistory.java @@ -0,0 +1,173 @@ +package org.junit.experimental.max; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +import org.junit.runner.Description; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + +/** + * Stores a subset of the history of each test: + *
      + *
    • Last failure timestamp + *
    • Duration of last execution + *
    + */ +public class MaxHistory implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * Loads a {@link MaxHistory} from {@code file}, or generates a new one that + * will be saved to {@code file}. + */ + public static MaxHistory forFolder(File file) { + if (file.exists()) { + try { + return readHistory(file); + } catch (CouldNotReadCoreException e) { + e.printStackTrace(); + file.delete(); + } + } + return new MaxHistory(file); + } + + private static MaxHistory readHistory(File storedResults) + throws CouldNotReadCoreException { + try { + FileInputStream file = new FileInputStream(storedResults); + try { + ObjectInputStream stream = new ObjectInputStream(file); + try { + return (MaxHistory) stream.readObject(); + } finally { + stream.close(); + } + } finally { + file.close(); + } + } catch (Exception e) { + throw new CouldNotReadCoreException(e); + } + } + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final Map fDurations = new HashMap(); + private final Map fFailureTimestamps = new HashMap(); + private final File fHistoryStore; + + private MaxHistory(File storedResults) { + fHistoryStore = storedResults; + } + + private void save() throws IOException { + ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream( + fHistoryStore)); + stream.writeObject(this); + stream.close(); + } + + Long getFailureTimestamp(Description key) { + return fFailureTimestamps.get(key.toString()); + } + + void putTestFailureTimestamp(Description key, long end) { + fFailureTimestamps.put(key.toString(), end); + } + + boolean isNewTest(Description key) { + return !fDurations.containsKey(key.toString()); + } + + Long getTestDuration(Description key) { + return fDurations.get(key.toString()); + } + + void putTestDuration(Description description, long duration) { + fDurations.put(description.toString(), duration); + } + + private final class RememberingListener extends RunListener { + private long overallStart = System.currentTimeMillis(); + + private Map starts = new HashMap(); + + @Override + public void testStarted(Description description) throws Exception { + starts.put(description, System.nanoTime()); // Get most accurate + // possible time + } + + @Override + public void testFinished(Description description) throws Exception { + long end = System.nanoTime(); + long start = starts.get(description); + putTestDuration(description, end - start); + } + + @Override + public void testFailure(Failure failure) throws Exception { + putTestFailureTimestamp(failure.getDescription(), overallStart); + } + + @Override + public void testRunFinished(Result result) throws Exception { + save(); + } + } + + private class TestComparator implements Comparator { + public int compare(Description o1, Description o2) { + // Always prefer new tests + if (isNewTest(o1)) { + return -1; + } + if (isNewTest(o2)) { + return 1; + } + // Then most recently failed first + int result = getFailure(o2).compareTo(getFailure(o1)); + return result != 0 ? result + // Then shorter tests first + : getTestDuration(o1).compareTo(getTestDuration(o2)); + } + + private Long getFailure(Description key) { + Long result = getFailureTimestamp(key); + if (result == null) { + return 0L; // 0 = "never failed (that I know about)" + } + return result; + } + } + + /** + * @return a listener that will update this history based on the test + * results reported. + */ + public RunListener listener() { + return new RememberingListener(); + } + + /** + * @return a comparator that ranks tests based on the JUnit Max sorting + * rules, as described in the {@link MaxCore} class comment. + */ + public Comparator testComparator() { + return new TestComparator(); + } +} diff --git a/src/main/java/org/junit/experimental/results/FailureList.java b/src/main/java/org/junit/experimental/results/FailureList.java new file mode 100644 index 000000000000..e02eeae6a439 --- /dev/null +++ b/src/main/java/org/junit/experimental/results/FailureList.java @@ -0,0 +1,28 @@ +package org.junit.experimental.results; + +import java.util.List; + +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + +class FailureList { + private final List failures; + + public FailureList(List failures) { + this.failures = failures; + } + + public Result result() { + Result result = new Result(); + RunListener listener = result.createListener(); + for (Failure failure : failures) { + try { + listener.testFailure(failure); + } catch (Exception e) { + throw new RuntimeException("I can't believe this happened"); + } + } + return result; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/results/PrintableResult.java b/src/main/java/org/junit/experimental/results/PrintableResult.java new file mode 100644 index 000000000000..ffe22f0e957c --- /dev/null +++ b/src/main/java/org/junit/experimental/results/PrintableResult.java @@ -0,0 +1,63 @@ +package org.junit.experimental.results; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.List; + +import org.junit.internal.TextListener; +import org.junit.runner.JUnitCore; +import org.junit.runner.Request; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +/** + * A test result that prints nicely in error messages. + * This is only intended to be used in JUnit self-tests. + * For example: + * + *
    + *    assertThat(testResult(HasExpectedException.class), isSuccessful());
    + * 
    + */ +public class PrintableResult { + private Result result; + + /** + * The result of running JUnit on {@code type} + */ + public static PrintableResult testResult(Class type) { + return testResult(Request.aClass(type)); + } + + /** + * The result of running JUnit on Request {@code request} + */ + public static PrintableResult testResult(Request request) { + return new PrintableResult(new JUnitCore().run(request)); + } + + /** + * A result that includes the given {@code failures} + */ + public PrintableResult(List failures) { + this(new FailureList(failures).result()); + } + + private PrintableResult(Result result) { + this.result = result; + } + + /** + * Returns the number of failures in this result. + */ + public int failureCount() { + return result.getFailures().size(); + } + + @Override + public String toString() { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + new TextListener(new PrintStream(stream)).testRunFinished(result); + return stream.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/results/ResultMatchers.java b/src/main/java/org/junit/experimental/results/ResultMatchers.java new file mode 100644 index 000000000000..98778a9f924e --- /dev/null +++ b/src/main/java/org/junit/experimental/results/ResultMatchers.java @@ -0,0 +1,79 @@ +package org.junit.experimental.results; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; + +/** + * Matchers on a PrintableResult, to enable JUnit self-tests. + * For example: + * + *
    + * assertThat(testResult(HasExpectedException.class), isSuccessful());
    + * 
    + */ +public class ResultMatchers { + + /** + * Do not instantiate. + * @deprecated will be private soon. + */ + @Deprecated + public ResultMatchers() { + } + + /** + * Matches if the tests are all successful + */ + public static Matcher isSuccessful() { + return failureCountIs(0); + } + + /** + * Matches if there are {@code count} failures + */ + public static Matcher failureCountIs(final int count) { + return new TypeSafeMatcher() { + public void describeTo(Description description) { + description.appendText("has " + count + " failures"); + } + + @Override + public boolean matchesSafely(PrintableResult item) { + return item.failureCount() == count; + } + }; + } + + /** + * Matches if the result has exactly one failure, and it contains {@code string} + */ + public static Matcher hasSingleFailureContaining(final String string) { + return new BaseMatcher() { + public boolean matches(Object item) { + return item.toString().contains(string) && failureCountIs(1).matches(item); + } + + public void describeTo(Description description) { + description.appendText("has single failure containing " + string); + } + }; + } + + /** + * Matches if the result has one or more failures, and at least one of them + * contains {@code string} + */ + public static Matcher hasFailureContaining(final String string) { + return new BaseMatcher() { + public boolean matches(Object item) { + return item.toString().contains(string); + } + + public void describeTo(Description description) { + description.appendText("has failure containing " + string); + } + }; + } +} diff --git a/src/main/java/org/junit/experimental/runners/Enclosed.java b/src/main/java/org/junit/experimental/runners/Enclosed.java new file mode 100644 index 000000000000..610b97066897 --- /dev/null +++ b/src/main/java/org/junit/experimental/runners/Enclosed.java @@ -0,0 +1,45 @@ +package org.junit.experimental.runners; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import org.junit.runners.Suite; +import org.junit.runners.model.RunnerBuilder; + +/** + * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class + * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes + * to group them for convenience or to share constants. Abstract inner classes are ignored. + *

    + * So, for example: + *

    + * @RunWith(Enclosed.class)
    + * public class ListTests {
    + *     ...useful shared stuff...
    + *     public static class OneKindOfListTest {...}
    + *     public static class AnotherKind {...}
    + *     abstract public static class Ignored {...}
    + * }
    + * 
    + */ +public class Enclosed extends Suite { + /** + * Only called reflectively. Do not use programmatically. + */ + public Enclosed(Class klass, RunnerBuilder builder) throws Throwable { + super(builder, klass, filterAbstractClasses(klass.getClasses())); + } + + private static Class[] filterAbstractClasses(final Class[] classes) { + final List> filteredList= new ArrayList>(classes.length); + + for (final Class clazz : classes) { + if (!Modifier.isAbstract(clazz.getModifiers())) { + filteredList.add(clazz); + } + } + + return filteredList.toArray(new Class[filteredList.size()]); + } +} diff --git a/src/main/java/org/junit/experimental/theories/DataPoint.java b/src/main/java/org/junit/experimental/theories/DataPoint.java new file mode 100644 index 000000000000..0a017bb5631e --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/DataPoint.java @@ -0,0 +1,56 @@ +package org.junit.experimental.theories; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotating an field or method with @DataPoint will cause the field value + * or the value returned by the method to be used as a potential parameter for + * theories in that class, when run with the + * {@link org.junit.experimental.theories.Theories Theories} runner. + *

    + * A DataPoint is only considered as a potential value for parameters for + * which its type is assignable. When multiple {@code DataPoint}s exist + * with overlapping types more control can be obtained by naming each DataPoint + * using the value of this annotation, e.g. with + * @DataPoint({"dataset1", "dataset2"}), and then specifying + * which named set to consider as potential values for each parameter using the + * {@link org.junit.experimental.theories.FromDataPoints @FromDataPoints} + * annotation. + *

    + * Parameters with no specified source (i.e. without @FromDataPoints or + * other {@link org.junit.experimental.theories.ParametersSuppliedBy + * @ParameterSuppliedBy} annotations) will use all {@code DataPoint}s that are + * assignable to the parameter type as potential values, including named sets of + * {@code DataPoint}s. + * + *

    + * @DataPoint
    + * public static String dataPoint = "value";
    + * 
    + * @DataPoint("generated")
    + * public static String generatedDataPoint() {
    + *     return "generated value";
    + * }
    + * 
    + * @Theory
    + * public void theoryMethod(String param) {
    + *     ...
    + * }
    + * 
    + * + * @see org.junit.experimental.theories.Theories + * @see org.junit.experimental.theories.Theory + * @see org.junit.experimental.theories.DataPoint + * @see org.junit.experimental.theories.FromDataPoints + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({FIELD, METHOD}) +public @interface DataPoint { + String[] value() default {}; + Class[] ignoredExceptions() default {}; +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/DataPoints.java b/src/main/java/org/junit/experimental/theories/DataPoints.java new file mode 100644 index 000000000000..b47461b388cd --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/DataPoints.java @@ -0,0 +1,64 @@ +package org.junit.experimental.theories; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotating an array or iterable-typed field or method with @DataPoints + * will cause the values in the array or iterable given to be used as potential + * parameters for theories in that class when run with the + * {@link org.junit.experimental.theories.Theories Theories} runner. + *

    + * DataPoints will only be considered as potential values for parameters for + * which their types are assignable. When multiple sets of DataPoints exist with + * overlapping types more control can be obtained by naming the DataPoints using + * the value of this annotation, e.g. with + * @DataPoints({"dataset1", "dataset2"}), and then specifying + * which named set to consider as potential values for each parameter using the + * {@link org.junit.experimental.theories.FromDataPoints @FromDataPoints} + * annotation. + *

    + * Parameters with no specified source (i.e. without @FromDataPoints or + * other {@link org.junit.experimental.theories.ParametersSuppliedBy + * @ParameterSuppliedBy} annotations) will use all DataPoints that are + * assignable to the parameter type as potential values, including named sets of + * DataPoints. + *

    + * DataPoints methods whose array types aren't assignable from the target + * parameter type (and so can't possibly return relevant values) will not be + * called when generating values for that parameter. Iterable-typed datapoints + * methods must always be called though, as this information is not available + * here after generic type erasure, so expensive methods returning iterable + * datapoints are a bad idea. + * + *

    + * @DataPoints
    + * public static String[] dataPoints = new String[] { ... };
    + * 
    + * @DataPoints
    + * public static String[] generatedDataPoints() {
    + *     return new String[] { ... };
    + * }
    + * 
    + * @Theory
    + * public void theoryMethod(String param) {
    + *     ...
    + * }
    + * 
    + * + * @see org.junit.experimental.theories.Theories + * @see org.junit.experimental.theories.Theory + * @see org.junit.experimental.theories.DataPoint + * @see org.junit.experimental.theories.FromDataPoints + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ FIELD, METHOD }) +public @interface DataPoints { + String[] value() default {}; + + Class[] ignoredExceptions() default {}; +} diff --git a/src/main/java/org/junit/experimental/theories/FromDataPoints.java b/src/main/java/org/junit/experimental/theories/FromDataPoints.java new file mode 100644 index 000000000000..2b149cae9cf1 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/FromDataPoints.java @@ -0,0 +1,54 @@ +package org.junit.experimental.theories; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.experimental.theories.internal.SpecificDataPointsSupplier; + +/** + * Annotating a parameter of a {@link org.junit.experimental.theories.Theory + * @Theory} method with @FromDataPoints will limit the + * datapoints considered as potential values for that parameter to just the + * {@link org.junit.experimental.theories.DataPoints DataPoints} with the given + * name. DataPoint names can be given as the value parameter of the + * @DataPoints annotation. + *

    + * DataPoints without names will not be considered as values for any parameters + * annotated with @FromDataPoints. + *

    + * @DataPoints
    + * public static String[] unnamed = new String[] { ... };
    + * 
    + * @DataPoints("regexes")
    + * public static String[] regexStrings = new String[] { ... };
    + * 
    + * @DataPoints({"forMatching", "alphanumeric"})
    + * public static String[] testStrings = new String[] { ... }; 
    + * 
    + * @Theory
    + * public void stringTheory(String param) {
    + *     // This will be called with every value in 'regexStrings',
    + *     // 'testStrings' and 'unnamed'.
    + * }
    + * 
    + * @Theory
    + * public void regexTheory(@FromDataPoints("regexes") String regex,
    + *                         @FromDataPoints("forMatching") String value) {
    + *     // This will be called with only the values in 'regexStrings' as 
    + *     // regex, only the values in 'testStrings' as value, and none 
    + *     // of the values in 'unnamed'.
    + * }
    + * 
    + * + * @see org.junit.experimental.theories.Theory + * @see org.junit.experimental.theories.DataPoint + * @see org.junit.experimental.theories.DataPoints + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +@ParametersSuppliedBy(SpecificDataPointsSupplier.class) +public @interface FromDataPoints { + String value(); +} diff --git a/src/main/java/org/junit/experimental/theories/ParameterSignature.java b/src/main/java/org/junit/experimental/theories/ParameterSignature.java new file mode 100644 index 000000000000..cf225835e5b4 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/ParameterSignature.java @@ -0,0 +1,134 @@ +package org.junit.experimental.theories; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ParameterSignature { + + private static final Map, Class> CONVERTABLE_TYPES_MAP = buildConvertableTypesMap(); + + private static Map, Class> buildConvertableTypesMap() { + Map, Class> map = new HashMap, Class>(); + + putSymmetrically(map, boolean.class, Boolean.class); + putSymmetrically(map, byte.class, Byte.class); + putSymmetrically(map, short.class, Short.class); + putSymmetrically(map, char.class, Character.class); + putSymmetrically(map, int.class, Integer.class); + putSymmetrically(map, long.class, Long.class); + putSymmetrically(map, float.class, Float.class); + putSymmetrically(map, double.class, Double.class); + + return Collections.unmodifiableMap(map); + } + + private static void putSymmetrically(Map map, T a, T b) { + map.put(a, b); + map.put(b, a); + } + + public static ArrayList signatures(Method method) { + return signatures(method.getParameterTypes(), method + .getParameterAnnotations()); + } + + public static List signatures(Constructor constructor) { + return signatures(constructor.getParameterTypes(), constructor + .getParameterAnnotations()); + } + + private static ArrayList signatures( + Class[] parameterTypes, Annotation[][] parameterAnnotations) { + ArrayList sigs = new ArrayList(); + for (int i = 0; i < parameterTypes.length; i++) { + sigs.add(new ParameterSignature(parameterTypes[i], + parameterAnnotations[i])); + } + return sigs; + } + + private final Class type; + + private final Annotation[] annotations; + + private ParameterSignature(Class type, Annotation[] annotations) { + this.type = type; + this.annotations = annotations; + } + + public boolean canAcceptValue(Object candidate) { + return (candidate == null) ? !type.isPrimitive() : canAcceptType(candidate.getClass()); + } + + public boolean canAcceptType(Class candidate) { + return type.isAssignableFrom(candidate) || + isAssignableViaTypeConversion(type, candidate); + } + + public boolean canPotentiallyAcceptType(Class candidate) { + return candidate.isAssignableFrom(type) || + isAssignableViaTypeConversion(candidate, type) || + canAcceptType(candidate); + } + + private boolean isAssignableViaTypeConversion(Class targetType, Class candidate) { + if (CONVERTABLE_TYPES_MAP.containsKey(candidate)) { + Class wrapperClass = CONVERTABLE_TYPES_MAP.get(candidate); + return targetType.isAssignableFrom(wrapperClass); + } else { + return false; + } + } + + public Class getType() { + return type; + } + + public List getAnnotations() { + return Arrays.asList(annotations); + } + + public boolean hasAnnotation(Class type) { + return getAnnotation(type) != null; + } + + public T findDeepAnnotation(Class annotationType) { + Annotation[] annotations2 = annotations; + return findDeepAnnotation(annotations2, annotationType, 3); + } + + private T findDeepAnnotation( + Annotation[] annotations, Class annotationType, int depth) { + if (depth == 0) { + return null; + } + for (Annotation each : annotations) { + if (annotationType.isInstance(each)) { + return annotationType.cast(each); + } + Annotation candidate = findDeepAnnotation(each.annotationType() + .getAnnotations(), annotationType, depth - 1); + if (candidate != null) { + return annotationType.cast(candidate); + } + } + + return null; + } + + public T getAnnotation(Class annotationType) { + for (Annotation each : getAnnotations()) { + if (annotationType.isInstance(each)) { + return annotationType.cast(each); + } + } + return null; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/ParameterSupplier.java b/src/main/java/org/junit/experimental/theories/ParameterSupplier.java new file mode 100644 index 000000000000..bac8b34282e2 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/ParameterSupplier.java @@ -0,0 +1,43 @@ +package org.junit.experimental.theories; + +import java.util.List; + +/** + * Abstract parent class for suppliers of input data points for theories. Extend this class to customize how {@link + * org.junit.experimental.theories.Theories Theories} runner + * finds accepted data points. Then use your class together with @ParametersSuppliedBy on input + * parameters for theories. + * + *

    + * For example, here is a supplier for values between two integers, and an annotation that references it: + * + *

    + *     @Retention(RetentionPolicy.RUNTIME)
    + *     @ParametersSuppliedBy(BetweenSupplier.class)
    + *     public @interface Between {
    + *         int first();
    + *
    + *         int last();
    + *     }
    + *
    + *     public static class BetweenSupplier extends ParameterSupplier {
    + *         @Override
    + *         public List<PotentialAssignment> getValueSources(ParameterSignature sig) {
    + *             List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();
    + *             Between annotation = (Between) sig.getSupplierAnnotation();
    + *
    + *             for (int i = annotation.first(); i <= annotation.last(); i++)
    + *                 list.add(PotentialAssignment.forValue("ints", i));
    + *             return list;
    + *         }
    + *     }
    + * 
    + *

    + * + * @see org.junit.experimental.theories.ParametersSuppliedBy + * @see org.junit.experimental.theories.Theories + * @see org.junit.experimental.theories.FromDataPoints + */ +public abstract class ParameterSupplier { + public abstract List getValueSources(ParameterSignature sig) throws Throwable; +} diff --git a/src/main/java/org/junit/experimental/theories/ParametersSuppliedBy.java b/src/main/java/org/junit/experimental/theories/ParametersSuppliedBy.java new file mode 100644 index 000000000000..15b5d9518d8a --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/ParametersSuppliedBy.java @@ -0,0 +1,48 @@ +package org.junit.experimental.theories; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.PARAMETER; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotating a {@link org.junit.experimental.theories.Theory Theory} method + * parameter with @ParametersSuppliedBy causes it to be supplied with + * values from the named + * {@link org.junit.experimental.theories.ParameterSupplier ParameterSupplier} + * when run as a theory by the {@link org.junit.experimental.theories.Theories + * Theories} runner. + * + * In addition, annotations themselves can be annotated with + * @ParametersSuppliedBy, and then used similarly. ParameterSuppliedBy + * annotations on parameters are detected by searching up this heirarchy such + * that these act as syntactic sugar, making: + * + *
    + * @ParametersSuppliedBy(Supplier.class)
    + * public @interface SpecialParameter { }
    + * 
    + * @Theory
    + * public void theoryMethod(@SpecialParameter String param) {
    + *   ...
    + * }
    + * 
    + * + * equivalent to: + * + *
    + * @Theory
    + * public void theoryMethod(@ParametersSuppliedBy(Supplier.class) String param) {
    + *   ...
    + * }
    + * 
    + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ANNOTATION_TYPE, PARAMETER }) +public @interface ParametersSuppliedBy { + + Class value(); + +} diff --git a/src/main/java/org/junit/experimental/theories/PotentialAssignment.java b/src/main/java/org/junit/experimental/theories/PotentialAssignment.java new file mode 100644 index 000000000000..18ca07a4044d --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/PotentialAssignment.java @@ -0,0 +1,52 @@ +package org.junit.experimental.theories; + +import static java.lang.String.format; + +public abstract class PotentialAssignment { + public static class CouldNotGenerateValueException extends Exception { + private static final long serialVersionUID = 1L; + + public CouldNotGenerateValueException() { + } + + public CouldNotGenerateValueException(Throwable e) { + super(e); + } + } + + public static PotentialAssignment forValue(final String name, final Object value) { + return new PotentialAssignment() { + @Override + public Object getValue() { + return value; + } + + @Override + public String toString() { + return format("[%s]", value); + } + + @Override + public String getDescription() { + String valueString; + + if (value == null) { + valueString = "null"; + } else { + try { + valueString = format("\"%s\"", value); + } catch (Throwable e) { + valueString = format("[toString() threw %s: %s]", + e.getClass().getSimpleName(), e.getMessage()); + } + } + + return format("%s ", valueString, name); + } + }; + } + + public abstract Object getValue() throws CouldNotGenerateValueException; + + public abstract String getDescription() throws CouldNotGenerateValueException; +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/Theories.java b/src/main/java/org/junit/experimental/theories/Theories.java new file mode 100644 index 000000000000..267435fdb731 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/Theories.java @@ -0,0 +1,305 @@ +package org.junit.experimental.theories; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Assume; +import org.junit.experimental.theories.internal.Assignments; +import org.junit.experimental.theories.internal.ParameterizedAssertionError; +import org.junit.internal.AssumptionViolatedException; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.Statement; +import org.junit.runners.model.TestClass; + +/** + * The Theories runner allows to test a certain functionality against a subset of an infinite set of data points. + *

    + * A Theory is a piece of functionality (a method) that is executed against several data inputs called data points. + * To make a test method a theory you mark it with @Theory. To create a data point you create a public + * field in your test class and mark it with @DataPoint. The Theories runner then executes your test + * method as many times as the number of data points declared, providing a different data point as + * the input argument on each invocation. + *

    + *

    + * A Theory differs from standard test method in that it captures some aspect of the intended behavior in possibly + * infinite numbers of scenarios which corresponds to the number of data points declared. Using assumptions and + * assertions properly together with covering multiple scenarios with different data points can make your tests more + * flexible and bring them closer to scientific theories (hence the name). + *

    + *

    + * For example: + *

    + *
    + * @RunWith(Theories.class)
    + * public class UserTest {
    + *      @DataPoint
    + *      public static String GOOD_USERNAME = "optimus";
    + *      @DataPoint
    + *      public static String USERNAME_WITH_SLASH = "optimus/prime";
    + *
    + *      @Theory
    + *      public void filenameIncludesUsername(String username) {
    + *          assumeThat(username, not(containsString("/")));
    + *          assertThat(new User(username).configFileName(), containsString(username));
    + *      }
    + * }
    + * 
    + * This makes it clear that the username should be included in the config file name, + * only if it doesn't contain a slash. Another test or theory might define what happens when a username does contain + * a slash. UserTest will attempt to run filenameIncludesUsername on every compatible data + * point defined in the class. If any of the assumptions fail, the data point is silently ignored. If all of the + * assumptions pass, but an assertion fails, the test fails. If no parameters can be found that satisfy all assumptions, the test fails. + *

    + * Defining general statements as theories allows data point reuse across a bunch of functionality tests and also + * allows automated tools to search for new, unexpected data points that expose bugs. + *

    + *

    + * The support for Theories has been absorbed from the Popper project, and more complete documentation can be found + * from that projects archived documentation. + *

    + * + * @see Archived Popper project documentation + * @see Paper on Theories + */ +public class Theories extends BlockJUnit4ClassRunner { + public Theories(Class klass) throws InitializationError { + super(klass); + } + + @Override + protected void collectInitializationErrors(List errors) { + super.collectInitializationErrors(errors); + validateDataPointFields(errors); + validateDataPointMethods(errors); + } + + private void validateDataPointFields(List errors) { + Field[] fields = getTestClass().getJavaClass().getDeclaredFields(); + + for (Field field : fields) { + if (field.getAnnotation(DataPoint.class) == null && field.getAnnotation(DataPoints.class) == null) { + continue; + } + if (!Modifier.isStatic(field.getModifiers())) { + errors.add(new Error("DataPoint field " + field.getName() + " must be static")); + } + if (!Modifier.isPublic(field.getModifiers())) { + errors.add(new Error("DataPoint field " + field.getName() + " must be public")); + } + } + } + + private void validateDataPointMethods(List errors) { + Method[] methods = getTestClass().getJavaClass().getDeclaredMethods(); + + for (Method method : methods) { + if (method.getAnnotation(DataPoint.class) == null && method.getAnnotation(DataPoints.class) == null) { + continue; + } + if (!Modifier.isStatic(method.getModifiers())) { + errors.add(new Error("DataPoint method " + method.getName() + " must be static")); + } + if (!Modifier.isPublic(method.getModifiers())) { + errors.add(new Error("DataPoint method " + method.getName() + " must be public")); + } + } + } + + @Override + protected void validateConstructor(List errors) { + validateOnlyOneConstructor(errors); + } + + @Override + protected void validateTestMethods(List errors) { + for (FrameworkMethod each : computeTestMethods()) { + if (each.getAnnotation(Theory.class) != null) { + each.validatePublicVoid(false, errors); + each.validateNoTypeParametersOnArgs(errors); + } else { + each.validatePublicVoidNoArg(false, errors); + } + + for (ParameterSignature signature : ParameterSignature.signatures(each.getMethod())) { + ParametersSuppliedBy annotation = signature.findDeepAnnotation(ParametersSuppliedBy.class); + if (annotation != null) { + validateParameterSupplier(annotation.value(), errors); + } + } + } + } + + private void validateParameterSupplier(Class supplierClass, List errors) { + Constructor[] constructors = supplierClass.getConstructors(); + + if (constructors.length != 1) { + errors.add(new Error("ParameterSupplier " + supplierClass.getName() + + " must have only one constructor (either empty or taking only a TestClass)")); + } else { + Class[] paramTypes = constructors[0].getParameterTypes(); + if (!(paramTypes.length == 0) && !paramTypes[0].equals(TestClass.class)) { + errors.add(new Error("ParameterSupplier " + supplierClass.getName() + + " constructor must take either nothing or a single TestClass instance")); + } + } + } + + @Override + protected List computeTestMethods() { + List testMethods = new ArrayList(super.computeTestMethods()); + List theoryMethods = getTestClass().getAnnotatedMethods(Theory.class); + testMethods.removeAll(theoryMethods); + testMethods.addAll(theoryMethods); + return testMethods; + } + + @Override + public Statement methodBlock(final FrameworkMethod method) { + return new TheoryAnchor(method, getTestClass()); + } + + public static class TheoryAnchor extends Statement { + private int successes = 0; + + private final FrameworkMethod testMethod; + private final TestClass testClass; + + private List fInvalidParameters = new ArrayList(); + + public TheoryAnchor(FrameworkMethod testMethod, TestClass testClass) { + this.testMethod = testMethod; + this.testClass = testClass; + } + + private TestClass getTestClass() { + return testClass; + } + + @Override + public void evaluate() throws Throwable { + runWithAssignment(Assignments.allUnassigned( + testMethod.getMethod(), getTestClass())); + + //if this test method is not annotated with Theory, then no successes is a valid case + boolean hasTheoryAnnotation = testMethod.getAnnotation(Theory.class) != null; + if (successes == 0 && hasTheoryAnnotation) { + Assert + .fail("Never found parameters that satisfied method assumptions. Violated assumptions: " + + fInvalidParameters); + } + } + + protected void runWithAssignment(Assignments parameterAssignment) + throws Throwable { + if (!parameterAssignment.isComplete()) { + runWithIncompleteAssignment(parameterAssignment); + } else { + runWithCompleteAssignment(parameterAssignment); + } + } + + protected void runWithIncompleteAssignment(Assignments incomplete) + throws Throwable { + for (PotentialAssignment source : incomplete + .potentialsForNextUnassigned()) { + runWithAssignment(incomplete.assignNext(source)); + } + } + + protected void runWithCompleteAssignment(final Assignments complete) + throws Throwable { + new BlockJUnit4ClassRunner(getTestClass().getJavaClass()) { + @Override + protected void collectInitializationErrors( + List errors) { + // do nothing + } + + @Override + public Statement methodBlock(FrameworkMethod method) { + final Statement statement = super.methodBlock(method); + return new Statement() { + @Override + public void evaluate() throws Throwable { + try { + statement.evaluate(); + handleDataPointSuccess(); + } catch (AssumptionViolatedException e) { + handleAssumptionViolation(e); + } catch (Throwable e) { + reportParameterizedError(e, complete + .getArgumentStrings(nullsOk())); + } + } + + }; + } + + @Override + protected Statement methodInvoker(FrameworkMethod method, Object test) { + return methodCompletesWithParameters(method, complete, test); + } + + @Override + public Object createTest() throws Exception { + Object[] params = complete.getConstructorArguments(); + + if (!nullsOk()) { + Assume.assumeNotNull(params); + } + + return getTestClass().getOnlyConstructor().newInstance(params); + } + }.methodBlock(testMethod).evaluate(); + } + + private Statement methodCompletesWithParameters( + final FrameworkMethod method, final Assignments complete, final Object freshInstance) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + final Object[] values = complete.getMethodArguments(); + + if (!nullsOk()) { + Assume.assumeNotNull(values); + } + + method.invokeExplosively(freshInstance, values); + } + }; + } + + protected void handleAssumptionViolation(AssumptionViolatedException e) { + fInvalidParameters.add(e); + } + + protected void reportParameterizedError(Throwable e, Object... params) + throws Throwable { + if (params.length == 0) { + throw e; + } + throw new ParameterizedAssertionError(e, testMethod.getName(), + params); + } + + private boolean nullsOk() { + Theory annotation = testMethod.getMethod().getAnnotation( + Theory.class); + if (annotation == null) { + return false; + } + return annotation.nullsAccepted(); + } + + protected void handleDataPointSuccess() { + successes++; + } + } +} diff --git a/src/main/java/org/junit/experimental/theories/Theory.java b/src/main/java/org/junit/experimental/theories/Theory.java new file mode 100644 index 000000000000..0b9f2c4121fe --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/Theory.java @@ -0,0 +1,18 @@ +package org.junit.experimental.theories; + +import static java.lang.annotation.ElementType.METHOD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks test methods that should be read as theories by the {@link org.junit.experimental.theories.Theories Theories} runner. + * + * @see org.junit.experimental.theories.Theories + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(METHOD) +public @interface Theory { + boolean nullsAccepted() default true; +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java b/src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java new file mode 100644 index 000000000000..f15fb288e4a6 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java @@ -0,0 +1,204 @@ +package org.junit.experimental.theories.internal; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.junit.Assume; +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.ParameterSupplier; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.runners.model.FrameworkField; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; + +/** + * Supplies Theory parameters based on all public members of the target class. + */ +public class AllMembersSupplier extends ParameterSupplier { + static class MethodParameterValue extends PotentialAssignment { + private final FrameworkMethod method; + + private MethodParameterValue(FrameworkMethod dataPointMethod) { + method = dataPointMethod; + } + + @Override + public Object getValue() throws CouldNotGenerateValueException { + try { + return method.invokeExplosively(null); + } catch (IllegalArgumentException e) { + throw new RuntimeException( + "unexpected: argument length is checked"); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "unexpected: getMethods returned an inaccessible method"); + } catch (Throwable throwable) { + DataPoint annotation = method.getAnnotation(DataPoint.class); + Assume.assumeTrue(annotation == null || !isAssignableToAnyOf(annotation.ignoredExceptions(), throwable)); + + throw new CouldNotGenerateValueException(throwable); + } + } + + @Override + public String getDescription() throws CouldNotGenerateValueException { + return method.getName(); + } + } + + private final TestClass clazz; + + /** + * Constructs a new supplier for {@code type} + */ + public AllMembersSupplier(TestClass type) { + clazz = type; + } + + @Override + public List getValueSources(ParameterSignature sig) throws Throwable { + List list = new ArrayList(); + + addSinglePointFields(sig, list); + addMultiPointFields(sig, list); + addSinglePointMethods(sig, list); + addMultiPointMethods(sig, list); + + return list; + } + + private void addMultiPointMethods(ParameterSignature sig, List list) throws Throwable { + for (FrameworkMethod dataPointsMethod : getDataPointsMethods(sig)) { + Class returnType = dataPointsMethod.getReturnType(); + + if ((returnType.isArray() && sig.canPotentiallyAcceptType(returnType.getComponentType())) || + Iterable.class.isAssignableFrom(returnType)) { + try { + addDataPointsValues(returnType, sig, dataPointsMethod.getName(), list, + dataPointsMethod.invokeExplosively(null)); + } catch (Throwable throwable) { + DataPoints annotation = dataPointsMethod.getAnnotation(DataPoints.class); + if (annotation != null && isAssignableToAnyOf(annotation.ignoredExceptions(), throwable)) { + return; + } else { + throw throwable; + } + } + } + } + } + + private void addSinglePointMethods(ParameterSignature sig, List list) { + for (FrameworkMethod dataPointMethod : getSingleDataPointMethods(sig)) { + if (sig.canAcceptType(dataPointMethod.getType())) { + list.add(new MethodParameterValue(dataPointMethod)); + } + } + } + + private void addMultiPointFields(ParameterSignature sig, List list) { + for (final Field field : getDataPointsFields(sig)) { + Class type = field.getType(); + addDataPointsValues(type, sig, field.getName(), list, getStaticFieldValue(field)); + } + } + + private void addSinglePointFields(ParameterSignature sig, List list) { + for (final Field field : getSingleDataPointFields(sig)) { + Object value = getStaticFieldValue(field); + + if (sig.canAcceptValue(value)) { + list.add(PotentialAssignment.forValue(field.getName(), value)); + } + } + } + + private void addDataPointsValues(Class type, ParameterSignature sig, String name, + List list, Object value) { + if (type.isArray()) { + addArrayValues(sig, name, list, value); + } + else if (Iterable.class.isAssignableFrom(type)) { + addIterableValues(sig, name, list, (Iterable) value); + } + } + + private void addArrayValues(ParameterSignature sig, String name, List list, Object array) { + for (int i = 0; i < Array.getLength(array); i++) { + Object value = Array.get(array, i); + if (sig.canAcceptValue(value)) { + list.add(PotentialAssignment.forValue(name + "[" + i + "]", value)); + } + } + } + + private void addIterableValues(ParameterSignature sig, String name, List list, Iterable iterable) { + Iterator iterator = iterable.iterator(); + int i = 0; + while (iterator.hasNext()) { + Object value = iterator.next(); + if (sig.canAcceptValue(value)) { + list.add(PotentialAssignment.forValue(name + "[" + i + "]", value)); + } + i += 1; + } + } + + private Object getStaticFieldValue(final Field field) { + try { + return field.get(null); + } catch (IllegalArgumentException e) { + throw new RuntimeException( + "unexpected: field from getClass doesn't exist on object"); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "unexpected: getFields returned an inaccessible field"); + } + } + + private static boolean isAssignableToAnyOf(Class[] typeArray, Object target) { + for (Class type : typeArray) { + if (type.isAssignableFrom(target.getClass())) { + return true; + } + } + return false; + } + + protected Collection getDataPointsMethods(ParameterSignature sig) { + return clazz.getAnnotatedMethods(DataPoints.class); + } + + protected Collection getSingleDataPointFields(ParameterSignature sig) { + List fields = clazz.getAnnotatedFields(DataPoint.class); + Collection validFields = new ArrayList(); + + for (FrameworkField frameworkField : fields) { + validFields.add(frameworkField.getField()); + } + + return validFields; + } + + protected Collection getDataPointsFields(ParameterSignature sig) { + List fields = clazz.getAnnotatedFields(DataPoints.class); + Collection validFields = new ArrayList(); + + for (FrameworkField frameworkField : fields) { + validFields.add(frameworkField.getField()); + } + + return validFields; + } + + protected Collection getSingleDataPointMethods(ParameterSignature sig) { + return clazz.getAnnotatedMethods(DataPoint.class); + } + +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/internal/Assignments.java b/src/main/java/org/junit/experimental/theories/internal/Assignments.java new file mode 100644 index 000000000000..6626797ef089 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/internal/Assignments.java @@ -0,0 +1,153 @@ +package org.junit.experimental.theories.internal; + +import static java.util.Collections.emptyList; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.ParameterSupplier; +import org.junit.experimental.theories.ParametersSuppliedBy; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException; +import org.junit.runners.model.TestClass; + +/** + * A potentially incomplete list of value assignments for a method's formal + * parameters + */ +public class Assignments { + private final List assigned; + + private final List unassigned; + + private final TestClass clazz; + + private Assignments(List assigned, + List unassigned, TestClass clazz) { + this.unassigned = unassigned; + this.assigned = assigned; + this.clazz = clazz; + } + + /** + * Returns a new assignment list for {@code testMethod}, with no params + * assigned. + */ + public static Assignments allUnassigned(Method testMethod, + TestClass testClass) { + List signatures; + signatures = ParameterSignature.signatures(testClass + .getOnlyConstructor()); + signatures.addAll(ParameterSignature.signatures(testMethod)); + return new Assignments(new ArrayList(), + signatures, testClass); + } + + public boolean isComplete() { + return unassigned.isEmpty(); + } + + public ParameterSignature nextUnassigned() { + return unassigned.get(0); + } + + public Assignments assignNext(PotentialAssignment source) { + List potentialAssignments = new ArrayList(assigned); + potentialAssignments.add(source); + + return new Assignments(potentialAssignments, unassigned.subList(1, + unassigned.size()), clazz); + } + + public Object[] getActualValues(int start, int stop) + throws CouldNotGenerateValueException { + Object[] values = new Object[stop - start]; + for (int i = start; i < stop; i++) { + values[i - start] = assigned.get(i).getValue(); + } + return values; + } + + public List potentialsForNextUnassigned() + throws Throwable { + ParameterSignature unassigned = nextUnassigned(); + List assignments = getSupplier(unassigned).getValueSources(unassigned); + + if (assignments.isEmpty()) { + assignments = generateAssignmentsFromTypeAlone(unassigned); + } + + return assignments; + } + + private List generateAssignmentsFromTypeAlone(ParameterSignature unassigned) { + Class paramType = unassigned.getType(); + + if (paramType.isEnum()) { + return new EnumSupplier(paramType).getValueSources(unassigned); + } else if (paramType.equals(Boolean.class) || paramType.equals(boolean.class)) { + return new BooleanSupplier().getValueSources(unassigned); + } else { + return emptyList(); + } + } + + private ParameterSupplier getSupplier(ParameterSignature unassigned) + throws Exception { + ParametersSuppliedBy annotation = unassigned + .findDeepAnnotation(ParametersSuppliedBy.class); + + if (annotation != null) { + return buildParameterSupplierFromClass(annotation.value()); + } else { + return new AllMembersSupplier(clazz); + } + } + + private ParameterSupplier buildParameterSupplierFromClass( + Class cls) throws Exception { + Constructor[] supplierConstructors = cls.getConstructors(); + + for (Constructor constructor : supplierConstructors) { + Class[] parameterTypes = constructor.getParameterTypes(); + if (parameterTypes.length == 1 + && parameterTypes[0].equals(TestClass.class)) { + return (ParameterSupplier) constructor.newInstance(clazz); + } + } + + return cls.newInstance(); + } + + public Object[] getConstructorArguments() + throws CouldNotGenerateValueException { + return getActualValues(0, getConstructorParameterCount()); + } + + public Object[] getMethodArguments() throws CouldNotGenerateValueException { + return getActualValues(getConstructorParameterCount(), assigned.size()); + } + + public Object[] getAllArguments() throws CouldNotGenerateValueException { + return getActualValues(0, assigned.size()); + } + + private int getConstructorParameterCount() { + List signatures = ParameterSignature + .signatures(clazz.getOnlyConstructor()); + int constructorParameterCount = signatures.size(); + return constructorParameterCount; + } + + public Object[] getArgumentStrings(boolean nullsOk) + throws CouldNotGenerateValueException { + Object[] values = new Object[assigned.size()]; + for (int i = 0; i < values.length; i++) { + values[i] = assigned.get(i).getDescription(); + } + return values; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/internal/BooleanSupplier.java b/src/main/java/org/junit/experimental/theories/internal/BooleanSupplier.java new file mode 100644 index 000000000000..5f7032fde739 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/internal/BooleanSupplier.java @@ -0,0 +1,18 @@ +package org.junit.experimental.theories.internal; + +import java.util.Arrays; +import java.util.List; + +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.ParameterSupplier; +import org.junit.experimental.theories.PotentialAssignment; + +public class BooleanSupplier extends ParameterSupplier { + + @Override + public List getValueSources(ParameterSignature sig) { + return Arrays.asList(PotentialAssignment.forValue("true", true), + PotentialAssignment.forValue("false", false)); + } + +} diff --git a/src/main/java/org/junit/experimental/theories/internal/EnumSupplier.java b/src/main/java/org/junit/experimental/theories/internal/EnumSupplier.java new file mode 100644 index 000000000000..1f3ab90844b3 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/internal/EnumSupplier.java @@ -0,0 +1,30 @@ +package org.junit.experimental.theories.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.ParameterSupplier; +import org.junit.experimental.theories.PotentialAssignment; + +public class EnumSupplier extends ParameterSupplier { + + private Class enumType; + + public EnumSupplier(Class enumType) { + this.enumType = enumType; + } + + @Override + public List getValueSources(ParameterSignature sig) { + Object[] enumValues = enumType.getEnumConstants(); + + List assignments = new ArrayList(); + for (Object value : enumValues) { + assignments.add(PotentialAssignment.forValue(value.toString(), value)); + } + + return assignments; + } + +} diff --git a/src/main/java/org/junit/experimental/theories/internal/ParameterizedAssertionError.java b/src/main/java/org/junit/experimental/theories/internal/ParameterizedAssertionError.java new file mode 100644 index 000000000000..5b9e9473f894 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/internal/ParameterizedAssertionError.java @@ -0,0 +1,50 @@ +package org.junit.experimental.theories.internal; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; + +public class ParameterizedAssertionError extends AssertionError { + private static final long serialVersionUID = 1L; + + public ParameterizedAssertionError(Throwable targetException, + String methodName, Object... params) { + super(String.format("%s(%s)", methodName, join(", ", params))); + this.initCause(targetException); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof ParameterizedAssertionError && toString().equals(obj.toString()); + } + + @Override + public int hashCode() { + return toString().hashCode(); + } + + public static String join(String delimiter, Object... params) { + return join(delimiter, Arrays.asList(params)); + } + + public static String join(String delimiter, Collection values) { + StringBuilder sb = new StringBuilder(); + Iterator iter = values.iterator(); + while (iter.hasNext()) { + Object next = iter.next(); + sb.append(stringValueOf(next)); + if (iter.hasNext()) { + sb.append(delimiter); + } + } + return sb.toString(); + } + + private static String stringValueOf(Object next) { + try { + return String.valueOf(next); + } catch (Throwable e) { + return "[toString failed]"; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/experimental/theories/internal/SpecificDataPointsSupplier.java b/src/main/java/org/junit/experimental/theories/internal/SpecificDataPointsSupplier.java new file mode 100644 index 000000000000..7b571e335941 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/internal/SpecificDataPointsSupplier.java @@ -0,0 +1,90 @@ +package org.junit.experimental.theories.internal; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.FromDataPoints; +import org.junit.experimental.theories.ParameterSignature; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; + +public class SpecificDataPointsSupplier extends AllMembersSupplier { + + public SpecificDataPointsSupplier(TestClass testClass) { + super(testClass); + } + + @Override + protected Collection getSingleDataPointFields(ParameterSignature sig) { + Collection fields = super.getSingleDataPointFields(sig); + String requestedName = sig.getAnnotation(FromDataPoints.class).value(); + + List fieldsWithMatchingNames = new ArrayList(); + + for (Field field : fields) { + String[] fieldNames = field.getAnnotation(DataPoint.class).value(); + if (Arrays.asList(fieldNames).contains(requestedName)) { + fieldsWithMatchingNames.add(field); + } + } + + return fieldsWithMatchingNames; + } + + @Override + protected Collection getDataPointsFields(ParameterSignature sig) { + Collection fields = super.getDataPointsFields(sig); + String requestedName = sig.getAnnotation(FromDataPoints.class).value(); + + List fieldsWithMatchingNames = new ArrayList(); + + for (Field field : fields) { + String[] fieldNames = field.getAnnotation(DataPoints.class).value(); + if (Arrays.asList(fieldNames).contains(requestedName)) { + fieldsWithMatchingNames.add(field); + } + } + + return fieldsWithMatchingNames; + } + + @Override + protected Collection getSingleDataPointMethods(ParameterSignature sig) { + Collection methods = super.getSingleDataPointMethods(sig); + String requestedName = sig.getAnnotation(FromDataPoints.class).value(); + + List methodsWithMatchingNames = new ArrayList(); + + for (FrameworkMethod method : methods) { + String[] methodNames = method.getAnnotation(DataPoint.class).value(); + if (Arrays.asList(methodNames).contains(requestedName)) { + methodsWithMatchingNames.add(method); + } + } + + return methodsWithMatchingNames; + } + + @Override + protected Collection getDataPointsMethods(ParameterSignature sig) { + Collection methods = super.getDataPointsMethods(sig); + String requestedName = sig.getAnnotation(FromDataPoints.class).value(); + + List methodsWithMatchingNames = new ArrayList(); + + for (FrameworkMethod method : methods) { + String[] methodNames = method.getAnnotation(DataPoints.class).value(); + if (Arrays.asList(methodNames).contains(requestedName)) { + methodsWithMatchingNames.add(method); + } + } + + return methodsWithMatchingNames; + } + +} diff --git a/src/main/java/org/junit/experimental/theories/suppliers/TestedOn.java b/src/main/java/org/junit/experimental/theories/suppliers/TestedOn.java new file mode 100644 index 000000000000..a19f20a5d0b6 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/suppliers/TestedOn.java @@ -0,0 +1,31 @@ +package org.junit.experimental.theories.suppliers; + +import static java.lang.annotation.ElementType.PARAMETER; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.experimental.theories.ParametersSuppliedBy; + +/** + * Annotating a {@link org.junit.experimental.theories.Theory Theory} method int + * parameter with @TestedOn causes it to be supplied with values from the + * ints array given when run as a theory by the + * {@link org.junit.experimental.theories.Theories Theories} runner. For + * example, the below method would be called three times by the Theories runner, + * once with each of the int parameters specified. + * + *
    + * @Theory
    + * public void shouldPassForSomeInts(@TestedOn(ints={1, 2, 3}) int param) {
    + *     ...
    + * }
    + * 
    + */ +@ParametersSuppliedBy(TestedOnSupplier.class) +@Retention(RetentionPolicy.RUNTIME) +@Target(PARAMETER) +public @interface TestedOn { + int[] ints(); +} diff --git a/src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java b/src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java new file mode 100644 index 000000000000..dc3d0c9ce326 --- /dev/null +++ b/src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java @@ -0,0 +1,25 @@ +package org.junit.experimental.theories.suppliers; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.ParameterSupplier; +import org.junit.experimental.theories.PotentialAssignment; + +/** + * @see org.junit.experimental.theories.suppliers.TestedOn + * @see org.junit.experimental.theories.ParameterSupplier + */ +public class TestedOnSupplier extends ParameterSupplier { + @Override + public List getValueSources(ParameterSignature sig) { + List list = new ArrayList(); + TestedOn testedOn = sig.getAnnotation(TestedOn.class); + int[] ints = testedOn.ints(); + for (final int i : ints) { + list.add(PotentialAssignment.forValue("ints", i)); + } + return list; + } +} diff --git a/src/main/java/org/junit/function/ThrowingRunnable.java b/src/main/java/org/junit/function/ThrowingRunnable.java new file mode 100644 index 000000000000..6e05d85c6580 --- /dev/null +++ b/src/main/java/org/junit/function/ThrowingRunnable.java @@ -0,0 +1,12 @@ +package org.junit.function; + +/** + * This interface facilitates the use of expectThrows from Java 8. It allows method references + * to void methods (that declare checked exceptions) to be passed directly into expectThrows + * without wrapping. It is not meant to be implemented directly. + * + * @since 4.13 + */ +public interface ThrowingRunnable { + void run() throws Throwable; +} diff --git a/src/main/java/org/junit/internal/ArrayComparisonFailure.java b/src/main/java/org/junit/internal/ArrayComparisonFailure.java new file mode 100644 index 000000000000..d300e7e5866b --- /dev/null +++ b/src/main/java/org/junit/internal/ArrayComparisonFailure.java @@ -0,0 +1,74 @@ +package org.junit.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; + +/** + * Thrown when two array elements differ + * + * @see Assert#assertArrayEquals(String, Object[], Object[]) + */ +public class ArrayComparisonFailure extends AssertionError { + + private static final long serialVersionUID = 1L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final List fIndices = new ArrayList(); + private final String fMessage; + private final AssertionError fCause; + + /** + * Construct a new ArrayComparisonFailure with an error text and the array's + * dimension that was not equal + * + * @param cause the exception that caused the array's content to fail the assertion test + * @param index the array position of the objects that are not equal. + * @see Assert#assertArrayEquals(String, Object[], Object[]) + */ + public ArrayComparisonFailure(String message, AssertionError cause, int index) { + this.fMessage = message; + this.fCause = cause; + initCause(fCause); + addDimension(index); + } + + public void addDimension(int index) { + fIndices.add(0, index); + } + + @Override + public synchronized Throwable getCause() { + return super.getCause() == null ? fCause : super.getCause(); + } + + @Override + public String getMessage() { + StringBuilder sb = new StringBuilder(); + if (fMessage != null) { + sb.append(fMessage); + } + sb.append("arrays first differed at element "); + for (int each : fIndices) { + sb.append("["); + sb.append(each); + sb.append("]"); + } + sb.append("; "); + sb.append(getCause().getMessage()); + return sb.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return getMessage(); + } +} diff --git a/src/main/java/org/junit/internal/AssumptionViolatedException.java b/src/main/java/org/junit/internal/AssumptionViolatedException.java new file mode 100644 index 000000000000..15c27af1b279 --- /dev/null +++ b/src/main/java/org/junit/internal/AssumptionViolatedException.java @@ -0,0 +1,111 @@ +package org.junit.internal; + +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.SelfDescribing; +import org.hamcrest.StringDescription; + +/** + * An exception class used to implement assumptions (state in which a given test + * is meaningful and should or should not be executed). A test for which an assumption + * fails should not generate a test case failure. + * + * @see org.junit.Assume + */ +public class AssumptionViolatedException extends RuntimeException implements SelfDescribing { + private static final long serialVersionUID = 2L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final String fAssumption; + private final boolean fValueMatcher; + private final Object fValue; + private final Matcher fMatcher; + + /** + * @deprecated Please use {@link org.junit.AssumptionViolatedException} instead. + */ + @Deprecated + public AssumptionViolatedException(String assumption, boolean hasValue, Object value, Matcher matcher) { + this.fAssumption = assumption; + this.fValue = value; + this.fMatcher = matcher; + this.fValueMatcher = hasValue; + + if (value instanceof Throwable) { + initCause((Throwable) value); + } + } + + /** + * An assumption exception with the given value (String or + * Throwable) and an additional failing {@link Matcher}. + * + * @deprecated Please use {@link org.junit.AssumptionViolatedException} instead. + */ + @Deprecated + public AssumptionViolatedException(Object value, Matcher matcher) { + this(null, true, value, matcher); + } + + /** + * An assumption exception with the given value (String or + * Throwable) and an additional failing {@link Matcher}. + * + * @deprecated Please use {@link org.junit.AssumptionViolatedException} instead. + */ + @Deprecated + public AssumptionViolatedException(String assumption, Object value, Matcher matcher) { + this(assumption, true, value, matcher); + } + + /** + * An assumption exception with the given message only. + * + * @deprecated Please use {@link org.junit.AssumptionViolatedException} instead. + */ + @Deprecated + public AssumptionViolatedException(String assumption) { + this(assumption, false, null, null); + } + + /** + * An assumption exception with the given message and a cause. + * + * @deprecated Please use {@link org.junit.AssumptionViolatedException} instead. + */ + @Deprecated + public AssumptionViolatedException(String assumption, Throwable e) { + this(assumption, false, null, null); + initCause(e); + } + + @Override + public String getMessage() { + return StringDescription.asString(this); + } + + public void describeTo(Description description) { + if (fAssumption != null) { + description.appendText(fAssumption); + } + + if (fValueMatcher) { + // a value was passed in when this instance was constructed; print it + if (fAssumption != null) { + description.appendText(": "); + } + + description.appendText("got: "); + description.appendValue(fValue); + + if (fMatcher != null) { + description.appendText(", expected: "); + description.appendDescriptionOf(fMatcher); + } + } + } +} diff --git a/src/main/java/org/junit/internal/Classes.java b/src/main/java/org/junit/internal/Classes.java new file mode 100644 index 000000000000..beca4453ae2f --- /dev/null +++ b/src/main/java/org/junit/internal/Classes.java @@ -0,0 +1,27 @@ +package org.junit.internal; + +import static java.lang.Thread.currentThread; + +/** + * Miscellaneous functions dealing with classes. + */ +public class Classes { + + /** + * Do not instantiate. + * @deprecated will be private soon. + */ + @Deprecated + public Classes() { + } + + /** + * Returns Class.forName for {@code className} using the current thread's class loader. + * + * @param className Name of the class. + * @throws ClassNotFoundException + */ + public static Class getClass(String className) throws ClassNotFoundException { + return Class.forName(className, true, currentThread().getContextClassLoader()); + } +} diff --git a/src/main/java/org/junit/internal/ComparisonCriteria.java b/src/main/java/org/junit/internal/ComparisonCriteria.java new file mode 100644 index 000000000000..ed1c674907cb --- /dev/null +++ b/src/main/java/org/junit/internal/ComparisonCriteria.java @@ -0,0 +1,132 @@ +package org.junit.internal; + +import java.lang.reflect.Array; +import java.util.Arrays; + +import org.junit.Assert; + +/** + * Defines criteria for finding two items "equal enough". Concrete subclasses + * may demand exact equality, or, for example, equality within a given delta. + */ +public abstract class ComparisonCriteria { + /** + * Asserts that two arrays are equal, according to the criteria defined by + * the concrete subclass. If they are not, an {@link AssertionError} is + * thrown with the given message. If expecteds and + * actuals are null, they are considered equal. + * + * @param message the identifying message for the {@link AssertionError} ( + * null okay) + * @param expecteds Object array or array of arrays (multi-dimensional array) with + * expected values. + * @param actuals Object array or array of arrays (multi-dimensional array) with + * actual values + */ + public void arrayEquals(String message, Object expecteds, Object actuals) + throws ArrayComparisonFailure { + arrayEquals(message, expecteds, actuals, true); + } + + private void arrayEquals(String message, Object expecteds, Object actuals, boolean outer) + throws ArrayComparisonFailure { + if (expecteds == actuals + || Arrays.deepEquals(new Object[] {expecteds}, new Object[] {actuals})) { + // The reflection-based loop below is potentially very slow, especially for primitive + // arrays. The deepEquals check allows us to circumvent it in the usual case where + // the arrays are exactly equal. + return; + } + String header = message == null ? "" : message + ": "; + + // Only include the user-provided message in the outer exception. + String exceptionMessage = outer ? header : ""; + + if (expecteds == null) { + Assert.fail(exceptionMessage + "expected array was null"); + } + if (actuals == null) { + Assert.fail(exceptionMessage + "actual array was null"); + } + + int actualsLength = Array.getLength(actuals); + int expectedsLength = Array.getLength(expecteds); + if (actualsLength != expectedsLength) { + header += "array lengths differed, expected.length=" + + expectedsLength + " actual.length=" + actualsLength + "; "; + } + int prefixLength = Math.min(actualsLength, expectedsLength); + + for (int i = 0; i < prefixLength; i++) { + Object expected = Array.get(expecteds, i); + Object actual = Array.get(actuals, i); + + if (isArray(expected) && isArray(actual)) { + try { + arrayEquals(message, expected, actual, false); + } catch (ArrayComparisonFailure e) { + e.addDimension(i); + throw e; + } catch (AssertionError e) { + // Array lengths differed. + throw new ArrayComparisonFailure(header, e, i); + } + } else { + try { + assertElementsEqual(expected, actual); + } catch (AssertionError e) { + throw new ArrayComparisonFailure(header, e, i); + } + } + } + + if (actualsLength != expectedsLength) { + Object expected = getToStringableArrayElement(expecteds, expectedsLength, prefixLength); + Object actual = getToStringableArrayElement(actuals, actualsLength, prefixLength); + try { + Assert.assertEquals(expected, actual); + } catch (AssertionError e) { + throw new ArrayComparisonFailure(header, e, prefixLength); + } + } + } + + private static final Object END_OF_ARRAY_SENTINEL = objectWithToString("end of array"); + + private Object getToStringableArrayElement(Object array, int length, int index) { + if (index < length) { + Object element = Array.get(array, index); + if (isArray(element)) { + return objectWithToString(componentTypeName(element.getClass()) + "[" + Array.getLength(element) + "]"); + } else { + return element; + } + } else { + return END_OF_ARRAY_SENTINEL; + } + } + + private static Object objectWithToString(final String string) { + return new Object() { + @Override + public String toString() { + return string; + } + }; + } + + private String componentTypeName(Class arrayClass) { + Class componentType = arrayClass.getComponentType(); + if (componentType.isArray()) { + return componentTypeName(componentType) + "[]"; + } else { + return componentType.getName(); + } + } + + private boolean isArray(Object expected) { + return expected != null && expected.getClass().isArray(); + } + + protected abstract void assertElementsEqual(Object expected, Object actual); +} diff --git a/src/main/java/org/junit/internal/ExactComparisonCriteria.java b/src/main/java/org/junit/internal/ExactComparisonCriteria.java new file mode 100644 index 000000000000..a267f7fe285d --- /dev/null +++ b/src/main/java/org/junit/internal/ExactComparisonCriteria.java @@ -0,0 +1,10 @@ +package org.junit.internal; + +import org.junit.Assert; + +public class ExactComparisonCriteria extends ComparisonCriteria { + @Override + protected void assertElementsEqual(Object expected, Object actual) { + Assert.assertEquals(expected, actual); + } +} diff --git a/src/main/java/org/junit/internal/InexactComparisonCriteria.java b/src/main/java/org/junit/internal/InexactComparisonCriteria.java new file mode 100644 index 000000000000..16e804b9450f --- /dev/null +++ b/src/main/java/org/junit/internal/InexactComparisonCriteria.java @@ -0,0 +1,24 @@ +package org.junit.internal; + +import org.junit.Assert; + +public class InexactComparisonCriteria extends ComparisonCriteria { + public Object fDelta; + + public InexactComparisonCriteria(double delta) { + fDelta = delta; + } + + public InexactComparisonCriteria(float delta) { + fDelta = delta; + } + + @Override + protected void assertElementsEqual(Object expected, Object actual) { + if (expected instanceof Double) { + Assert.assertEquals((Double) expected, (Double) actual, (Double) fDelta); + } else { + Assert.assertEquals((Float) expected, (Float) actual, (Float) fDelta); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/JUnitSystem.java b/src/main/java/org/junit/internal/JUnitSystem.java new file mode 100644 index 000000000000..cf0f2c055243 --- /dev/null +++ b/src/main/java/org/junit/internal/JUnitSystem.java @@ -0,0 +1,14 @@ +package org.junit.internal; + +import java.io.PrintStream; + +public interface JUnitSystem { + + /** + * Will be removed in the next major release + */ + @Deprecated + void exit(int code); + + PrintStream out(); +} diff --git a/src/main/java/org/junit/internal/MethodSorter.java b/src/main/java/org/junit/internal/MethodSorter.java new file mode 100644 index 000000000000..d8e661aa8824 --- /dev/null +++ b/src/main/java/org/junit/internal/MethodSorter.java @@ -0,0 +1,72 @@ +package org.junit.internal; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.FixMethodOrder; + +public class MethodSorter { + /** + * DEFAULT sort order + */ + public static final Comparator DEFAULT = new Comparator() { + public int compare(Method m1, Method m2) { + int i1 = m1.getName().hashCode(); + int i2 = m2.getName().hashCode(); + if (i1 != i2) { + return i1 < i2 ? -1 : 1; + } + return NAME_ASCENDING.compare(m1, m2); + } + }; + + /** + * Method name ascending lexicographic sort order, with {@link Method#toString()} as a tiebreaker + */ + public static final Comparator NAME_ASCENDING = new Comparator() { + public int compare(Method m1, Method m2) { + final int comparison = m1.getName().compareTo(m2.getName()); + if (comparison != 0) { + return comparison; + } + return m1.toString().compareTo(m2.toString()); + } + }; + + /** + * Gets declared methods of a class in a predictable order, unless @FixMethodOrder(MethodSorters.JVM) is specified. + * + * Using the JVM order is unwise since the Java platform does not + * specify any particular order, and in fact JDK 7 returns a more or less + * random order; well-written test code would not assume any order, but some + * does, and a predictable failure is better than a random failure on + * certain platforms. By default, uses an unspecified but deterministic order. + * + * @param clazz a class + * @return same as {@link Class#getDeclaredMethods} but sorted + * @see JDK + * (non-)bug #7023180 + */ + public static Method[] getDeclaredMethods(Class clazz) { + Comparator comparator = getSorter(clazz.getAnnotation(FixMethodOrder.class)); + + Method[] methods = clazz.getDeclaredMethods(); + if (comparator != null) { + Arrays.sort(methods, comparator); + } + + return methods; + } + + private MethodSorter() { + } + + private static Comparator getSorter(FixMethodOrder fixMethodOrder) { + if (fixMethodOrder == null) { + return DEFAULT; + } + + return fixMethodOrder.value().getComparator(); + } +} diff --git a/src/main/java/org/junit/internal/RealSystem.java b/src/main/java/org/junit/internal/RealSystem.java new file mode 100644 index 000000000000..e64e1fe6aa61 --- /dev/null +++ b/src/main/java/org/junit/internal/RealSystem.java @@ -0,0 +1,19 @@ +package org.junit.internal; + +import java.io.PrintStream; + +public class RealSystem implements JUnitSystem { + + /** + * Will be removed in the next major release + */ + @Deprecated + public void exit(int code) { + System.exit(code); + } + + public PrintStream out() { + return System.out; + } + +} diff --git a/src/main/java/org/junit/internal/TextListener.java b/src/main/java/org/junit/internal/TextListener.java new file mode 100644 index 000000000000..a75e80d50618 --- /dev/null +++ b/src/main/java/org/junit/internal/TextListener.java @@ -0,0 +1,101 @@ +package org.junit.internal; + +import java.io.PrintStream; +import java.text.NumberFormat; +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + +public class TextListener extends RunListener { + + private final PrintStream writer; + + public TextListener(JUnitSystem system) { + this(system.out()); + } + + public TextListener(PrintStream writer) { + this.writer = writer; + } + + @Override + public void testRunFinished(Result result) { + printHeader(result.getRunTime()); + printFailures(result); + printFooter(result); + } + + @Override + public void testStarted(Description description) { + writer.append('.'); + } + + @Override + public void testFailure(Failure failure) { + writer.append('E'); + } + + @Override + public void testIgnored(Description description) { + writer.append('I'); + } + + /* + * Internal methods + */ + + private PrintStream getWriter() { + return writer; + } + + protected void printHeader(long runTime) { + getWriter().println(); + getWriter().println("Time: " + elapsedTimeAsString(runTime)); + } + + protected void printFailures(Result result) { + List failures = result.getFailures(); + if (failures.isEmpty()) { + return; + } + if (failures.size() == 1) { + getWriter().println("There was " + failures.size() + " failure:"); + } else { + getWriter().println("There were " + failures.size() + " failures:"); + } + int i = 1; + for (Failure each : failures) { + printFailure(each, "" + i++); + } + } + + protected void printFailure(Failure each, String prefix) { + getWriter().println(prefix + ") " + each.getTestHeader()); + getWriter().print(each.getTrace()); + } + + protected void printFooter(Result result) { + if (result.wasSuccessful()) { + getWriter().println(); + getWriter().print("OK"); + getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); + + } else { + getWriter().println(); + getWriter().println("FAILURES!!!"); + getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); + } + getWriter().println(); + } + + /** + * Returns the formatted string of the elapsed time. Duplicated from + * BaseTestRunner. Fix it. + */ + protected String elapsedTimeAsString(long runTime) { + return NumberFormat.getInstance().format((double) runTime / 1000); + } +} diff --git a/src/main/java/org/junit/internal/Throwables.java b/src/main/java/org/junit/internal/Throwables.java new file mode 100644 index 000000000000..92b8d2f8d467 --- /dev/null +++ b/src/main/java/org/junit/internal/Throwables.java @@ -0,0 +1,57 @@ +package org.junit.internal; + +import java.io.PrintWriter; +import java.io.StringWriter; + +/** + * Miscellaneous functions dealing with {@code Throwable}. + * + * @author kcooney@google.com (Kevin Cooney) + * @since 4.12 + */ +public final class Throwables { + + private Throwables() { + } + + /** + * Rethrows the given {@code Throwable}, allowing the caller to + * declare that it throws {@code Exception}. This is useful when + * your callers have nothing reasonable they can do when a + * {@code Throwable} is thrown. This is declared to return {@code Exception} + * so it can be used in a {@code throw} clause: + *
    +     * try {
    +     *   doSomething();
    +     * } catch (Throwable e} {
    +     *   throw Throwables.rethrowAsException(e);
    +     * }
    +     * doSomethingLater();
    +     * 
    + * + * @param e exception to rethrow + * @return does not return anything + * @since 4.12 + */ + public static Exception rethrowAsException(Throwable e) throws Exception { + Throwables.rethrow(e); + return null; // we never get here + } + + @SuppressWarnings("unchecked") + private static void rethrow(Throwable e) throws T { + throw (T) e; + } + + /** + * Returns the stacktrace of the given Throwable as a String. + * + * @since 4.13 + */ + public static String getStacktrace(Throwable exception) { + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter); + exception.printStackTrace(writer); + return stringWriter.toString(); + } +} diff --git a/src/main/java/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java b/src/main/java/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java new file mode 100644 index 000000000000..d86ec950f655 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java @@ -0,0 +1,56 @@ +package org.junit.internal.builders; + +import java.util.Arrays; +import java.util.List; + +import org.junit.runner.Runner; +import org.junit.runners.model.RunnerBuilder; + +public class AllDefaultPossibilitiesBuilder extends RunnerBuilder { + private final boolean canUseSuiteMethod; + + public AllDefaultPossibilitiesBuilder(boolean canUseSuiteMethod) { + this.canUseSuiteMethod = canUseSuiteMethod; + } + + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + List builders = Arrays.asList( + ignoredBuilder(), + annotatedBuilder(), + suiteMethodBuilder(), + junit3Builder(), + junit4Builder()); + + for (RunnerBuilder each : builders) { + Runner runner = each.safeRunnerForClass(testClass); + if (runner != null) { + return runner; + } + } + return null; + } + + protected JUnit4Builder junit4Builder() { + return new JUnit4Builder(); + } + + protected JUnit3Builder junit3Builder() { + return new JUnit3Builder(); + } + + protected AnnotatedBuilder annotatedBuilder() { + return new AnnotatedBuilder(this); + } + + protected IgnoredBuilder ignoredBuilder() { + return new IgnoredBuilder(); + } + + protected RunnerBuilder suiteMethodBuilder() { + if (canUseSuiteMethod) { + return new SuiteMethodBuilder(); + } + return new NullBuilder(); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/AnnotatedBuilder.java b/src/main/java/org/junit/internal/builders/AnnotatedBuilder.java new file mode 100644 index 000000000000..04d7a683652f --- /dev/null +++ b/src/main/java/org/junit/internal/builders/AnnotatedBuilder.java @@ -0,0 +1,116 @@ +package org.junit.internal.builders; + +import org.junit.runner.RunWith; +import org.junit.runner.Runner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; + +import java.lang.reflect.Modifier; + + +/** + * The {@code AnnotatedBuilder} is a strategy for constructing runners for test class that have been annotated with the + * {@code @RunWith} annotation. All tests within this class will be executed using the runner that was specified within + * the annotation. + *

    + * If a runner supports inner member classes, the member classes will inherit the runner from the enclosing class, e.g.: + *

    + * @RunWith(MyRunner.class)
    + * public class MyTest {
    + *     // some tests might go here
    + *
    + *     public class MyMemberClass {
    + *         @Test
    + *         public void thisTestRunsWith_MyRunner() {
    + *             // some test logic
    + *         }
    + *
    + *         // some more tests might go here
    + *     }
    + *
    + *     @RunWith(AnotherRunner.class)
    + *     public class AnotherMemberClass {
    + *         // some tests might go here
    + *
    + *         public class DeepInnerClass {
    + *             @Test
    + *             public void thisTestRunsWith_AnotherRunner() {
    + *                 // some test logic
    + *             }
    + *         }
    + *
    + *         public class DeepInheritedClass extends SuperTest {
    + *             @Test
    + *             public void thisTestRunsWith_SuperRunner() {
    + *                 // some test logic
    + *             }
    + *         }
    + *     }
    + * }
    + *
    + * @RunWith(SuperRunner.class)
    + * public class SuperTest {
    + *     // some tests might go here
    + * }
    + * 
    + * The key points to note here are: + *
      + *
    • If there is no RunWith annotation, no runner will be created.
    • + *
    • The resolve step is inside-out, e.g. the closest RunWith annotation wins
    • + *
    • RunWith annotations are inherited and work as if the class was annotated itself.
    • + *
    • The default JUnit runner does not support inner member classes, + * so this is only valid for custom runners that support inner member classes.
    • + *
    • Custom runners with support for inner classes may or may not support RunWith annotations for member + * classes. Please refer to the custom runner documentation.
    • + *
    + * + * @see org.junit.runners.model.RunnerBuilder + * @see org.junit.runner.RunWith + * @since 4.0 + */ +public class AnnotatedBuilder extends RunnerBuilder { + private static final String CONSTRUCTOR_ERROR_FORMAT = "Custom runner class %s should have a public constructor with signature %s(Class testClass)"; + + private final RunnerBuilder suiteBuilder; + + public AnnotatedBuilder(RunnerBuilder suiteBuilder) { + this.suiteBuilder = suiteBuilder; + } + + @Override + public Runner runnerForClass(Class testClass) throws Exception { + for (Class currentTestClass = testClass; currentTestClass != null; + currentTestClass = getEnclosingClassForNonStaticMemberClass(currentTestClass)) { + RunWith annotation = currentTestClass.getAnnotation(RunWith.class); + if (annotation != null) { + return buildRunner(annotation.value(), testClass); + } + } + + return null; + } + + private Class getEnclosingClassForNonStaticMemberClass(Class currentTestClass) { + if (currentTestClass.isMemberClass() && !Modifier.isStatic(currentTestClass.getModifiers())) { + return currentTestClass.getEnclosingClass(); + } else { + return null; + } + } + + public Runner buildRunner(Class runnerClass, + Class testClass) throws Exception { + try { + return runnerClass.getConstructor(Class.class).newInstance(testClass); + } catch (NoSuchMethodException e) { + try { + return runnerClass.getConstructor(Class.class, + RunnerBuilder.class).newInstance(testClass, suiteBuilder); + } catch (NoSuchMethodException e2) { + String simpleName = runnerClass.getSimpleName(); + throw new InitializationError(String.format( + CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName)); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/IgnoredBuilder.java b/src/main/java/org/junit/internal/builders/IgnoredBuilder.java new file mode 100644 index 000000000000..71940c87fb44 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/IgnoredBuilder.java @@ -0,0 +1,15 @@ +package org.junit.internal.builders; + +import org.junit.Ignore; +import org.junit.runner.Runner; +import org.junit.runners.model.RunnerBuilder; + +public class IgnoredBuilder extends RunnerBuilder { + @Override + public Runner runnerForClass(Class testClass) { + if (testClass.getAnnotation(Ignore.class) != null) { + return new IgnoredClassRunner(testClass); + } + return null; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/IgnoredClassRunner.java b/src/main/java/org/junit/internal/builders/IgnoredClassRunner.java new file mode 100644 index 000000000000..7c8926b7fb79 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/IgnoredClassRunner.java @@ -0,0 +1,23 @@ +package org.junit.internal.builders; + +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.notification.RunNotifier; + +public class IgnoredClassRunner extends Runner { + private final Class clazz; + + public IgnoredClassRunner(Class testClass) { + clazz = testClass; + } + + @Override + public void run(RunNotifier notifier) { + notifier.fireTestIgnored(getDescription()); + } + + @Override + public Description getDescription() { + return Description.createSuiteDescription(clazz); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/JUnit3Builder.java b/src/main/java/org/junit/internal/builders/JUnit3Builder.java new file mode 100644 index 000000000000..8b6b37145533 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/JUnit3Builder.java @@ -0,0 +1,19 @@ +package org.junit.internal.builders; + +import org.junit.internal.runners.JUnit38ClassRunner; +import org.junit.runner.Runner; +import org.junit.runners.model.RunnerBuilder; + +public class JUnit3Builder extends RunnerBuilder { + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + if (isPre4Test(testClass)) { + return new JUnit38ClassRunner(testClass); + } + return null; + } + + boolean isPre4Test(Class testClass) { + return junit.framework.TestCase.class.isAssignableFrom(testClass); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/JUnit4Builder.java b/src/main/java/org/junit/internal/builders/JUnit4Builder.java new file mode 100644 index 000000000000..6a0067852cc6 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/JUnit4Builder.java @@ -0,0 +1,12 @@ +package org.junit.internal.builders; + +import org.junit.runner.Runner; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.RunnerBuilder; + +public class JUnit4Builder extends RunnerBuilder { + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + return new BlockJUnit4ClassRunner(testClass); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/NullBuilder.java b/src/main/java/org/junit/internal/builders/NullBuilder.java new file mode 100644 index 000000000000..c8d306e03dc5 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/NullBuilder.java @@ -0,0 +1,11 @@ +package org.junit.internal.builders; + +import org.junit.runner.Runner; +import org.junit.runners.model.RunnerBuilder; + +public class NullBuilder extends RunnerBuilder { + @Override + public Runner runnerForClass(Class each) throws Throwable { + return null; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java b/src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java new file mode 100644 index 000000000000..953e6cfd5474 --- /dev/null +++ b/src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java @@ -0,0 +1,24 @@ +package org.junit.internal.builders; + +import org.junit.internal.runners.SuiteMethod; +import org.junit.runner.Runner; +import org.junit.runners.model.RunnerBuilder; + +public class SuiteMethodBuilder extends RunnerBuilder { + @Override + public Runner runnerForClass(Class each) throws Throwable { + if (hasSuiteMethod(each)) { + return new SuiteMethod(each); + } + return null; + } + + public boolean hasSuiteMethod(Class testClass) { + try { + testClass.getMethod("suite"); + } catch (NoSuchMethodException e) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java b/src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java new file mode 100644 index 000000000000..9e9505da075f --- /dev/null +++ b/src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java @@ -0,0 +1,57 @@ +package org.junit.internal.matchers; + +import org.hamcrest.Description; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; + +import org.junit.internal.Throwables; + +/** + * A matcher that delegates to throwableMatcher and in addition appends the + * stacktrace of the actual Throwable in case of a mismatch. + * + * @deprecated use {@code org.hamcrest.junit.JunitMatchers.isThrowable()} + * or {@code org.hamcrest.junit.JunitMatchers.isException()} + */ +@Deprecated +public class StacktracePrintingMatcher extends + org.hamcrest.TypeSafeMatcher { + + private final Matcher throwableMatcher; + + public StacktracePrintingMatcher(Matcher throwableMatcher) { + this.throwableMatcher = throwableMatcher; + } + + public void describeTo(Description description) { + throwableMatcher.describeTo(description); + } + + @Override + protected boolean matchesSafely(T item) { + return throwableMatcher.matches(item); + } + + @Override + protected void describeMismatchSafely(T item, Description description) { + throwableMatcher.describeMismatch(item, description); + description.appendText("\nStacktrace was: "); + description.appendText(readStacktrace(item)); + } + + private String readStacktrace(Throwable throwable) { + return Throwables.getStacktrace(throwable); + } + + @Factory + public static Matcher isThrowable( + Matcher throwableMatcher) { + return new StacktracePrintingMatcher(throwableMatcher); + } + + @Factory + public static Matcher isException( + Matcher exceptionMatcher) { + return new StacktracePrintingMatcher(exceptionMatcher); + } +} diff --git a/src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java b/src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java new file mode 100644 index 000000000000..6b99004dd709 --- /dev/null +++ b/src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java @@ -0,0 +1,52 @@ +package org.junit.internal.matchers; + +import org.hamcrest.Description; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; + +/** + * A matcher that applies a delegate matcher to the cause of the current Throwable, returning the result of that + * match. + * + * @param the type of the throwable being matched + * @deprecated use {@code org.hamcrest.junit.ExpectedException} + */ +@Deprecated +public class ThrowableCauseMatcher extends + TypeSafeMatcher { + + private final Matcher causeMatcher; + + public ThrowableCauseMatcher(Matcher causeMatcher) { + this.causeMatcher = causeMatcher; + } + + public void describeTo(Description description) { + description.appendText("exception with cause "); + description.appendDescriptionOf(causeMatcher); + } + + @Override + protected boolean matchesSafely(T item) { + return causeMatcher.matches(item.getCause()); + } + + @Override + protected void describeMismatchSafely(T item, Description description) { + description.appendText("cause "); + causeMatcher.describeMismatch(item.getCause(), description); + } + + /** + * Returns a matcher that verifies that the outer exception has a cause for which the supplied matcher + * evaluates to true. + * + * @param matcher to apply to the cause of the outer exception + * @param type of the outer exception + */ + @Factory + public static Matcher hasCause(final Matcher matcher) { + return new ThrowableCauseMatcher(matcher); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java b/src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java new file mode 100644 index 000000000000..74386a862115 --- /dev/null +++ b/src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java @@ -0,0 +1,37 @@ +package org.junit.internal.matchers; + +import org.hamcrest.Description; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; + +public class ThrowableMessageMatcher extends + TypeSafeMatcher { + + private final Matcher matcher; + + public ThrowableMessageMatcher(Matcher matcher) { + this.matcher = matcher; + } + + public void describeTo(Description description) { + description.appendText("exception with message "); + description.appendDescriptionOf(matcher); + } + + @Override + protected boolean matchesSafely(T item) { + return matcher.matches(item.getMessage()); + } + + @Override + protected void describeMismatchSafely(T item, Description description) { + description.appendText("message "); + matcher.describeMismatch(item.getMessage(), description); + } + + @Factory + public static Matcher hasMessage(final Matcher matcher) { + return new ThrowableMessageMatcher(matcher); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java b/src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java new file mode 100644 index 000000000000..fb25982bbd4d --- /dev/null +++ b/src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java @@ -0,0 +1,63 @@ +package org.junit.internal.matchers; + +import java.lang.reflect.Method; + +import org.hamcrest.BaseMatcher; +import org.junit.internal.MethodSorter; + +/** + * Convenient base class for Matchers that require a non-null value of a specific type. + * This simply implements the null check, checks the type and then casts. + * + * @author Joe Walnes + * @deprecated Please use {@link org.hamcrest.TypeSafeMatcher}. + */ +@Deprecated +public abstract class TypeSafeMatcher extends BaseMatcher { + + private Class expectedType; + + /** + * Subclasses should implement this. The item will already have been checked for + * the specific type and will never be null. + */ + public abstract boolean matchesSafely(T item); + + protected TypeSafeMatcher() { + expectedType = findExpectedType(getClass()); + } + + private static Class findExpectedType(Class fromClass) { + for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { + for (Method method : MethodSorter.getDeclaredMethods(c)) { + if (isMatchesSafelyMethod(method)) { + return method.getParameterTypes()[0]; + } + } + } + + throw new Error("Cannot determine correct type for matchesSafely() method."); + } + + private static boolean isMatchesSafelyMethod(Method method) { + return "matchesSafely".equals(method.getName()) + && method.getParameterTypes().length == 1 + && !method.isSynthetic(); + } + + protected TypeSafeMatcher(Class expectedType) { + this.expectedType = expectedType; + } + + /** + * Method made final to prevent accidental override. + * If you need to override this, there's no point on extending TypeSafeMatcher. + * Instead, extend the {@link BaseMatcher}. + */ + @SuppressWarnings({"unchecked"}) + public final boolean matches(Object item) { + return item != null + && expectedType.isInstance(item) + && matchesSafely((T) item); + } +} diff --git a/src/main/java/org/junit/internal/requests/ClassRequest.java b/src/main/java/org/junit/internal/requests/ClassRequest.java new file mode 100644 index 000000000000..a4ed4830aff8 --- /dev/null +++ b/src/main/java/org/junit/internal/requests/ClassRequest.java @@ -0,0 +1,39 @@ +package org.junit.internal.requests; + +import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; +import org.junit.runner.Request; +import org.junit.runner.Runner; + +public class ClassRequest extends Request { + private final Object runnerLock = new Object(); + + /* + * We have to use the f prefix, because IntelliJ's JUnit4IdeaTestRunner uses + * reflection to access this field. See + * https://github.com/junit-team/junit4/issues/960 + */ + private final Class fTestClass; + private final boolean canUseSuiteMethod; + private volatile Runner runner; + + public ClassRequest(Class testClass, boolean canUseSuiteMethod) { + this.fTestClass = testClass; + this.canUseSuiteMethod = canUseSuiteMethod; + } + + public ClassRequest(Class testClass) { + this(testClass, true); + } + + @Override + public Runner getRunner() { + if (runner == null) { + synchronized (runnerLock) { + if (runner == null) { + runner = new AllDefaultPossibilitiesBuilder(canUseSuiteMethod).safeRunnerForClass(fTestClass); + } + } + } + return runner; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/requests/FilterRequest.java b/src/main/java/org/junit/internal/requests/FilterRequest.java new file mode 100644 index 000000000000..5f00399557c2 --- /dev/null +++ b/src/main/java/org/junit/internal/requests/FilterRequest.java @@ -0,0 +1,45 @@ +package org.junit.internal.requests; + +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.Request; +import org.junit.runner.Runner; +import org.junit.runner.manipulation.Filter; +import org.junit.runner.manipulation.NoTestsRemainException; + +/** + * A filtered {@link Request}. + */ +public final class FilterRequest extends Request { + private final Request request; + /* + * We have to use the f prefix, because IntelliJ's JUnit4IdeaTestRunner uses + * reflection to access this field. See + * https://github.com/junit-team/junit4/issues/960 + */ + private final Filter fFilter; + + /** + * Creates a filtered Request + * + * @param request a {@link Request} describing your Tests + * @param filter {@link Filter} to apply to the Tests described in + * request + */ + public FilterRequest(Request request, Filter filter) { + this.request = request; + this.fFilter = filter; + } + + @Override + public Runner getRunner() { + try { + Runner runner = request.getRunner(); + fFilter.apply(runner); + return runner; + } catch (NoTestsRemainException e) { + return new ErrorReportingRunner(Filter.class, new Exception(String + .format("No tests found matching %s from %s", fFilter + .describe(), request.toString()))); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/requests/SortingRequest.java b/src/main/java/org/junit/internal/requests/SortingRequest.java new file mode 100644 index 000000000000..77061da27d5c --- /dev/null +++ b/src/main/java/org/junit/internal/requests/SortingRequest.java @@ -0,0 +1,25 @@ +package org.junit.internal.requests; + +import java.util.Comparator; + +import org.junit.runner.Description; +import org.junit.runner.Request; +import org.junit.runner.Runner; +import org.junit.runner.manipulation.Sorter; + +public class SortingRequest extends Request { + private final Request request; + private final Comparator comparator; + + public SortingRequest(Request request, Comparator comparator) { + this.request = request; + this.comparator = comparator; + } + + @Override + public Runner getRunner() { + Runner runner = request.getRunner(); + new Sorter(comparator).apply(runner); + return runner; + } +} diff --git a/src/main/java/org/junit/internal/requests/package-info.java b/src/main/java/org/junit/internal/requests/package-info.java new file mode 100644 index 000000000000..66d2928344d2 --- /dev/null +++ b/src/main/java/org/junit/internal/requests/package-info.java @@ -0,0 +1,6 @@ +/** + * Provides implementations of {@link org.junit.runner.Request}. + * + * @since 4.0 + */ +package org.junit.internal.requests; \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/ClassRoadie.java b/src/main/java/org/junit/internal/runners/ClassRoadie.java new file mode 100644 index 000000000000..df1b45349ca6 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/ClassRoadie.java @@ -0,0 +1,81 @@ +package org.junit.internal.runners; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import org.junit.internal.AssumptionViolatedException; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +public class ClassRoadie { + private RunNotifier notifier; + private TestClass testClass; + private Description description; + private final Runnable runnable; + + public ClassRoadie(RunNotifier notifier, TestClass testClass, + Description description, Runnable runnable) { + this.notifier = notifier; + this.testClass = testClass; + this.description = description; + this.runnable = runnable; + } + + protected void runUnprotected() { + runnable.run(); + } + + protected void addFailure(Throwable targetException) { + notifier.fireTestFailure(new Failure(description, targetException)); + } + + public void runProtected() { + try { + runBefores(); + runUnprotected(); + } catch (FailedBefore e) { + } finally { + runAfters(); + } + } + + private void runBefores() throws FailedBefore { + try { + try { + List befores = testClass.getBefores(); + for (Method before : befores) { + before.invoke(null); + } + } catch (InvocationTargetException e) { + throw e.getTargetException(); + } + } catch (AssumptionViolatedException e) { + throw new FailedBefore(); + } catch (Throwable e) { + addFailure(e); + throw new FailedBefore(); + } + } + + private void runAfters() { + List afters = testClass.getAfters(); + for (Method after : afters) { + try { + after.invoke(null); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + } catch (Throwable e) { + addFailure(e); // Untested, but seems impossible + } + } + } +} diff --git a/src/main/java/org/junit/internal/runners/ErrorReportingRunner.java b/src/main/java/org/junit/internal/runners/ErrorReportingRunner.java new file mode 100644 index 000000000000..f52abab69439 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/ErrorReportingRunner.java @@ -0,0 +1,92 @@ +package org.junit.internal.runners; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.InvalidTestClassError; +import org.junit.runners.model.InitializationError; + +import static java.util.Collections.singletonList; + +public class ErrorReportingRunner extends Runner { + private final List causes; + + private final String classNames; + + public ErrorReportingRunner(Class testClass, Throwable cause) { + this(cause, testClass); + } + + public ErrorReportingRunner(Throwable cause, Class... testClasses) { + if (testClasses == null || testClasses.length == 0) { + throw new NullPointerException("Test classes cannot be null or empty"); + } + for (Class testClass : testClasses) { + if (testClass == null) { + throw new NullPointerException("Test class cannot be null"); + } + } + classNames = getClassNames(testClasses); + causes = getCauses(cause); + } + + @Override + public Description getDescription() { + Description description = Description.createSuiteDescription(classNames); + for (Throwable each : causes) { + description.addChild(describeCause()); + } + return description; + } + + @Override + public void run(RunNotifier notifier) { + for (Throwable each : causes) { + runCause(each, notifier); + } + } + + private String getClassNames(Class... testClasses) { + final StringBuilder builder = new StringBuilder(); + for (Class testClass : testClasses) { + if (builder.length() != 0) { + builder.append(", "); + } + builder.append(testClass.getName()); + } + return builder.toString(); + } + + @SuppressWarnings("deprecation") + private List getCauses(Throwable cause) { + if (cause instanceof InvocationTargetException) { + return getCauses(cause.getCause()); + } + if (cause instanceof InvalidTestClassError) { + return singletonList(cause); + } + if (cause instanceof InitializationError) { + return ((InitializationError) cause).getCauses(); + } + if (cause instanceof org.junit.internal.runners.InitializationError) { + return ((org.junit.internal.runners.InitializationError) cause) + .getCauses(); + } + return singletonList(cause); + } + + private Description describeCause() { + return Description.createTestDescription(classNames, "initializationError"); + } + + private void runCause(Throwable child, RunNotifier notifier) { + Description description = describeCause(); + notifier.fireTestStarted(description); + notifier.fireTestFailure(new Failure(description, child)); + notifier.fireTestFinished(description); + } +} diff --git a/src/main/java/org/junit/internal/runners/FailedBefore.java b/src/main/java/org/junit/internal/runners/FailedBefore.java new file mode 100644 index 000000000000..1036cb69bf0a --- /dev/null +++ b/src/main/java/org/junit/internal/runners/FailedBefore.java @@ -0,0 +1,13 @@ +package org.junit.internal.runners; + +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +class FailedBefore extends Exception { + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/InitializationError.java b/src/main/java/org/junit/internal/runners/InitializationError.java new file mode 100644 index 000000000000..484f58d26d69 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/InitializationError.java @@ -0,0 +1,37 @@ +package org.junit.internal.runners; + +import java.util.Arrays; +import java.util.List; + +/** + * Use the published version: + * {@link org.junit.runners.model.InitializationError} + * This may disappear as soon as 1 April 2009 + */ +@Deprecated +public class InitializationError extends Exception { + private static final long serialVersionUID = 1L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final List fErrors; + + public InitializationError(List errors) { + this.fErrors = errors; + } + + public InitializationError(Throwable... errors) { + this(Arrays.asList(errors)); + } + + public InitializationError(String string) { + this(new Exception(string)); + } + + public List getCauses() { + return fErrors; + } +} diff --git a/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java b/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java new file mode 100644 index 000000000000..631fcf2e5904 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java @@ -0,0 +1,180 @@ +package org.junit.internal.runners; + +import junit.extensions.TestDecorator; +import junit.framework.AssertionFailedError; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestListener; +import junit.framework.TestResult; +import junit.framework.TestSuite; +import org.junit.runner.Describable; +import org.junit.runner.Description; +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.runner.manipulation.Sortable; +import org.junit.runner.manipulation.Sorter; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +public class JUnit38ClassRunner extends Runner implements Filterable, Sortable { + private static final class OldTestClassAdaptingListener implements + TestListener { + private final RunNotifier notifier; + + private OldTestClassAdaptingListener(RunNotifier notifier) { + this.notifier = notifier; + } + + public void endTest(Test test) { + notifier.fireTestFinished(asDescription(test)); + } + + public void startTest(Test test) { + notifier.fireTestStarted(asDescription(test)); + } + + // Implement junit.framework.TestListener + public void addError(Test test, Throwable e) { + Failure failure = new Failure(asDescription(test), e); + notifier.fireTestFailure(failure); + } + + private Description asDescription(Test test) { + if (test instanceof Describable) { + Describable facade = (Describable) test; + return facade.getDescription(); + } + return Description.createTestDescription(getEffectiveClass(test), getName(test)); + } + + private Class getEffectiveClass(Test test) { + return test.getClass(); + } + + private String getName(Test test) { + if (test instanceof TestCase) { + return ((TestCase) test).getName(); + } else { + return test.toString(); + } + } + + public void addFailure(Test test, AssertionFailedError t) { + addError(test, t); + } + } + + private volatile Test test; + + public JUnit38ClassRunner(Class klass) { + this(new TestSuite(klass.asSubclass(TestCase.class))); + } + + public JUnit38ClassRunner(Test test) { + super(); + setTest(test); + } + + @Override + public void run(RunNotifier notifier) { + TestResult result = new TestResult(); + result.addListener(createAdaptingListener(notifier)); + getTest().run(result); + } + + public TestListener createAdaptingListener(final RunNotifier notifier) { + return new OldTestClassAdaptingListener(notifier); + } + + @Override + public Description getDescription() { + return makeDescription(getTest()); + } + + private static Description makeDescription(Test test) { + if (test instanceof TestCase) { + TestCase tc = (TestCase) test; + return Description.createTestDescription(tc.getClass(), tc.getName(), + getAnnotations(tc)); + } else if (test instanceof TestSuite) { + TestSuite ts = (TestSuite) test; + String name = ts.getName() == null ? createSuiteDescription(ts) : ts.getName(); + Description description = Description.createSuiteDescription(name); + int n = ts.testCount(); + for (int i = 0; i < n; i++) { + Description made = makeDescription(ts.testAt(i)); + description.addChild(made); + } + return description; + } else if (test instanceof Describable) { + Describable adapter = (Describable) test; + return adapter.getDescription(); + } else if (test instanceof TestDecorator) { + TestDecorator decorator = (TestDecorator) test; + return makeDescription(decorator.getTest()); + } else { + // This is the best we can do in this case + return Description.createSuiteDescription(test.getClass()); + } + } + + /** + * Get the annotations associated with given TestCase. + * @param test the TestCase. + */ + private static Annotation[] getAnnotations(TestCase test) { + try { + Method m = test.getClass().getMethod(test.getName()); + return m.getDeclaredAnnotations(); + } catch (SecurityException e) { + } catch (NoSuchMethodException e) { + } + return new Annotation[0]; + } + + private static String createSuiteDescription(TestSuite ts) { + int count = ts.countTestCases(); + String example = count == 0 ? "" : String.format(" [example: %s]", ts.testAt(0)); + return String.format("TestSuite with %s tests%s", count, example); + } + + public void filter(Filter filter) throws NoTestsRemainException { + if (getTest() instanceof Filterable) { + Filterable adapter = (Filterable) getTest(); + adapter.filter(filter); + } else if (getTest() instanceof TestSuite) { + TestSuite suite = (TestSuite) getTest(); + TestSuite filtered = new TestSuite(suite.getName()); + int n = suite.testCount(); + for (int i = 0; i < n; i++) { + Test test = suite.testAt(i); + if (filter.shouldRun(makeDescription(test))) { + filtered.addTest(test); + } + } + setTest(filtered); + if (filtered.testCount() == 0) { + throw new NoTestsRemainException(); + } + } + } + + public void sort(Sorter sorter) { + if (getTest() instanceof Sortable) { + Sortable adapter = (Sortable) getTest(); + adapter.sort(sorter); + } + } + + private void setTest(Test test) { + this.test = test; + } + + private Test getTest() { + return test; + } +} diff --git a/src/main/java/org/junit/internal/runners/JUnit4ClassRunner.java b/src/main/java/org/junit/internal/runners/JUnit4ClassRunner.java new file mode 100644 index 000000000000..69a23c448ccd --- /dev/null +++ b/src/main/java/org/junit/internal/runners/JUnit4ClassRunner.java @@ -0,0 +1,147 @@ +package org.junit.internal.runners; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import org.junit.runner.Description; +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.runner.manipulation.Sortable; +import org.junit.runner.manipulation.Sorter; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +public class JUnit4ClassRunner extends Runner implements Filterable, Sortable { + private final List testMethods; + private TestClass testClass; + + public JUnit4ClassRunner(Class klass) throws InitializationError { + testClass = new TestClass(klass); + testMethods = getTestMethods(); + validate(); + } + + protected List getTestMethods() { + return testClass.getTestMethods(); + } + + protected void validate() throws InitializationError { + MethodValidator methodValidator = new MethodValidator(testClass); + methodValidator.validateMethodsForDefaultRunner(); + methodValidator.assertValid(); + } + + @Override + public void run(final RunNotifier notifier) { + new ClassRoadie(notifier, testClass, getDescription(), new Runnable() { + public void run() { + runMethods(notifier); + } + }).runProtected(); + } + + protected void runMethods(final RunNotifier notifier) { + for (Method method : testMethods) { + invokeTestMethod(method, notifier); + } + } + + @Override + public Description getDescription() { + Description spec = Description.createSuiteDescription(getName(), classAnnotations()); + List testMethods = this.testMethods; + for (Method method : testMethods) { + spec.addChild(methodDescription(method)); + } + return spec; + } + + protected Annotation[] classAnnotations() { + return testClass.getJavaClass().getAnnotations(); + } + + protected String getName() { + return getTestClass().getName(); + } + + protected Object createTest() throws Exception { + return getTestClass().getConstructor().newInstance(); + } + + protected void invokeTestMethod(Method method, RunNotifier notifier) { + Description description = methodDescription(method); + Object test; + try { + test = createTest(); + } catch (InvocationTargetException e) { + testAborted(notifier, description, e.getCause()); + return; + } catch (Exception e) { + testAborted(notifier, description, e); + return; + } + TestMethod testMethod = wrapMethod(method); + new MethodRoadie(test, testMethod, notifier, description).run(); + } + + private void testAborted(RunNotifier notifier, Description description, + Throwable e) { + notifier.fireTestStarted(description); + notifier.fireTestFailure(new Failure(description, e)); + notifier.fireTestFinished(description); + } + + protected TestMethod wrapMethod(Method method) { + return new TestMethod(method, testClass); + } + + protected String testName(Method method) { + return method.getName(); + } + + protected Description methodDescription(Method method) { + return Description.createTestDescription(getTestClass().getJavaClass(), testName(method), testAnnotations(method)); + } + + protected Annotation[] testAnnotations(Method method) { + return method.getAnnotations(); + } + + public void filter(Filter filter) throws NoTestsRemainException { + for (Iterator iter = testMethods.iterator(); iter.hasNext(); ) { + Method method = iter.next(); + if (!filter.shouldRun(methodDescription(method))) { + iter.remove(); + } + } + if (testMethods.isEmpty()) { + throw new NoTestsRemainException(); + } + } + + public void sort(final Sorter sorter) { + Collections.sort(testMethods, new Comparator() { + public int compare(Method o1, Method o2) { + return sorter.compare(methodDescription(o1), methodDescription(o2)); + } + }); + } + + protected TestClass getTestClass() { + return testClass; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/MethodRoadie.java b/src/main/java/org/junit/internal/runners/MethodRoadie.java new file mode 100644 index 000000000000..01a476bd7341 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/MethodRoadie.java @@ -0,0 +1,163 @@ +package org.junit.internal.runners; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.internal.AssumptionViolatedException; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.TestTimedOutException; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +public class MethodRoadie { + private final Object test; + private final RunNotifier notifier; + private final Description description; + private TestMethod testMethod; + + public MethodRoadie(Object test, TestMethod method, RunNotifier notifier, Description description) { + this.test = test; + this.notifier = notifier; + this.description = description; + testMethod = method; + } + + public void run() { + if (testMethod.isIgnored()) { + notifier.fireTestIgnored(description); + return; + } + notifier.fireTestStarted(description); + try { + long timeout = testMethod.getTimeout(); + if (timeout > 0) { + runWithTimeout(timeout); + } else { + runTest(); + } + } finally { + notifier.fireTestFinished(description); + } + } + + private void runWithTimeout(final long timeout) { + runBeforesThenTestThenAfters(new Runnable() { + + public void run() { + ExecutorService service = Executors.newSingleThreadExecutor(); + Callable callable = new Callable() { + public Object call() throws Exception { + runTestMethod(); + return null; + } + }; + Future result = service.submit(callable); + service.shutdown(); + try { + boolean terminated = service.awaitTermination(timeout, + TimeUnit.MILLISECONDS); + if (!terminated) { + service.shutdownNow(); + } + result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation + } catch (TimeoutException e) { + addFailure(new TestTimedOutException(timeout, TimeUnit.MILLISECONDS)); + } catch (Exception e) { + addFailure(e); + } + } + }); + } + + public void runTest() { + runBeforesThenTestThenAfters(new Runnable() { + public void run() { + runTestMethod(); + } + }); + } + + public void runBeforesThenTestThenAfters(Runnable test) { + try { + runBefores(); + test.run(); + } catch (FailedBefore e) { + } catch (Exception e) { + throw new RuntimeException("test should never throw an exception to this level"); + } finally { + runAfters(); + } + } + + protected void runTestMethod() { + try { + testMethod.invoke(test); + if (testMethod.expectsException()) { + addFailure(new AssertionError("Expected exception: " + testMethod.getExpectedException().getName())); + } + } catch (InvocationTargetException e) { + Throwable actual = e.getTargetException(); + if (actual instanceof AssumptionViolatedException) { + return; + } else if (!testMethod.expectsException()) { + addFailure(actual); + } else if (testMethod.isUnexpected(actual)) { + String message = "Unexpected exception, expected<" + testMethod.getExpectedException().getName() + "> but was<" + + actual.getClass().getName() + ">"; + addFailure(new Exception(message, actual)); + } + } catch (Throwable e) { + addFailure(e); + } + } + + private void runBefores() throws FailedBefore { + try { + try { + List befores = testMethod.getBefores(); + for (Method before : befores) { + before.invoke(test); + } + } catch (InvocationTargetException e) { + throw e.getTargetException(); + } + } catch (AssumptionViolatedException e) { + throw new FailedBefore(); + } catch (Throwable e) { + addFailure(e); + throw new FailedBefore(); + } + } + + private void runAfters() { + List afters = testMethod.getAfters(); + for (Method after : afters) { + try { + after.invoke(test); + } catch (InvocationTargetException e) { + addFailure(e.getTargetException()); + } catch (Throwable e) { + addFailure(e); // Untested, but seems impossible + } + } + } + + protected void addFailure(Throwable e) { + notifier.fireTestFailure(new Failure(description, e)); + } +} + diff --git a/src/main/java/org/junit/internal/runners/MethodValidator.java b/src/main/java/org/junit/internal/runners/MethodValidator.java new file mode 100644 index 000000000000..e656ee50efea --- /dev/null +++ b/src/main/java/org/junit/internal/runners/MethodValidator.java @@ -0,0 +1,97 @@ +package org.junit.internal.runners; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +public class MethodValidator { + + private final List errors = new ArrayList(); + + private TestClass testClass; + + public MethodValidator(TestClass testClass) { + this.testClass = testClass; + } + + public void validateInstanceMethods() { + validateTestMethods(After.class, false); + validateTestMethods(Before.class, false); + validateTestMethods(Test.class, false); + + List methods = testClass.getAnnotatedMethods(Test.class); + if (methods.size() == 0) { + errors.add(new Exception("No runnable methods")); + } + } + + public void validateStaticMethods() { + validateTestMethods(BeforeClass.class, true); + validateTestMethods(AfterClass.class, true); + } + + public List validateMethodsForDefaultRunner() { + validateNoArgConstructor(); + validateStaticMethods(); + validateInstanceMethods(); + return errors; + } + + public void assertValid() throws InitializationError { + if (!errors.isEmpty()) { + throw new InitializationError(errors); + } + } + + public void validateNoArgConstructor() { + try { + testClass.getConstructor(); + } catch (Exception e) { + errors.add(new Exception("Test class should have public zero-argument constructor", e)); + } + } + + private void validateTestMethods(Class annotation, + boolean isStatic) { + List methods = testClass.getAnnotatedMethods(annotation); + + for (Method each : methods) { + if (Modifier.isStatic(each.getModifiers()) != isStatic) { + String state = isStatic ? "should" : "should not"; + errors.add(new Exception("Method " + each.getName() + "() " + + state + " be static")); + } + if (!Modifier.isPublic(each.getDeclaringClass().getModifiers())) { + errors.add(new Exception("Class " + each.getDeclaringClass().getName() + + " should be public")); + } + if (!Modifier.isPublic(each.getModifiers())) { + errors.add(new Exception("Method " + each.getName() + + " should be public")); + } + if (each.getReturnType() != Void.TYPE) { + errors.add(new Exception("Method " + each.getName() + + "should have a return type of void")); + } + if (each.getParameterTypes().length != 0) { + errors.add(new Exception("Method " + each.getName() + + " should have no parameters")); + } + } + } +} diff --git a/src/main/java/org/junit/internal/runners/SuiteMethod.java b/src/main/java/org/junit/internal/runners/SuiteMethod.java new file mode 100644 index 000000000000..e336983caa80 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/SuiteMethod.java @@ -0,0 +1,41 @@ +package org.junit.internal.runners; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import junit.framework.Test; + +/** + * Runner for use with JUnit 3.8.x-style AllTests classes + * (those that only implement a static suite() + * method). For example: + *
    + * @RunWith(AllTests.class)
    + * public class ProductTests {
    + *    public static junit.framework.Test suite() {
    + *       ...
    + *    }
    + * }
    + * 
    + */ +public class SuiteMethod extends JUnit38ClassRunner { + public SuiteMethod(Class klass) throws Throwable { + super(testFromSuiteMethod(klass)); + } + + public static Test testFromSuiteMethod(Class klass) throws Throwable { + Method suiteMethod = null; + Test suite = null; + try { + suiteMethod = klass.getMethod("suite"); + if (!Modifier.isStatic(suiteMethod.getModifiers())) { + throw new Exception(klass.getName() + ".suite() must be static"); + } + suite = (Test) suiteMethod.invoke(null); // static method + } catch (InvocationTargetException e) { + throw e.getCause(); + } + return suite; + } +} diff --git a/src/main/java/org/junit/internal/runners/TestClass.java b/src/main/java/org/junit/internal/runners/TestClass.java new file mode 100644 index 000000000000..6d24f4fb05af --- /dev/null +++ b/src/main/java/org/junit/internal/runners/TestClass.java @@ -0,0 +1,109 @@ +package org.junit.internal.runners; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.internal.MethodSorter; +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +public class TestClass { + private final Class klass; + + public TestClass(Class klass) { + this.klass = klass; + } + + public List getTestMethods() { + return getAnnotatedMethods(Test.class); + } + + List getBefores() { + return getAnnotatedMethods(BeforeClass.class); + } + + List getAfters() { + return getAnnotatedMethods(AfterClass.class); + } + + public List getAnnotatedMethods(Class annotationClass) { + List results = new ArrayList(); + for (Class eachClass : getSuperClasses(klass)) { + Method[] methods = MethodSorter.getDeclaredMethods(eachClass); + for (Method eachMethod : methods) { + Annotation annotation = eachMethod.getAnnotation(annotationClass); + if (annotation != null && !isShadowed(eachMethod, results)) { + results.add(eachMethod); + } + } + } + if (runsTopToBottom(annotationClass)) { + Collections.reverse(results); + } + return results; + } + + private boolean runsTopToBottom(Class annotation) { + return annotation.equals(Before.class) || annotation.equals(BeforeClass.class); + } + + private boolean isShadowed(Method method, List results) { + for (Method each : results) { + if (isShadowed(method, each)) { + return true; + } + } + return false; + } + + private boolean isShadowed(Method current, Method previous) { + if (!previous.getName().equals(current.getName())) { + return false; + } + if (previous.getParameterTypes().length != current.getParameterTypes().length) { + return false; + } + for (int i = 0; i < previous.getParameterTypes().length; i++) { + if (!previous.getParameterTypes()[i].equals(current.getParameterTypes()[i])) { + return false; + } + } + return true; + } + + private List> getSuperClasses(Class testClass) { + List> results = new ArrayList>(); + Class current = testClass; + while (current != null) { + results.add(current); + current = current.getSuperclass(); + } + return results; + } + + public Constructor getConstructor() throws SecurityException, NoSuchMethodException { + return klass.getConstructor(); + } + + public Class getJavaClass() { + return klass; + } + + public String getName() { + return klass.getName(); + } + +} diff --git a/src/main/java/org/junit/internal/runners/TestMethod.java b/src/main/java/org/junit/internal/runners/TestMethod.java new file mode 100644 index 000000000000..821e193d53af --- /dev/null +++ b/src/main/java/org/junit/internal/runners/TestMethod.java @@ -0,0 +1,71 @@ +package org.junit.internal.runners; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.Test.None; +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * @deprecated Included for backwards compatibility with JUnit 4.4. Will be + * removed in the next major release. Please use + * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. + */ +@Deprecated +public class TestMethod { + private final Method method; + private TestClass testClass; + + public TestMethod(Method method, TestClass testClass) { + this.method = method; + this.testClass = testClass; + } + + public boolean isIgnored() { + return method.getAnnotation(Ignore.class) != null; + } + + public long getTimeout() { + Test annotation = method.getAnnotation(Test.class); + if (annotation == null) { + return 0; + } + long timeout = annotation.timeout(); + return timeout; + } + + protected Class getExpectedException() { + Test annotation = method.getAnnotation(Test.class); + if (annotation == null || annotation.expected() == None.class) { + return null; + } else { + return annotation.expected(); + } + } + + boolean isUnexpected(Throwable exception) { + return !getExpectedException().isAssignableFrom(exception.getClass()); + } + + boolean expectsException() { + return getExpectedException() != null; + } + + List getBefores() { + return testClass.getAnnotatedMethods(Before.class); + } + + List getAfters() { + return testClass.getAnnotatedMethods(After.class); + } + + public void invoke(Object test) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { + method.invoke(test); + } + +} diff --git a/src/main/java/org/junit/internal/runners/model/EachTestNotifier.java b/src/main/java/org/junit/internal/runners/model/EachTestNotifier.java new file mode 100644 index 000000000000..c5a0764e6a47 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/model/EachTestNotifier.java @@ -0,0 +1,71 @@ +package org.junit.internal.runners.model; + +import org.junit.internal.AssumptionViolatedException; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.MultipleFailureException; + +public class EachTestNotifier { + private final RunNotifier notifier; + + private final Description description; + + public EachTestNotifier(RunNotifier notifier, Description description) { + this.notifier = notifier; + this.description = description; + } + + public void addFailure(Throwable targetException) { + if (targetException instanceof MultipleFailureException) { + addMultipleFailureException((MultipleFailureException) targetException); + } else { + notifier.fireTestFailure(new Failure(description, targetException)); + } + } + + private void addMultipleFailureException(MultipleFailureException mfe) { + for (Throwable each : mfe.getFailures()) { + addFailure(each); + } + } + + public void addFailedAssumption(AssumptionViolatedException e) { + notifier.fireTestAssumptionFailed(new Failure(description, e)); + } + + public void fireTestFinished() { + notifier.fireTestFinished(description); + } + + public void fireTestStarted() { + notifier.fireTestStarted(description); + } + + public void fireTestIgnored() { + notifier.fireTestIgnored(description); + } + + /** + * Calls {@link RunNotifier#fireTestSuiteStarted(Description)}, passing the + * {@link Description} that was passed to the {@code EachTestNotifier} constructor. + * This should be called when a test suite is about to be started. + * @see RunNotifier#fireTestSuiteStarted(Description) + * @since 4.13 + */ + public void fireTestSuiteStarted() { + notifier.fireTestSuiteStarted(description); + } + + /** + * Calls {@link RunNotifier#fireTestSuiteFinished(Description)}, passing the + * {@link Description} that was passed to the {@code EachTestNotifier} constructor. + * This should be called when a test suite has finished, whether the test suite succeeds + * or fails. + * @see RunNotifier#fireTestSuiteFinished(Description) + * @since 4.13 + */ + public void fireTestSuiteFinished() { + notifier.fireTestSuiteFinished(description); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/model/MultipleFailureException.java b/src/main/java/org/junit/internal/runners/model/MultipleFailureException.java new file mode 100644 index 000000000000..054f0428b4bc --- /dev/null +++ b/src/main/java/org/junit/internal/runners/model/MultipleFailureException.java @@ -0,0 +1,12 @@ +package org.junit.internal.runners.model; + +import java.util.List; + +@Deprecated +public class MultipleFailureException extends org.junit.runners.model.MultipleFailureException { + private static final long serialVersionUID = 1L; + + public MultipleFailureException(List errors) { + super(errors); + } +} diff --git a/src/main/java/org/junit/internal/runners/model/ReflectiveCallable.java b/src/main/java/org/junit/internal/runners/model/ReflectiveCallable.java new file mode 100644 index 000000000000..79d5c05f3af7 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/model/ReflectiveCallable.java @@ -0,0 +1,19 @@ +package org.junit.internal.runners.model; + +import java.lang.reflect.InvocationTargetException; + +/** + * When invoked, throws the exception from the reflected method, rather than + * wrapping it in an InvocationTargetException. + */ +public abstract class ReflectiveCallable { + public Object run() throws Throwable { + try { + return runReflectiveCall(); + } catch (InvocationTargetException e) { + throw e.getTargetException(); + } + } + + protected abstract Object runReflectiveCall() throws Throwable; +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/package-info.java b/src/main/java/org/junit/internal/runners/package-info.java new file mode 100644 index 000000000000..5ab7e7bd42f1 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/package-info.java @@ -0,0 +1,6 @@ +/** + * Provides implementations of {@link org.junit.runner.Runner} + * + * @since 4.0 + */ +package org.junit.internal.runners; \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/rules/RuleMemberValidator.java b/src/main/java/org/junit/internal/runners/rules/RuleMemberValidator.java new file mode 100644 index 000000000000..36de4f106297 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/rules/RuleMemberValidator.java @@ -0,0 +1,279 @@ +package org.junit.internal.runners.rules; + +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.rules.MethodRule; +import org.junit.rules.TestRule; +import org.junit.runners.model.FrameworkMember; +import org.junit.runners.model.TestClass; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * A RuleMemberValidator validates the rule fields/methods of a + * {@link org.junit.runners.model.TestClass}. All reasons for rejecting the + * {@code TestClass} are written to a list of errors. + * + *

    There are four slightly different validators. The {@link #CLASS_RULE_VALIDATOR} + * validates fields with a {@link ClassRule} annotation and the + * {@link #RULE_VALIDATOR} validates fields with a {@link Rule} annotation.

    + * + *

    The {@link #CLASS_RULE_METHOD_VALIDATOR} + * validates methods with a {@link ClassRule} annotation and the + * {@link #RULE_METHOD_VALIDATOR} validates methods with a {@link Rule} annotation.

    + */ +public class RuleMemberValidator { + /** + * Validates fields with a {@link ClassRule} annotation. + */ + public static final RuleMemberValidator CLASS_RULE_VALIDATOR = + classRuleValidatorBuilder() + .withValidator(new DeclaringClassMustBePublic()) + .withValidator(new MemberMustBeStatic()) + .withValidator(new MemberMustBePublic()) + .withValidator(new FieldMustBeATestRule()) + .build(); + /** + * Validates fields with a {@link Rule} annotation. + */ + public static final RuleMemberValidator RULE_VALIDATOR = + testRuleValidatorBuilder() + .withValidator(new MemberMustBeNonStaticOrAlsoClassRule()) + .withValidator(new MemberMustBePublic()) + .withValidator(new FieldMustBeARule()) + .build(); + /** + * Validates methods with a {@link ClassRule} annotation. + */ + public static final RuleMemberValidator CLASS_RULE_METHOD_VALIDATOR = + classRuleValidatorBuilder() + .forMethods() + .withValidator(new DeclaringClassMustBePublic()) + .withValidator(new MemberMustBeStatic()) + .withValidator(new MemberMustBePublic()) + .withValidator(new MethodMustBeATestRule()) + .build(); + + /** + * Validates methods with a {@link Rule} annotation. + */ + public static final RuleMemberValidator RULE_METHOD_VALIDATOR = + testRuleValidatorBuilder() + .forMethods() + .withValidator(new MemberMustBeNonStaticOrAlsoClassRule()) + .withValidator(new MemberMustBePublic()) + .withValidator(new MethodMustBeARule()) + .build(); + + private final Class annotation; + private final boolean methods; + private final List validatorStrategies; + + RuleMemberValidator(Builder builder) { + this.annotation = builder.annotation; + this.methods = builder.methods; + this.validatorStrategies = builder.validators; + } + + /** + * Validate the {@link org.junit.runners.model.TestClass} and adds reasons + * for rejecting the class to a list of errors. + * + * @param target the {@code TestClass} to validate. + * @param errors the list of errors. + */ + public void validate(TestClass target, List errors) { + List> members = methods ? target.getAnnotatedMethods(annotation) + : target.getAnnotatedFields(annotation); + + for (FrameworkMember each : members) { + validateMember(each, errors); + } + } + + private void validateMember(FrameworkMember member, List errors) { + for (RuleValidator strategy : validatorStrategies) { + strategy.validate(member, annotation, errors); + } + } + + private static Builder classRuleValidatorBuilder() { + return new Builder(ClassRule.class); + } + + private static Builder testRuleValidatorBuilder() { + return new Builder(Rule.class); + } + + private static class Builder { + private final Class annotation; + private boolean methods; + private final List validators; + + private Builder(Class annotation) { + this.annotation = annotation; + this.methods = false; + this.validators = new ArrayList(); + } + + Builder forMethods() { + methods = true; + return this; + } + + Builder withValidator(RuleValidator validator) { + validators.add(validator); + return this; + } + + RuleMemberValidator build() { + return new RuleMemberValidator(this); + } + } + + private static boolean isRuleType(FrameworkMember member) { + return isMethodRule(member) || isTestRule(member); + } + + private static boolean isTestRule(FrameworkMember member) { + return TestRule.class.isAssignableFrom(member.getType()); + } + + private static boolean isMethodRule(FrameworkMember member) { + return MethodRule.class.isAssignableFrom(member.getType()); + } + + /** + * Encapsulates a single piece of validation logic, used to determine if {@link org.junit.Rule} and + * {@link org.junit.ClassRule} annotations have been used correctly + */ + interface RuleValidator { + /** + * Examine the given member and add any violations of the strategy's validation logic to the given list of errors + * @param member The member (field or member) to examine + * @param annotation The type of rule annotation on the member + * @param errors The list of errors to add validation violations to + */ + void validate(FrameworkMember member, Class annotation, List errors); + } + + /** + * Requires the validated member to be non-static + */ + private static final class MemberMustBeNonStaticOrAlsoClassRule implements RuleValidator { + public void validate(FrameworkMember member, Class annotation, List errors) { + boolean isMethodRuleMember = isMethodRule(member); + boolean isClassRuleAnnotated = (member.getAnnotation(ClassRule.class) != null); + + // We disallow: + // - static MethodRule members + // - static @Rule annotated members + // - UNLESS they're also @ClassRule annotated + // Note that MethodRule cannot be annotated with @ClassRule + if (member.isStatic() && (isMethodRuleMember || !isClassRuleAnnotated)) { + String message; + if (isMethodRule(member)) { + message = "must not be static."; + } else { + message = "must not be static or it must be annotated with @ClassRule."; + } + errors.add(new ValidationError(member, annotation, message)); + } + } + } + + /** + * Requires the member to be static + */ + private static final class MemberMustBeStatic implements RuleValidator { + public void validate(FrameworkMember member, Class annotation, List errors) { + if (!member.isStatic()) { + errors.add(new ValidationError(member, annotation, + "must be static.")); + } + } + } + + /** + * Requires the member's declaring class to be public + */ + private static final class DeclaringClassMustBePublic implements RuleValidator { + public void validate(FrameworkMember member, Class annotation, List errors) { + if (!isDeclaringClassPublic(member)) { + errors.add(new ValidationError(member, annotation, + "must be declared in a public class.")); + } + } + + private boolean isDeclaringClassPublic(FrameworkMember member) { + return Modifier.isPublic(member.getDeclaringClass().getModifiers()); + } + } + + /** + * Requires the member to be public + */ + private static final class MemberMustBePublic implements RuleValidator { + public void validate(FrameworkMember member, Class annotation, List errors) { + if (!member.isPublic()) { + errors.add(new ValidationError(member, annotation, + "must be public.")); + } + } + } + + /** + * Requires the member is a field implementing {@link org.junit.rules.MethodRule} or {@link org.junit.rules.TestRule} + */ + private static final class FieldMustBeARule implements RuleValidator { + public void validate(FrameworkMember member, Class annotation, List errors) { + if (!isRuleType(member)) { + errors.add(new ValidationError(member, annotation, + "must implement MethodRule or TestRule.")); + } + } + } + + /** + * Require the member to return an implementation of {@link org.junit.rules.MethodRule} or + * {@link org.junit.rules.TestRule} + */ + private static final class MethodMustBeARule implements RuleValidator { + public void validate(FrameworkMember member, Class annotation, List errors) { + if (!isRuleType(member)) { + errors.add(new ValidationError(member, annotation, + "must return an implementation of MethodRule or TestRule.")); + } + } + } + + /** + * Require the member to return an implementation of {@link org.junit.rules.TestRule} + */ + private static final class MethodMustBeATestRule implements RuleValidator { + public void validate(FrameworkMember member, + Class annotation, List errors) { + if (!isTestRule(member)) { + errors.add(new ValidationError(member, annotation, + "must return an implementation of TestRule.")); + } + } + } + + /** + * Requires the member is a field implementing {@link org.junit.rules.TestRule} + */ + private static final class FieldMustBeATestRule implements RuleValidator { + + public void validate(FrameworkMember member, + Class annotation, List errors) { + if (!isTestRule(member)) { + errors.add(new ValidationError(member, annotation, + "must implement TestRule.")); + } + } + } +} diff --git a/src/main/java/org/junit/internal/runners/rules/ValidationError.java b/src/main/java/org/junit/internal/runners/rules/ValidationError.java new file mode 100644 index 000000000000..31bd66019e09 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/rules/ValidationError.java @@ -0,0 +1,14 @@ +package org.junit.internal.runners.rules; + +import org.junit.runners.model.FrameworkMember; + +import java.lang.annotation.Annotation; + +class ValidationError extends Exception { + + private static final long serialVersionUID = 3176511008672645574L; + + public ValidationError(FrameworkMember member, Class annotation, String suffix) { + super(String.format("The @%s '%s' %s", annotation.getSimpleName(), member.getName(), suffix)); + } +} diff --git a/src/main/java/org/junit/internal/runners/statements/ExpectException.java b/src/main/java/org/junit/internal/runners/statements/ExpectException.java new file mode 100644 index 000000000000..d0636bd78bbb --- /dev/null +++ b/src/main/java/org/junit/internal/runners/statements/ExpectException.java @@ -0,0 +1,36 @@ +package org.junit.internal.runners.statements; + +import org.junit.internal.AssumptionViolatedException; +import org.junit.runners.model.Statement; + +public class ExpectException extends Statement { + private final Statement next; + private final Class expected; + + public ExpectException(Statement next, Class expected) { + this.next = next; + this.expected = expected; + } + + @Override + public void evaluate() throws Exception { + boolean complete = false; + try { + next.evaluate(); + complete = true; + } catch (AssumptionViolatedException e) { + throw e; + } catch (Throwable e) { + if (!expected.isAssignableFrom(e.getClass())) { + String message = "Unexpected exception, expected<" + + expected.getName() + "> but was<" + + e.getClass().getName() + ">"; + throw new Exception(message, e); + } + } + if (complete) { + throw new AssertionError("Expected exception: " + + expected.getName()); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/statements/Fail.java b/src/main/java/org/junit/internal/runners/statements/Fail.java new file mode 100644 index 000000000000..e55875c14659 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/statements/Fail.java @@ -0,0 +1,16 @@ +package org.junit.internal.runners.statements; + +import org.junit.runners.model.Statement; + +public class Fail extends Statement { + private final Throwable error; + + public Fail(Throwable e) { + error = e; + } + + @Override + public void evaluate() throws Throwable { + throw error; + } +} diff --git a/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java b/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java new file mode 100644 index 000000000000..922c96924849 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java @@ -0,0 +1,287 @@ +package org.junit.internal.runners.statements; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; +import org.junit.runners.model.TestTimedOutException; + +public class FailOnTimeout extends Statement { + private final Statement originalStatement; + private final TimeUnit timeUnit; + private final long timeout; + private final boolean lookForStuckThread; + + /** + * Returns a new builder for building an instance. + * + * @since 4.12 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Creates an instance wrapping the given statement with the given timeout in milliseconds. + * + * @param statement the statement to wrap + * @param timeoutMillis the timeout in milliseconds + * @deprecated use {@link #builder()} instead. + */ + @Deprecated + public FailOnTimeout(Statement statement, long timeoutMillis) { + this(builder().withTimeout(timeoutMillis, TimeUnit.MILLISECONDS), statement); + } + + private FailOnTimeout(Builder builder, Statement statement) { + originalStatement = statement; + timeout = builder.timeout; + timeUnit = builder.unit; + lookForStuckThread = builder.lookForStuckThread; + } + + /** + * Builder for {@link FailOnTimeout}. + * + * @since 4.12 + */ + public static class Builder { + private boolean lookForStuckThread = false; + private long timeout = 0; + private TimeUnit unit = TimeUnit.SECONDS; + + private Builder() { + } + + /** + * Specifies the time to wait before timing out the test. + * + *

    If this is not called, or is called with a {@code timeout} of + * {@code 0}, the returned {@code Statement} will wait forever for the + * test to complete, however the test will still launch from a separate + * thread. This can be useful for disabling timeouts in environments + * where they are dynamically set based on some property. + * + * @param timeout the maximum time to wait + * @param unit the time unit of the {@code timeout} argument + * @return {@code this} for method chaining. + */ + public Builder withTimeout(long timeout, TimeUnit unit) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout must be non-negative"); + } + if (unit == null) { + throw new NullPointerException("TimeUnit cannot be null"); + } + this.timeout = timeout; + this.unit = unit; + return this; + } + + /** + * Specifies whether to look for a stuck thread. If a timeout occurs and this + * feature is enabled, the test will look for a thread that appears to be stuck + * and dump its backtrace. This feature is experimental. Behavior may change + * after the 4.12 release in response to feedback. + * + * @param enable {@code true} to enable the feature + * @return {@code this} for method chaining. + */ + public Builder withLookingForStuckThread(boolean enable) { + this.lookForStuckThread = enable; + return this; + } + + /** + * Builds a {@link FailOnTimeout} instance using the values in this builder, + * wrapping the given statement. + * + * @param statement + */ + public FailOnTimeout build(Statement statement) { + if (statement == null) { + throw new NullPointerException("statement cannot be null"); + } + return new FailOnTimeout(this, statement); + } + } + + @Override + public void evaluate() throws Throwable { + CallableStatement callable = new CallableStatement(); + FutureTask task = new FutureTask(callable); + ThreadGroup threadGroup = new ThreadGroup("FailOnTimeoutGroup"); + Thread thread = new Thread(threadGroup, task, "Time-limited test"); + thread.setDaemon(true); + thread.start(); + callable.awaitStarted(); + Throwable throwable = getResult(task, thread); + if (throwable != null) { + throw throwable; + } + } + + /** + * Wait for the test task, returning the exception thrown by the test if the + * test failed, an exception indicating a timeout if the test timed out, or + * {@code null} if the test passed. + */ + private Throwable getResult(FutureTask task, Thread thread) { + try { + if (timeout > 0) { + return task.get(timeout, timeUnit); + } else { + return task.get(); + } + } catch (InterruptedException e) { + return e; // caller will re-throw; no need to call Thread.interrupt() + } catch (ExecutionException e) { + // test failed; have caller re-throw the exception thrown by the test + return e.getCause(); + } catch (TimeoutException e) { + return createTimeoutException(thread); + } + } + + private Exception createTimeoutException(Thread thread) { + StackTraceElement[] stackTrace = thread.getStackTrace(); + final Thread stuckThread = lookForStuckThread ? getStuckThread(thread) : null; + Exception currThreadException = new TestTimedOutException(timeout, timeUnit); + if (stackTrace != null) { + currThreadException.setStackTrace(stackTrace); + thread.interrupt(); + } + if (stuckThread != null) { + Exception stuckThreadException = + new Exception("Appears to be stuck in thread " + + stuckThread.getName()); + stuckThreadException.setStackTrace(getStackTrace(stuckThread)); + return new MultipleFailureException( + Arrays.asList(currThreadException, stuckThreadException)); + } else { + return currThreadException; + } + } + + /** + * Retrieves the stack trace for a given thread. + * @param thread The thread whose stack is to be retrieved. + * @return The stack trace; returns a zero-length array if the thread has + * terminated or the stack cannot be retrieved for some other reason. + */ + private StackTraceElement[] getStackTrace(Thread thread) { + try { + return thread.getStackTrace(); + } catch (SecurityException e) { + return new StackTraceElement[0]; + } + } + + /** + * Determines whether the test appears to be stuck in some thread other than + * the "main thread" (the one created to run the test). This feature is experimental. + * Behavior may change after the 4.12 release in response to feedback. + * @param mainThread The main thread created by {@code evaluate()} + * @return The thread which appears to be causing the problem, if different from + * {@code mainThread}, or {@code null} if the main thread appears to be the + * problem or if the thread cannot be determined. The return value is never equal + * to {@code mainThread}. + */ + private Thread getStuckThread(Thread mainThread) { + List threadsInGroup = getThreadsInGroup(mainThread.getThreadGroup()); + if (threadsInGroup.isEmpty()) { + return null; + } + + // Now that we have all the threads in the test's thread group: Assume that + // any thread we're "stuck" in is RUNNABLE. Look for all RUNNABLE threads. + // If just one, we return that (unless it equals threadMain). If there's more + // than one, pick the one that's using the most CPU time, if this feature is + // supported. + Thread stuckThread = null; + long maxCpuTime = 0; + for (Thread thread : threadsInGroup) { + if (thread.getState() == Thread.State.RUNNABLE) { + long threadCpuTime = cpuTime(thread); + if (stuckThread == null || threadCpuTime > maxCpuTime) { + stuckThread = thread; + maxCpuTime = threadCpuTime; + } + } + } + return (stuckThread == mainThread) ? null : stuckThread; + } + + /** + * Returns all active threads belonging to a thread group. + * @param group The thread group. + * @return The active threads in the thread group. The result should be a + * complete list of the active threads at some point in time. Returns an empty list + * if this cannot be determined, e.g. because new threads are being created at an + * extremely fast rate. + */ + private List getThreadsInGroup(ThreadGroup group) { + final int activeThreadCount = group.activeCount(); // this is just an estimate + int threadArraySize = Math.max(activeThreadCount * 2, 100); + for (int loopCount = 0; loopCount < 5; loopCount++) { + Thread[] threads = new Thread[threadArraySize]; + int enumCount = group.enumerate(threads); + if (enumCount < threadArraySize) { + return Arrays.asList(threads).subList(0, enumCount); + } + // if there are too many threads to fit into the array, enumerate's result + // is >= the array's length; therefore we can't trust that it returned all + // the threads. Try again. + threadArraySize += 100; + } + // threads are proliferating too fast for us. Bail before we get into + // trouble. + return Collections.emptyList(); + } + + /** + * Returns the CPU time used by a thread, if possible. + * @param thr The thread to query. + * @return The CPU time used by {@code thr}, or 0 if it cannot be determined. + */ + private long cpuTime(Thread thr) { + ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); + if (mxBean.isThreadCpuTimeSupported()) { + try { + return mxBean.getThreadCpuTime(thr.getId()); + } catch (UnsupportedOperationException e) { + } + } + return 0; + } + + private class CallableStatement implements Callable { + private final CountDownLatch startLatch = new CountDownLatch(1); + + public Throwable call() throws Exception { + try { + startLatch.countDown(); + originalStatement.evaluate(); + } catch (Exception e) { + throw e; + } catch (Throwable e) { + return e; + } + return null; + } + + public void awaitStarted() throws InterruptedException { + startLatch.await(); + } + } +} diff --git a/src/main/java/org/junit/internal/runners/statements/InvokeMethod.java b/src/main/java/org/junit/internal/runners/statements/InvokeMethod.java new file mode 100644 index 000000000000..68c0545b1422 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/statements/InvokeMethod.java @@ -0,0 +1,19 @@ +package org.junit.internal.runners.statements; + +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.Statement; + +public class InvokeMethod extends Statement { + private final FrameworkMethod testMethod; + private final Object target; + + public InvokeMethod(FrameworkMethod testMethod, Object target) { + this.testMethod = testMethod; + this.target = target; + } + + @Override + public void evaluate() throws Throwable { + testMethod.invokeExplosively(target); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/statements/RunAfters.java b/src/main/java/org/junit/internal/runners/statements/RunAfters.java new file mode 100644 index 000000000000..7512a7d61f40 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/statements/RunAfters.java @@ -0,0 +1,41 @@ +package org.junit.internal.runners.statements; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +public class RunAfters extends Statement { + private final Statement next; + + private final Object target; + + private final List afters; + + public RunAfters(Statement next, List afters, Object target) { + this.next = next; + this.afters = afters; + this.target = target; + } + + @Override + public void evaluate() throws Throwable { + List errors = new ArrayList(); + try { + next.evaluate(); + } catch (Throwable e) { + errors.add(e); + } finally { + for (FrameworkMethod each : afters) { + try { + each.invokeExplosively(target); + } catch (Throwable e) { + errors.add(e); + } + } + } + MultipleFailureException.assertEmpty(errors); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/internal/runners/statements/RunBefores.java b/src/main/java/org/junit/internal/runners/statements/RunBefores.java new file mode 100644 index 000000000000..238fbe7d07a5 --- /dev/null +++ b/src/main/java/org/junit/internal/runners/statements/RunBefores.java @@ -0,0 +1,28 @@ +package org.junit.internal.runners.statements; + +import java.util.List; + +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.Statement; + +public class RunBefores extends Statement { + private final Statement next; + + private final Object target; + + private final List befores; + + public RunBefores(Statement next, List befores, Object target) { + this.next = next; + this.befores = befores; + this.target = target; + } + + @Override + public void evaluate() throws Throwable { + for (FrameworkMethod before : befores) { + before.invokeExplosively(target); + } + next.evaluate(); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/matchers/JUnitMatchers.java b/src/main/java/org/junit/matchers/JUnitMatchers.java new file mode 100644 index 000000000000..47897c5ae044 --- /dev/null +++ b/src/main/java/org/junit/matchers/JUnitMatchers.java @@ -0,0 +1,115 @@ +package org.junit.matchers; + +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matcher; +import org.hamcrest.core.CombinableMatcher.CombinableBothMatcher; +import org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher; +import org.junit.internal.matchers.StacktracePrintingMatcher; + +/** + * Convenience import class: these are useful matchers for use with the assertThat method, but they are + * not currently included in the basic CoreMatchers class from hamcrest. + * + * @since 4.4 + * @deprecated use {@code org.hamcrest.junit.JUnitMatchers} + */ +@Deprecated +public class JUnitMatchers { + /** + * @return A matcher matching any collection containing element + * @deprecated Please use {@link CoreMatchers#hasItem(Object)} instead. + */ + @Deprecated + public static Matcher> hasItem(T element) { + return CoreMatchers.hasItem(element); + } + + /** + * @return A matcher matching any collection containing an element matching elementMatcher + * @deprecated Please use {@link CoreMatchers#hasItem(Matcher)} instead. + */ + @Deprecated + public static Matcher> hasItem(Matcher elementMatcher) { + return CoreMatchers.hasItem(elementMatcher); + } + + /** + * @return A matcher matching any collection containing every element in elements + * @deprecated Please use {@link CoreMatchers#hasItems(Object...)} instead. + */ + @Deprecated + public static Matcher> hasItems(T... elements) { + return CoreMatchers.hasItems(elements); + } + + /** + * @return A matcher matching any collection containing at least one element that matches + * each matcher in elementMatcher (this may be one element matching all matchers, + * or different elements matching each matcher) + * @deprecated Please use {@link CoreMatchers#hasItems(Matcher...)} instead. + */ + @Deprecated + public static Matcher> hasItems(Matcher... elementMatchers) { + return CoreMatchers.hasItems(elementMatchers); + } + + /** + * @return A matcher matching any collection in which every element matches elementMatcher + * @deprecated Please use {@link CoreMatchers#everyItem(Matcher)} instead. + */ + @Deprecated + public static Matcher> everyItem(final Matcher elementMatcher) { + return CoreMatchers.everyItem(elementMatcher); + } + + /** + * @return a matcher matching any string that contains substring + * @deprecated Please use {@link CoreMatchers#containsString(String)} instead. + */ + @Deprecated + public static Matcher containsString(java.lang.String substring) { + return CoreMatchers.containsString(substring); + } + + /** + * This is useful for fluently combining matchers that must both pass. For example: + *

    +     *   assertThat(string, both(containsString("a")).and(containsString("b")));
    +     * 
    + * + * @deprecated Please use {@link CoreMatchers#both(Matcher)} instead. + */ + @Deprecated + public static CombinableBothMatcher both(Matcher matcher) { + return CoreMatchers.both(matcher); + } + + /** + * This is useful for fluently combining matchers where either may pass, for example: + *
    +     *   assertThat(string, either(containsString("a")).or(containsString("b")));
    +     * 
    + * + * @deprecated Please use {@link CoreMatchers#either(Matcher)} instead. + */ + @Deprecated + public static CombinableEitherMatcher either(Matcher matcher) { + return CoreMatchers.either(matcher); + } + + /** + * @return A matcher that delegates to throwableMatcher and in addition + * appends the stacktrace of the actual Throwable in case of a mismatch. + */ + public static Matcher isThrowable(Matcher throwableMatcher) { + return StacktracePrintingMatcher.isThrowable(throwableMatcher); + } + + /** + * @return A matcher that delegates to exceptionMatcher and in addition + * appends the stacktrace of the actual Exception in case of a mismatch. + */ + public static Matcher isException(Matcher exceptionMatcher) { + return StacktracePrintingMatcher.isException(exceptionMatcher); + } +} diff --git a/src/main/java/org/junit/matchers/package-info.java b/src/main/java/org/junit/matchers/package-info.java new file mode 100644 index 000000000000..71aca349009a --- /dev/null +++ b/src/main/java/org/junit/matchers/package-info.java @@ -0,0 +1,9 @@ +/** + * Provides useful additional {@link org.hamcrest.Matcher}s for use with + * the {@link org.junit.Assert#assertThat(Object, org.hamcrest.Matcher)} + * statement + * + * @since 4.0 + * @see org.junit.matchers.JUnitMatchers + */ +package org.junit.matchers; \ No newline at end of file diff --git a/src/main/java/org/junit/package-info.java b/src/main/java/org/junit/package-info.java new file mode 100644 index 000000000000..fb12f2598f0b --- /dev/null +++ b/src/main/java/org/junit/package-info.java @@ -0,0 +1,8 @@ +/** + * Provides JUnit core classes and annotations. + * + * Corresponds to junit.framework in Junit 3.x. + * + * @since 4.0 + */ +package org.junit; \ No newline at end of file diff --git a/src/main/java/org/junit/rules/DisableOnDebug.java b/src/main/java/org/junit/rules/DisableOnDebug.java new file mode 100644 index 000000000000..afa6dee7d735 --- /dev/null +++ b/src/main/java/org/junit/rules/DisableOnDebug.java @@ -0,0 +1,127 @@ +package org.junit.rules; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * The {@code DisableOnDebug} Rule allows you to label certain rules to be + * disabled when debugging. + *

    + * The most illustrative use case is for tests that make use of the + * {@link Timeout} rule, when ran in debug mode the test may terminate on + * timeout abruptly during debugging. Developers may disable the timeout, or + * increase the timeout by making a code change on tests that need debugging and + * remember revert the change afterwards or rules such as {@link Timeout} that + * may be disabled during debugging may be wrapped in a {@code DisableOnDebug}. + *

    + * The important benefit of this feature is that you can disable such rules + * without any making any modifications to your test class to remove them during + * debugging. + *

    + * This does nothing to tackle timeouts or time sensitive code under test when + * debugging and may make this less useful in such circumstances. + *

    + * Example usage: + * + *

    + * public static class DisableTimeoutOnDebugSampleTest {
    + * 
    + *     @Rule
    + *     public TestRule timeout = new DisableOnDebug(new Timeout(20));
    + * 
    + *     @Test
    + *     public void myTest() {
    + *         int i = 0;
    + *         assertEquals(0, i); // suppose you had a break point here to inspect i
    + *     }
    + * }
    + * 
    + * + * @since 4.12 + */ +public class DisableOnDebug implements TestRule { + private final TestRule rule; + private final boolean debugging; + + /** + * Create a {@code DisableOnDebug} instance with the timeout specified in + * milliseconds. + * + * @param rule to disable during debugging + */ + public DisableOnDebug(TestRule rule) { + this(rule, ManagementFactory.getRuntimeMXBean() + .getInputArguments()); + } + + /** + * Visible for testing purposes only. + * + * @param rule the rule to disable during debugging + * @param inputArguments + * arguments provided to the Java runtime + */ + DisableOnDebug(TestRule rule, List inputArguments) { + this.rule = rule; + debugging = isDebugging(inputArguments); + } + + /** + * @see TestRule#apply(Statement, Description) + */ + public Statement apply(Statement base, Description description) { + if (debugging) { + return base; + } else { + return rule.apply(base, description); + } + } + + /** + * Parses arguments passed to the runtime environment for debug flags + *

    + * Options specified in: + *

      + *
    • + * javase-6
    • + *
    • javase-7
    • + *
    • javase-8
    • + * + * + * @param arguments + * the arguments passed to the runtime environment, usually this + * will be {@link RuntimeMXBean#getInputArguments()} + * @return true if the current JVM was started in debug mode, false + * otherwise. + */ + private static boolean isDebugging(List arguments) { + for (final String argument : arguments) { + if ("-Xdebug".equals(argument)) { + return true; + } else if (argument.startsWith("-agentlib:jdwp")) { + return true; + } + } + return false; + } + + /** + * Returns {@code true} if the JVM is in debug mode. This method may be used + * by test classes to take additional action to disable code paths that + * interfere with debugging if required. + * + * @return {@code true} if the current JVM is in debug mode, {@code false} + * otherwise + */ + public boolean isDebugging() { + return debugging; + } + +} diff --git a/src/main/java/org/junit/rules/ErrorCollector.java b/src/main/java/org/junit/rules/ErrorCollector.java new file mode 100644 index 000000000000..5d5ea8b77db4 --- /dev/null +++ b/src/main/java/org/junit/rules/ErrorCollector.java @@ -0,0 +1,111 @@ +package org.junit.rules; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertThrows; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import org.junit.function.ThrowingRunnable; + +import org.hamcrest.Matcher; +import org.junit.runners.model.MultipleFailureException; + +/** + * The ErrorCollector rule allows execution of a test to continue after the + * first problem is found (for example, to collect _all_ the incorrect rows in a + * table, and report them all at once): + * + *
      + * 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"));
      + *      collector.checkThat(getResult(), not(containsString("ERROR!")));
      + *      // all lines will run, and then a combined failure logged at the end.
      + *     }
      + * }
      + * 
      + * + * @since 4.7 + */ +public class ErrorCollector extends Verifier { + private List errors = new ArrayList(); + + @Override + protected void verify() throws Throwable { + MultipleFailureException.assertEmpty(errors); + } + + /** + * Adds a Throwable to the table. Execution continues, but the test will fail at the end. + */ + public void addError(Throwable error) { + errors.add(error); + } + + /** + * Adds a failure to the table if {@code matcher} does not match {@code value}. + * Execution continues, but the test will fail at the end if the match fails. + * + * @deprecated use {@code org.hamcrest.junit.ErrorCollector.checkThat()} + */ + @Deprecated + public void checkThat(final T value, final Matcher matcher) { + checkThat("", value, matcher); + } + + /** + * Adds a failure with the given {@code reason} + * to the table if {@code matcher} does not match {@code value}. + * Execution continues, but the test will fail at the end if the match fails. + * + * @deprecated use {@code org.hamcrest.junit.ErrorCollector.checkThat()} + */ + @Deprecated + public void checkThat(final String reason, final T value, final Matcher matcher) { + checkSucceeds(new Callable() { + public Object call() throws Exception { + assertThat(reason, value, matcher); + return value; + } + }); + } + + /** + * Adds to the table the exception, if any, thrown from {@code callable}. + * Execution continues, but the test will fail at the end if + * {@code callable} threw an exception. + */ + public T checkSucceeds(Callable callable) { + try { + return callable.call(); + } catch (Throwable e) { + addError(e); + return null; + } + } + + /** + * Adds a failure to the table if {@code runnable} does not throw an + * exception of type {@code expectedThrowable} when executed. + * Execution continues, but the test will fail at the end if the runnable + * does not throw an exception, or if it throws a different exception. + * + * @param expectedThrowable the expected type of the exception + * @param runnable a function that is expected to throw an exception when executed + * @since 4.13 + */ + public void checkThrows(Class expectedThrowable, ThrowingRunnable runnable) { + try { + assertThrows(expectedThrowable, runnable); + } catch (AssertionError e) { + addError(e); + } + } + +} diff --git a/src/main/java/org/junit/rules/ExpectedException.java b/src/main/java/org/junit/rules/ExpectedException.java new file mode 100644 index 000000000000..71ee21ffe4f4 --- /dev/null +++ b/src/main/java/org/junit/rules/ExpectedException.java @@ -0,0 +1,283 @@ +package org.junit.rules; + +import static java.lang.String.format; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause; +import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; +import org.hamcrest.Matcher; +import org.hamcrest.StringDescription; +import org.junit.AssumptionViolatedException; +import org.junit.runners.model.Statement; + +/** + * The {@code ExpectedException} rule allows you to verify that your code + * throws a specific exception. + * + *

      Usage

      + * + *
       public class SimpleExpectedExceptionTest {
      + *     @Rule
      + *     public ExpectedException thrown = ExpectedException.none();
      + *
      + *     @Test
      + *     public void throwsNothing() {
      + *         // no exception expected, none thrown: passes.
      + *     }
      + *
      + *     @Test
      + *     public void throwsExceptionWithSpecificType() {
      + *         thrown.expect(NullPointerException.class);
      + *         throw new NullPointerException();
      + *     }
      + * }
      + * + *

      + * You have to add the {@code ExpectedException} rule to your test. + * This doesn't affect your existing tests (see {@code throwsNothing()}). + * After specifiying the type of the expected exception your test is + * successful when such an exception is thrown and it fails if a + * different or no exception is thrown. + * + *

      + * Instead of specifying the exception's type you can characterize the + * expected exception based on other criteria, too: + * + *

        + *
      • The exception's message contains a specific text: {@link #expectMessage(String)}
      • + *
      • The exception's message complies with a Hamcrest matcher: {@link #expectMessage(Matcher)}
      • + *
      • The exception's cause complies with a Hamcrest matcher: {@link #expectCause(Matcher)}
      • + *
      • The exception itself complies with a Hamcrest matcher: {@link #expect(Matcher)}
      • + *
      + * + *

      + * You can combine any of the presented expect-methods. The test is + * successful if all specifications are met. + *

       @Test
      + * public void throwsException() {
      + *     thrown.expect(NullPointerException.class);
      + *     thrown.expectMessage("happened");
      + *     throw new NullPointerException("What happened?");
      + * }
      + * + *

      AssumptionViolatedExceptions

      + *

      + * JUnit uses {@link AssumptionViolatedException}s for indicating that a test + * provides no useful information. (See {@link org.junit.Assume} for more + * information.) You have to call {@code assume} methods before you set + * expectations of the {@code ExpectedException} rule. In this case the rule + * will not handle consume the exceptions and it can be handled by the + * framework. E.g. the following test is ignored by JUnit's default runner. + * + *

       @Test
      + * public void ignoredBecauseOfFailedAssumption() {
      + *     assumeTrue(false); // throws AssumptionViolatedException
      + *     thrown.expect(NullPointerException.class);
      + * }
      + * + *

      AssertionErrors

      + * + *

      + * JUnit uses {@link AssertionError}s for indicating that a test is failing. You + * have to call {@code assert} methods before you set expectations of the + * {@code ExpectedException} rule, if they should be handled by the framework. + * E.g. the following test fails because of the {@code assertTrue} statement. + * + *

       @Test
      + * public void throwsUnhandled() {
      + *     assertTrue(false); // throws AssertionError
      + *     thrown.expect(NullPointerException.class);
      + * }
      + * + *

      Missing Exceptions

      + *

      + * By default missing exceptions are reported with an error message + * like "Expected test to throw an instance of foo". You can configure a different + * message by means of {@link #reportMissingExceptionWithMessage(String)}. You + * can use a {@code %s} placeholder for the description of the expected + * exception. E.g. "Test doesn't throw %s." will fail with the error message + * "Test doesn't throw an instance of foo.". + * + * @since 4.7 + */ +public class ExpectedException implements TestRule { + /** + * Returns a {@linkplain TestRule rule} that expects no exception to + * be thrown (identical to behavior without this rule). + */ + public static ExpectedException none() { + return new ExpectedException(); + } + + private final ExpectedExceptionMatcherBuilder matcherBuilder = new ExpectedExceptionMatcherBuilder(); + + private String missingExceptionMessage= "Expected test to throw %s"; + + private ExpectedException() { + } + + /** + * This method does nothing. Don't use it. + * @deprecated AssertionErrors are handled by default since JUnit 4.12. Just + * like in JUnit <= 4.10. + */ + @Deprecated + public ExpectedException handleAssertionErrors() { + return this; + } + + /** + * This method does nothing. Don't use it. + * @deprecated AssumptionViolatedExceptions are handled by default since + * JUnit 4.12. Just like in JUnit <= 4.10. + */ + @Deprecated + public ExpectedException handleAssumptionViolatedExceptions() { + return this; + } + + /** + * Specifies the failure message for tests that are expected to throw + * an exception but do not throw any. You can use a {@code %s} placeholder for + * the description of the expected exception. E.g. "Test doesn't throw %s." + * will fail with the error message + * "Test doesn't throw an instance of foo.". + * + * @param message exception detail message + * @return the rule itself + */ + public ExpectedException reportMissingExceptionWithMessage(String message) { + missingExceptionMessage = message; + return this; + } + + public Statement apply(Statement base, + org.junit.runner.Description description) { + return new ExpectedExceptionStatement(base); + } + + /** + * Verify that your code throws an exception that is matched by + * a Hamcrest matcher. + *

       @Test
      +     * public void throwsExceptionThatCompliesWithMatcher() {
      +     *     NullPointerException e = new NullPointerException();
      +     *     thrown.expect(is(e));
      +     *     throw e;
      +     * }
      + * + * @deprecated use {@code org.hamcrest.junit.ExpectedException.expect()} + */ + @Deprecated + public ExpectedException expect(Matcher matcher) { + matcherBuilder.add(matcher); + return this; + } + + /** + * Verify that your code throws an exception that is an + * instance of specific {@code type}. + *
       @Test
      +     * public void throwsExceptionWithSpecificType() {
      +     *     thrown.expect(NullPointerException.class);
      +     *     throw new NullPointerException();
      +     * }
      + */ + public ExpectedException expect(Class type) { + expect(instanceOf(type)); + return this; + } + + /** + * Verify that your code throws an exception whose message contains + * a specific text. + *
       @Test
      +     * public void throwsExceptionWhoseMessageContainsSpecificText() {
      +     *     thrown.expectMessage("happened");
      +     *     throw new NullPointerException("What happened?");
      +     * }
      + */ + public ExpectedException expectMessage(String substring) { + expectMessage(containsString(substring)); + return this; + } + + /** + * Verify that your code throws an exception whose message is matched + * by a Hamcrest matcher. + *
       @Test
      +     * public void throwsExceptionWhoseMessageCompliesWithMatcher() {
      +     *     thrown.expectMessage(startsWith("What"));
      +     *     throw new NullPointerException("What happened?");
      +     * }
      + * + * @deprecated use {@code org.hamcrest.junit.ExpectedException.expectMessage()} + */ + @Deprecated + public ExpectedException expectMessage(Matcher matcher) { + expect(hasMessage(matcher)); + return this; + } + + /** + * Verify that your code throws an exception whose cause is matched by + * a Hamcrest matcher. + *
       @Test
      +     * public void throwsExceptionWhoseCauseCompliesWithMatcher() {
      +     *     NullPointerException expectedCause = new NullPointerException();
      +     *     thrown.expectCause(is(expectedCause));
      +     *     throw new IllegalArgumentException("What happened?", cause);
      +     * }
      + * + * @deprecated use {@code org.hamcrest.junit.ExpectedException.expectCause()} + */ + @Deprecated + public ExpectedException expectCause(Matcher expectedCause) { + expect(hasCause(expectedCause)); + return this; + } + + private class ExpectedExceptionStatement extends Statement { + private final Statement next; + + public ExpectedExceptionStatement(Statement base) { + next = base; + } + + @Override + public void evaluate() throws Throwable { + try { + next.evaluate(); + } catch (Throwable e) { + handleException(e); + return; + } + if (isAnyExceptionExpected()) { + failDueToMissingException(); + } + } + } + + private void handleException(Throwable e) throws Throwable { + if (isAnyExceptionExpected()) { + assertThat(e, matcherBuilder.build()); + } else { + throw e; + } + } + + private boolean isAnyExceptionExpected() { + return matcherBuilder.expectsThrowable(); + } + + private void failDueToMissingException() throws AssertionError { + fail(missingExceptionMessage()); + } + + private String missingExceptionMessage() { + String expectation= StringDescription.toString(matcherBuilder.build()); + return format(missingExceptionMessage, expectation); + } +} diff --git a/src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java b/src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java new file mode 100644 index 000000000000..e7d94c483f4a --- /dev/null +++ b/src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java @@ -0,0 +1,46 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.junit.matchers.JUnitMatchers.isThrowable; + +import java.util.ArrayList; +import java.util.List; + +import org.hamcrest.Matcher; + +/** + * Builds special matcher used by {@link ExpectedException}. + */ +class ExpectedExceptionMatcherBuilder { + + private final List> matchers = new ArrayList>(); + + void add(Matcher matcher) { + matchers.add(matcher); + } + + boolean expectsThrowable() { + return !matchers.isEmpty(); + } + + Matcher build() { + return isThrowable(allOfTheMatchers()); + } + + private Matcher allOfTheMatchers() { + if (matchers.size() == 1) { + return cast(matchers.get(0)); + } + return allOf(castedMatchers()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private List> castedMatchers() { + return new ArrayList>((List) matchers); + } + + @SuppressWarnings("unchecked") + private Matcher cast(Matcher singleMatcher) { + return (Matcher) singleMatcher; + } +} diff --git a/src/main/java/org/junit/rules/ExternalResource.java b/src/main/java/org/junit/rules/ExternalResource.java new file mode 100644 index 000000000000..71fc84294308 --- /dev/null +++ b/src/main/java/org/junit/rules/ExternalResource.java @@ -0,0 +1,84 @@ +package org.junit.rules; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +/** + * A base class for Rules (like TemporaryFolder) that set up an external + * resource before a test (a file, socket, server, database connection, etc.), + * and guarantee to tear it down afterward: + * + *
      + * public static class UsesExternalResource {
      + *  Server myServer= new Server();
      + *
      + *  @Rule
      + *  public ExternalResource resource= new ExternalResource() {
      + *      @Override
      + *      protected void before() throws Throwable {
      + *          myServer.connect();
      + *         };
      + *
      + *      @Override
      + *      protected void after() {
      + *          myServer.disconnect();
      + *         };
      + *     };
      + *
      + *  @Test
      + *  public void testFoo() {
      + *      new Client().run(myServer);
      + *     }
      + * }
      + * 
      + * + * @since 4.7 + */ +public abstract class ExternalResource implements TestRule { + public Statement apply(Statement base, Description description) { + return statement(base); + } + + private Statement statement(final Statement base) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + before(); + + List errors = new ArrayList(); + try { + base.evaluate(); + } catch (Throwable t) { + errors.add(t); + } finally { + try { + after(); + } catch (Throwable t) { + errors.add(t); + } + } + MultipleFailureException.assertEmpty(errors); + } + }; + } + + /** + * Override to set up your specific external resource. + * + * @throws Throwable if setup fails (which will disable {@code after} + */ + protected void before() throws Throwable { + // do nothing + } + + /** + * Override to tear down your specific external resource. + */ + protected void after() { + // do nothing + } +} diff --git a/src/main/java/org/junit/rules/MethodRule.java b/src/main/java/org/junit/rules/MethodRule.java new file mode 100644 index 000000000000..94608f5a88f9 --- /dev/null +++ b/src/main/java/org/junit/rules/MethodRule.java @@ -0,0 +1,32 @@ +package org.junit.rules; + +import org.junit.Rule; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.Statement; + +/** + * A MethodRule is an alteration in how a test method is run and reported. + * Multiple {@link MethodRule}s can be applied to a test method. The + * {@link Statement} that executes the method is passed to each annotated + * {@link Rule} in turn, and each may return a substitute or modified + * {@link Statement}, which is passed to the next {@link Rule}, if any. For + * an example of how this can be useful, see {@link TestWatchman}. + * + *

      Note that {@link MethodRule} has been replaced by {@link TestRule}, + * which has the added benefit of supporting class rules. + * + * @since 4.7 + */ +public interface MethodRule { + /** + * Modifies the method-running {@link Statement} to implement an additional + * test-running rule. + * + * @param base The {@link Statement} to be modified + * @param method The method to be run + * @param target The object on which the method will be run. + * @return a new statement, which may be the same as {@code base}, + * a wrapper around {@code base}, or a completely new Statement. + */ + Statement apply(Statement base, FrameworkMethod method, Object target); +} diff --git a/src/main/java/org/junit/rules/RuleChain.java b/src/main/java/org/junit/rules/RuleChain.java new file mode 100644 index 000000000000..fe710eb2eb02 --- /dev/null +++ b/src/main/java/org/junit/rules/RuleChain.java @@ -0,0 +1,113 @@ +package org.junit.rules; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * The RuleChain rule allows ordering of TestRules. You create a + * {@code RuleChain} with {@link #outerRule(TestRule)} and subsequent calls of + * {@link #around(TestRule)}: + * + *

      + * public class UseRuleChain {
      + * 	@Rule
      + * 	public RuleChain chain= RuleChain
      + * 	                       .outerRule(new LoggingRule("outer rule"))
      + * 	                       .around(new LoggingRule("middle rule"))
      + * 	                       .around(new LoggingRule("inner rule"));
      + *
      + * 	@Test
      + * 	public void example() {
      + * 		assertTrue(true);
      + *     }
      + * }
      + * 
      + * + * writes the log + * + *
      + * starting outer rule
      + * starting middle rule
      + * starting inner rule
      + * finished inner rule
      + * finished middle rule
      + * finished outer rule
      + * 
      + * + * {@code RuleChain} cannot be used to define the order of existing rules. + * For example in the below snippet the LoggingRule {@code middle} would be + * executed outside as well as inside the {@code RuleChain}: + * + *
      + * @Rule
      + * public LoggingRule middle = new LoggingRule("middle rule");
      + * 
      + * @Rule
      + * public RuleChain chain = RuleChain
      + *                          .outerRule(new LoggingRule("outer rule"))
      + *                          .around(middle)
      + *                          .around(new LoggingRule("inner rule"));
      + * 
      + * + * @since 4.10 + */ +public class RuleChain implements TestRule { + private static final RuleChain EMPTY_CHAIN = new RuleChain( + Collections.emptyList()); + + private List rulesStartingWithInnerMost; + + /** + * Returns a {@code RuleChain} without a {@link TestRule}. This method may + * be the starting point of a {@code RuleChain}. + * + * @return a {@code RuleChain} without a {@link TestRule}. + */ + public static RuleChain emptyRuleChain() { + return EMPTY_CHAIN; + } + + /** + * Returns a {@code RuleChain} with a single {@link TestRule}. This method + * is the usual starting point of a {@code RuleChain}. + * + * @param outerRule the outer rule of the {@code RuleChain}. + * @return a {@code RuleChain} with a single {@link TestRule}. + */ + public static RuleChain outerRule(TestRule outerRule) { + return emptyRuleChain().around(outerRule); + } + + private RuleChain(List rules) { + this.rulesStartingWithInnerMost = rules; + } + + /** + * Create a new {@code RuleChain}, which encloses the given {@link TestRule} with + * the rules of the current {@code RuleChain}. + * + * @param enclosedRule the rule to enclose; must not be {@code null}. + * @return a new {@code RuleChain}. + * @throws NullPointerException if the argument {@code enclosedRule} is {@code null} + */ + public RuleChain around(TestRule enclosedRule) { + if (enclosedRule == null) { + throw new NullPointerException("The enclosed rule must not be null"); + } + List rulesOfNewChain = new ArrayList(); + rulesOfNewChain.add(enclosedRule); + rulesOfNewChain.addAll(rulesStartingWithInnerMost); + return new RuleChain(rulesOfNewChain); + } + + /** + * {@inheritDoc} + */ + public Statement apply(Statement base, Description description) { + return new RunRules(base, rulesStartingWithInnerMost, description); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/rules/RunRules.java b/src/main/java/org/junit/rules/RunRules.java new file mode 100644 index 000000000000..131fc1f81543 --- /dev/null +++ b/src/main/java/org/junit/rules/RunRules.java @@ -0,0 +1,30 @@ +package org.junit.rules; + +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * Runs a collection of rules on a statement. + * + * @since 4.9 + */ +public class RunRules extends Statement { + private final Statement statement; + + public RunRules(Statement base, Iterable rules, Description description) { + statement = applyAll(base, rules, description); + } + + @Override + public void evaluate() throws Throwable { + statement.evaluate(); + } + + private static Statement applyAll(Statement result, Iterable rules, + Description description) { + for (TestRule each : rules) { + result = each.apply(result, description); + } + return result; + } +} diff --git a/src/main/java/org/junit/rules/Stopwatch.java b/src/main/java/org/junit/rules/Stopwatch.java new file mode 100644 index 000000000000..6900a481cf11 --- /dev/null +++ b/src/main/java/org/junit/rules/Stopwatch.java @@ -0,0 +1,183 @@ +package org.junit.rules; + +import org.junit.AssumptionViolatedException; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +import java.util.concurrent.TimeUnit; + +/** + * The Stopwatch Rule notifies one of its own protected methods of the time spent by a test. + * + *

      Override them to get the time in nanoseconds. For example, this class will keep logging the + * time spent by each passed, failed, skipped, and finished test: + * + *

      + * public static class StopwatchTest {
      + *     private static final Logger logger = Logger.getLogger("");
      + *
      + *     private static void logInfo(Description description, String status, long nanos) {
      + *         String testName = description.getMethodName();
      + *         logger.info(String.format("Test %s %s, spent %d microseconds",
      + *                                   testName, status, TimeUnit.NANOSECONDS.toMicros(nanos)));
      + *     }
      + *
      + *     @Rule
      + *     public Stopwatch stopwatch = new Stopwatch() {
      + *         @Override
      + *         protected void succeeded(long nanos, Description description) {
      + *             logInfo(description, "succeeded", nanos);
      + *         }
      + *
      + *         @Override
      + *         protected void failed(long nanos, Throwable e, Description description) {
      + *             logInfo(description, "failed", nanos);
      + *         }
      + *
      + *         @Override
      + *         protected void skipped(long nanos, AssumptionViolatedException e, Description description) {
      + *             logInfo(description, "skipped", nanos);
      + *         }
      + *
      + *         @Override
      + *         protected void finished(long nanos, Description description) {
      + *             logInfo(description, "finished", nanos);
      + *         }
      + *     };
      + *
      + *     @Test
      + *     public void succeeds() {
      + *     }
      + *
      + *     @Test
      + *     public void fails() {
      + *         fail();
      + *     }
      + *
      + *     @Test
      + *     public void skips() {
      + *         assumeTrue(false);
      + *     }
      + * }
      + * 
      + * + * An example to assert runtime: + *
      + * @Test
      + * public void performanceTest() throws InterruptedException {
      + *     long delta = 30;
      + *     Thread.sleep(300L);
      + *     assertEquals(300d, stopwatch.runtime(MILLISECONDS), delta);
      + *     Thread.sleep(500L);
      + *     assertEquals(800d, stopwatch.runtime(MILLISECONDS), delta);
      + * }
      + * 
      + * + * @author tibor17 + * @since 4.12 + */ +public class Stopwatch implements TestRule { + private final Clock clock; + private volatile long startNanos; + private volatile long endNanos; + + public Stopwatch() { + this(new Clock()); + } + + Stopwatch(Clock clock) { + this.clock = clock; + } + + /** + * Gets the runtime for the test. + * + * @param unit time unit for returned runtime + * @return runtime measured during the test + */ + public long runtime(TimeUnit unit) { + return unit.convert(getNanos(), TimeUnit.NANOSECONDS); + } + + /** + * Invoked when a test succeeds + */ + protected void succeeded(long nanos, Description description) { + } + + /** + * Invoked when a test fails + */ + protected void failed(long nanos, Throwable e, Description description) { + } + + /** + * Invoked when a test is skipped due to a failed assumption. + */ + protected void skipped(long nanos, AssumptionViolatedException e, Description description) { + } + + /** + * Invoked when a test method finishes (whether passing or failing) + */ + protected void finished(long nanos, Description description) { + } + + private long getNanos() { + if (startNanos == 0) { + throw new IllegalStateException("Test has not started"); + } + long currentEndNanos = endNanos; // volatile read happens here + if (currentEndNanos == 0) { + currentEndNanos = clock.nanoTime(); + } + + return currentEndNanos - startNanos; + } + + private void starting() { + startNanos = clock.nanoTime(); + endNanos = 0; + } + + private void stopping() { + endNanos = clock.nanoTime(); + } + + public final Statement apply(Statement base, Description description) { + return new InternalWatcher().apply(base, description); + } + + private class InternalWatcher extends TestWatcher { + + @Override protected void starting(Description description) { + Stopwatch.this.starting(); + } + + @Override protected void finished(Description description) { + Stopwatch.this.finished(getNanos(), description); + } + + @Override protected void succeeded(Description description) { + Stopwatch.this.stopping(); + Stopwatch.this.succeeded(getNanos(), description); + } + + @Override protected void failed(Throwable e, Description description) { + Stopwatch.this.stopping(); + Stopwatch.this.failed(getNanos(), e, description); + } + + @Override protected void skipped(AssumptionViolatedException e, Description description) { + Stopwatch.this.stopping(); + Stopwatch.this.skipped(getNanos(), e, description); + } + } + + static class Clock { + + public long nanoTime() { + return System.nanoTime(); + } + } +} diff --git a/src/main/java/org/junit/rules/TemporaryFolder.java b/src/main/java/org/junit/rules/TemporaryFolder.java new file mode 100644 index 000000000000..3354057f55da --- /dev/null +++ b/src/main/java/org/junit/rules/TemporaryFolder.java @@ -0,0 +1,298 @@ +package org.junit.rules; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; + +import org.junit.Rule; + +/** + * The TemporaryFolder Rule allows creation of files and folders that should + * be deleted when the test method finishes (whether it passes or + * fails). + * By default no exception will be thrown in case the deletion fails. + * + *

      Example of usage: + *

      + * public static class HasTempFolder {
      + *  @Rule
      + *  public TemporaryFolder folder= new TemporaryFolder();
      + *
      + *  @Test
      + *  public void testUsingTempFolder() throws IOException {
      + *      File createdFile= folder.newFile("myfile.txt");
      + *      File createdFolder= folder.newFolder("subfolder");
      + *      // ...
      + *     }
      + * }
      + * 
      + * + *

      TemporaryFolder rule supports assured deletion mode, which + * will fail the test in case deletion fails with {@link AssertionError}. + * + *

      Creating TemporaryFolder with assured deletion: + *

      + *  @Rule
      + *  public TemporaryFolder folder= TemporaryFolder.builder().assureDeletion().build();
      + * 
      + * + * @since 4.7 + */ +public class TemporaryFolder extends ExternalResource { + private final File parentFolder; + private final boolean assureDeletion; + private File folder; + + private static final int TEMP_DIR_ATTEMPTS = 10000; + private static final String TMP_PREFIX = "junit"; + + /** + * Create a temporary folder which uses system default temporary-file + * directory to create temporary resources. + */ + public TemporaryFolder() { + this((File) null); + } + + /** + * Create a temporary folder which uses the specified directory to create + * temporary resources. + * + * @param parentFolder folder where temporary resources will be created. + * If {@code null} then system default temporary-file directory is used. + */ + public TemporaryFolder(File parentFolder) { + this.parentFolder = parentFolder; + this.assureDeletion = false; + } + + /** + * Create a {@link TemporaryFolder} initialized with + * values from a builder. + */ + protected TemporaryFolder(Builder builder) { + this.parentFolder = builder.parentFolder; + this.assureDeletion = builder.assureDeletion; + } + + /** + * Returns a new builder for building an instance of {@link TemporaryFolder}. + * + * @since 4.13 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Builds an instance of {@link TemporaryFolder}. + * + * @since 4.13 + */ + public static class Builder { + private File parentFolder; + private boolean assureDeletion; + + protected Builder() {} + + /** + * Specifies which folder to use for creating temporary resources. + * If {@code null} then system default temporary-file directory is + * used. + * + * @return this + */ + public Builder parentFolder(File parentFolder) { + this.parentFolder = parentFolder; + return this; + } + + /** + * Setting this flag assures that no resources are left undeleted. Failure + * to fulfill the assurance results in failure of tests with an + * {@link AssertionError}. + * + * @return this + */ + public Builder assureDeletion() { + this.assureDeletion = true; + return this; + } + + /** + * Builds a {@link TemporaryFolder} instance using the values in this builder. + */ + public TemporaryFolder build() { + return new TemporaryFolder(this); + } + } + + @Override + protected void before() throws Throwable { + create(); + } + + @Override + protected void after() { + delete(); + } + + // testing purposes only + + /** + * for testing purposes only. Do not use. + */ + public void create() throws IOException { + folder = createTemporaryFolderIn(parentFolder); + } + + /** + * Returns a new fresh file with the given name under the temporary folder. + */ + public File newFile(String fileName) throws IOException { + File file = new File(getRoot(), fileName); + if (!file.createNewFile()) { + throw new IOException( + "a file with the name \'" + fileName + "\' already exists in the test folder"); + } + return file; + } + + /** + * Returns a new fresh file with a random name under the temporary folder. + */ + public File newFile() throws IOException { + return File.createTempFile(TMP_PREFIX, null, getRoot()); + } + + /** + * Returns a new fresh folder with the given name under the temporary + * folder. + */ + public File newFolder(String folder) throws IOException { + return newFolder(new String[]{folder}); + } + + /** + * Returns a new fresh folder with the given name(s) under the temporary + * folder. + */ + public File newFolder(String... folderNames) throws IOException { + File file = getRoot(); + for (int i = 0; i < folderNames.length; i++) { + String folderName = folderNames[i]; + validateFolderName(folderName); + file = new File(file, folderName); + if (!file.mkdir() && isLastElementInArray(i, folderNames)) { + throw new IOException( + "a folder with the name \'" + folderName + "\' already exists"); + } + } + return file; + } + + /** + * Validates if multiple path components were used while creating a folder. + * + * @param folderName + * Name of the folder being created + */ + private void validateFolderName(String folderName) throws IOException { + File tempFile = new File(folderName); + if (tempFile.getParent() != null) { + String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; + throw new IOException(errorMsg); + } + } + + private boolean isLastElementInArray(int index, String[] array) { + return index == array.length - 1; + } + + /** + * Returns a new fresh folder with a random name under the temporary folder. + */ + public File newFolder() throws IOException { + return createTemporaryFolderIn(getRoot()); + } + + private File createTemporaryFolderIn(File parentFolder) throws IOException { + File createdFolder = null; + for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) { + // Use createTempFile to get a suitable folder name. + String suffix = ".tmp"; + File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder); + String tmpName = tmpFile.toString(); + // Discard .tmp suffix of tmpName. + String folderName = tmpName.substring(0, tmpName.length() - suffix.length()); + createdFolder = new File(folderName); + if (createdFolder.mkdir()) { + tmpFile.delete(); + return createdFolder; + } + tmpFile.delete(); + } + throw new IOException("Unable to create temporary directory in: " + + parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. " + + "Last attempted to create: " + createdFolder.toString()); + } + + /** + * @return the location of this temporary folder. + */ + public File getRoot() { + if (folder == null) { + throw new IllegalStateException( + "the temporary folder has not yet been created"); + } + return folder; + } + + /** + * Delete all files and folders under the temporary folder. Usually not + * called directly, since it is automatically applied by the {@link Rule}. + * + * @throws AssertionError if unable to clean up resources + * and deletion of resources is assured. + */ + public void delete() { + if (!tryDelete()) { + if (assureDeletion) { + fail("Unable to clean up temporary folder " + folder); + } + } + } + + /** + * Tries to delete all files and folders under the temporary folder and + * returns whether deletion was successful or not. + * + * @return {@code true} if all resources are deleted successfully, + * {@code false} otherwise. + */ + protected boolean tryDelete() { + if (folder == null) { + return true; + } + + return recursiveDelete(folder); + } + + private boolean recursiveDelete(File file) { + // Try deleting file before assuming file is a directory + // to prevent following symbolic links. + if (file.delete()) { + return true; + } + boolean result = true; + File[] files = file.listFiles(); + if (files != null) { + for (File each : files) { + result = result && recursiveDelete(each); + } + } + return result && file.delete(); + } +} diff --git a/src/main/java/org/junit/rules/TestName.java b/src/main/java/org/junit/rules/TestName.java new file mode 100644 index 000000000000..e2ebc2ec97d1 --- /dev/null +++ b/src/main/java/org/junit/rules/TestName.java @@ -0,0 +1,41 @@ +package org.junit.rules; + +import org.junit.runner.Description; + +/** + * The TestName Rule makes the current test name available inside test methods: + * + *
      + * public class TestNameTest {
      + *  @Rule
      + *  public TestName name= new TestName();
      + *
      + *  @Test
      + *  public void testA() {
      + *      assertEquals("testA", name.getMethodName());
      + *     }
      + *
      + *  @Test
      + *  public void testB() {
      + *      assertEquals("testB", name.getMethodName());
      + *     }
      + * }
      + * 
      + * + * @since 4.7 + */ +public class TestName extends TestWatcher { + private volatile String name; + + @Override + protected void starting(Description d) { + name = d.getMethodName(); + } + + /** + * @return the name of the currently-running test method + */ + public String getMethodName() { + return name; + } +} diff --git a/src/main/java/org/junit/rules/TestRule.java b/src/main/java/org/junit/rules/TestRule.java new file mode 100644 index 000000000000..53e2f708e276 --- /dev/null +++ b/src/main/java/org/junit/rules/TestRule.java @@ -0,0 +1,56 @@ +package org.junit.rules; + +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * A TestRule is an alteration in how a test method, or set of test methods, + * is run and reported. A {@link TestRule} may add additional checks that cause + * a test that would otherwise fail to pass, or it may perform necessary setup or + * cleanup for tests, or it may observe test execution to report it elsewhere. + * {@link TestRule}s can do everything that could be done previously with + * methods annotated with {@link org.junit.Before}, + * {@link org.junit.After}, {@link org.junit.BeforeClass}, or + * {@link org.junit.AfterClass}, but they are more powerful, and more easily + * shared + * between projects and classes. + * + * The default JUnit test runners for suites and + * individual test cases recognize {@link TestRule}s introduced in two different + * ways. {@link org.junit.Rule} annotates method-level + * {@link TestRule}s, and {@link org.junit.ClassRule} + * annotates class-level {@link TestRule}s. See Javadoc for those annotations + * for more information. + * + * Multiple {@link TestRule}s can be applied to a test or suite execution. The + * {@link Statement} that executes the method or suite is passed to each annotated + * {@link org.junit.Rule} in turn, and each may return a substitute or modified + * {@link Statement}, which is passed to the next {@link org.junit.Rule}, if any. For + * examples of how this can be useful, see these provided TestRules, + * or write your own: + * + *
        + *
      • {@link ErrorCollector}: collect multiple errors in one test method
      • + *
      • {@link ExpectedException}: make flexible assertions about thrown exceptions
      • + *
      • {@link ExternalResource}: start and stop a server, for example
      • + *
      • {@link TemporaryFolder}: create fresh files, and delete after test
      • + *
      • {@link TestName}: remember the test name for use during the method
      • + *
      • {@link TestWatcher}: add logic at events during method execution
      • + *
      • {@link Timeout}: cause test to fail after a set time
      • + *
      • {@link Verifier}: fail test if object state ends up incorrect
      • + *
      + * + * @since 4.9 + */ +public interface TestRule { + /** + * Modifies the method-running {@link Statement} to implement this + * test-running rule. + * + * @param base The {@link Statement} to be modified + * @param description A {@link Description} of the test implemented in {@code base} + * @return a new statement, which may be the same as {@code base}, + * a wrapper around {@code base}, or a completely new Statement. + */ + Statement apply(Statement base, Description description); +} diff --git a/src/main/java/org/junit/rules/TestWatcher.java b/src/main/java/org/junit/rules/TestWatcher.java new file mode 100644 index 000000000000..b790dd304cc1 --- /dev/null +++ b/src/main/java/org/junit/rules/TestWatcher.java @@ -0,0 +1,164 @@ +package org.junit.rules; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.AssumptionViolatedException; +import org.junit.runner.Description; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +/** + * TestWatcher is a base class for Rules that take note of the testing + * action, without modifying it. For example, this class will keep a log of each + * passing and failing test: + * + *
      + * public static class WatchmanTest {
      + *  private static String watchedLog;
      + *
      + *  @Rule
      + *  public TestWatcher watchman= new TestWatcher() {
      + *      @Override
      + *      protected void failed(Throwable e, Description description) {
      + *          watchedLog+= description + "\n";
      + *      }
      + *
      + *      @Override
      + *      protected void succeeded(Description description) {
      + *          watchedLog+= description + " " + "success!\n";
      + *         }
      + *     };
      + *
      + *  @Test
      + *  public void fails() {
      + *      fail();
      + *  }
      + *
      + *  @Test
      + *  public void succeeds() {
      + *     }
      + * }
      + * 
      + * + * @since 4.9 + */ +public abstract class TestWatcher implements TestRule { + public Statement apply(final Statement base, final Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + List errors = new ArrayList(); + + startingQuietly(description, errors); + try { + base.evaluate(); + succeededQuietly(description, errors); + } catch (org.junit.internal.AssumptionViolatedException e) { + errors.add(e); + skippedQuietly(e, description, errors); + } catch (Throwable e) { + errors.add(e); + failedQuietly(e, description, errors); + } finally { + finishedQuietly(description, errors); + } + + MultipleFailureException.assertEmpty(errors); + } + }; + } + + private void succeededQuietly(Description description, + List errors) { + try { + succeeded(description); + } catch (Throwable e) { + errors.add(e); + } + } + + private void failedQuietly(Throwable e, Description description, + List errors) { + try { + failed(e, description); + } catch (Throwable e1) { + errors.add(e1); + } + } + + private void skippedQuietly( + org.junit.internal.AssumptionViolatedException e, Description description, + List errors) { + try { + if (e instanceof AssumptionViolatedException) { + skipped((AssumptionViolatedException) e, description); + } else { + skipped(e, description); + } + } catch (Throwable e1) { + errors.add(e1); + } + } + + private void startingQuietly(Description description, + List errors) { + try { + starting(description); + } catch (Throwable e) { + errors.add(e); + } + } + + private void finishedQuietly(Description description, + List errors) { + try { + finished(description); + } catch (Throwable e) { + errors.add(e); + } + } + + /** + * Invoked when a test succeeds + */ + protected void succeeded(Description description) { + } + + /** + * Invoked when a test fails + */ + protected void failed(Throwable e, Description description) { + } + + /** + * Invoked when a test is skipped due to a failed assumption. + */ + protected void skipped(AssumptionViolatedException e, Description description) { + // For backwards compatibility with JUnit 4.11 and earlier, call the legacy version + org.junit.internal.AssumptionViolatedException asInternalException = e; + skipped(asInternalException, description); + } + + /** + * Invoked when a test is skipped due to a failed assumption. + * + * @deprecated use {@link #skipped(AssumptionViolatedException, Description)} + */ + @Deprecated + protected void skipped( + org.junit.internal.AssumptionViolatedException e, Description description) { + } + + /** + * Invoked when a test is about to start + */ + protected void starting(Description description) { + } + + /** + * Invoked when a test method finishes (whether passing or failing) + */ + protected void finished(Description description) { + } +} diff --git a/src/main/java/org/junit/rules/TestWatchman.java b/src/main/java/org/junit/rules/TestWatchman.java new file mode 100644 index 000000000000..c8d6c71ab7cf --- /dev/null +++ b/src/main/java/org/junit/rules/TestWatchman.java @@ -0,0 +1,91 @@ +package org.junit.rules; + +import org.junit.internal.AssumptionViolatedException; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.Statement; + +/** + * TestWatchman is a base class for Rules that take note of the testing + * action, without modifying it. For example, this class will keep a log of each + * passing and failing test: + * + *
      + * 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() {
      + *     }
      + * }
      + * 
      + * + * @since 4.7 + * @deprecated Use {@link TestWatcher} (which implements {@link TestRule}) instead. + */ +@Deprecated +public class TestWatchman implements MethodRule { + public Statement apply(final Statement base, final FrameworkMethod method, + Object target) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + starting(method); + try { + base.evaluate(); + succeeded(method); + } catch (AssumptionViolatedException e) { + throw e; + } catch (Throwable e) { + failed(e, method); + throw e; + } finally { + finished(method); + } + } + }; + } + + /** + * Invoked when a test method succeeds + */ + public void succeeded(FrameworkMethod method) { + } + + /** + * Invoked when a test method fails + */ + public void failed(Throwable e, FrameworkMethod method) { + } + + /** + * Invoked when a test method is about to start + */ + public void starting(FrameworkMethod method) { + } + + + /** + * Invoked when a test method finishes (whether passing or failing) + */ + public void finished(FrameworkMethod method) { + } +} diff --git a/src/main/java/org/junit/rules/Timeout.java b/src/main/java/org/junit/rules/Timeout.java new file mode 100644 index 000000000000..334a9235cd26 --- /dev/null +++ b/src/main/java/org/junit/rules/Timeout.java @@ -0,0 +1,233 @@ +package org.junit.rules; + +import org.junit.internal.runners.statements.FailOnTimeout; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +import java.util.concurrent.TimeUnit; + +/** + * The Timeout Rule applies the same timeout to all test methods in a class: + *
      + * public static class HasGlobalLongTimeout {
      + *
      + *  @Rule
      + *  public Timeout globalTimeout = Timeout.millis(20);
      + *
      + *  @Test
      + *  public void run1() throws InterruptedException {
      + *      Thread.sleep(100);
      + *  }
      + *
      + *  @Test
      + *  public void infiniteLoop() {
      + *      while (true) {}
      + *  }
      + * }
      + * 
      + *

      + * Each test is run in a new thread. If the specified timeout elapses before + * the test completes, its execution is interrupted via {@link Thread#interrupt()}. + * This happens in interruptable I/O and locks, and methods in {@link Object} + * and {@link Thread} throwing {@link InterruptedException}. + *

      + * A specified timeout of 0 will be interpreted as not set, however tests will + * still launch from separate threads. This can be useful for disabling timeouts + * in environments where they are dynamically set based on some property. + * + * @since 4.7 + */ +public class Timeout implements TestRule { + private final long timeout; + private final TimeUnit timeUnit; + private final boolean lookForStuckThread; + + /** + * Returns a new builder for building an instance. + * + * @since 4.12 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Create a {@code Timeout} instance with the timeout specified + * in milliseconds. + *

      + * This constructor is deprecated. + *

      + * Instead use {@link #Timeout(long, java.util.concurrent.TimeUnit)}, + * {@link Timeout#millis(long)}, or {@link Timeout#seconds(long)}. + * + * @param millis the maximum time in milliseconds to allow the + * test to run before it should timeout + */ + @Deprecated + public Timeout(int millis) { + this(millis, TimeUnit.MILLISECONDS); + } + + /** + * Create a {@code Timeout} instance with the timeout specified + * at the timeUnit of granularity of the provided {@code TimeUnit}. + * + * @param timeout the maximum time to allow the test to run + * before it should timeout + * @param timeUnit the time unit for the {@code timeout} + * @since 4.12 + */ + public Timeout(long timeout, TimeUnit timeUnit) { + this.timeout = timeout; + this.timeUnit = timeUnit; + lookForStuckThread = false; + } + + /** + * Create a {@code Timeout} instance initialized with values from + * a builder. + * + * @since 4.12 + */ + protected Timeout(Builder builder) { + timeout = builder.getTimeout(); + timeUnit = builder.getTimeUnit(); + lookForStuckThread = builder.getLookingForStuckThread(); + } + + /** + * Creates a {@link Timeout} that will timeout a test after the + * given duration, in milliseconds. + * + * @since 4.12 + */ + public static Timeout millis(long millis) { + return new Timeout(millis, TimeUnit.MILLISECONDS); + } + + /** + * Creates a {@link Timeout} that will timeout a test after the + * given duration, in seconds. + * + * @since 4.12 + */ + public static Timeout seconds(long seconds) { + return new Timeout(seconds, TimeUnit.SECONDS); + } + + /** + * Gets the timeout configured for this rule, in the given units. + * + * @since 4.12 + */ + protected final long getTimeout(TimeUnit unit) { + return unit.convert(timeout, timeUnit); + } + + /** + * Gets whether this {@code Timeout} will look for a stuck thread + * when the test times out. + * + * @since 4.12 + */ + protected final boolean getLookingForStuckThread() { + return lookForStuckThread; + } + + /** + * Creates a {@link Statement} that will run the given + * {@code statement}, and timeout the operation based + * on the values configured in this rule. Subclasses + * can override this method for different behavior. + * + * @since 4.12 + */ + protected Statement createFailOnTimeoutStatement( + Statement statement) throws Exception { + return FailOnTimeout.builder() + .withTimeout(timeout, timeUnit) + .withLookingForStuckThread(lookForStuckThread) + .build(statement); + } + + public Statement apply(Statement base, Description description) { + try { + return createFailOnTimeoutStatement(base); + } catch (final Exception e) { + return new Statement() { + @Override public void evaluate() throws Throwable { + throw new RuntimeException("Invalid parameters for Timeout", e); + } + }; + } + } + + /** + * Builder for {@link Timeout}. + * + * @since 4.12 + */ + public static class Builder { + private boolean lookForStuckThread = false; + private long timeout = 0; + private TimeUnit timeUnit = TimeUnit.SECONDS; + + protected Builder() { + } + + /** + * Specifies the time to wait before timing out the test. + * + *

      If this is not called, or is called with a + * {@code timeout} of {@code 0}, the returned {@code Timeout} + * rule instance will cause the tests to wait forever to + * complete, however the tests will still launch from a + * separate thread. This can be useful for disabling timeouts + * in environments where they are dynamically set based on + * some property. + * + * @param timeout the maximum time to wait + * @param unit the time unit of the {@code timeout} argument + * @return {@code this} for method chaining. + */ + public Builder withTimeout(long timeout, TimeUnit unit) { + this.timeout = timeout; + this.timeUnit = unit; + return this; + } + + protected long getTimeout() { + return timeout; + } + + protected TimeUnit getTimeUnit() { + return timeUnit; + } + + /** + * Specifies whether to look for a stuck thread. If a timeout occurs and this + * feature is enabled, the rule will look for a thread that appears to be stuck + * and dump its backtrace. This feature is experimental. Behavior may change + * after the 4.12 release in response to feedback. + * + * @param enable {@code true} to enable the feature + * @return {@code this} for method chaining. + */ + public Builder withLookingForStuckThread(boolean enable) { + this.lookForStuckThread = enable; + return this; + } + + protected boolean getLookingForStuckThread() { + return lookForStuckThread; + } + + + /** + * Builds a {@link Timeout} instance using the values in this builder., + */ + public Timeout build() { + return new Timeout(this); + } + } +} diff --git a/src/main/java/org/junit/rules/Verifier.java b/src/main/java/org/junit/rules/Verifier.java new file mode 100644 index 000000000000..7a03b0cb56d3 --- /dev/null +++ b/src/main/java/org/junit/rules/Verifier.java @@ -0,0 +1,47 @@ +package org.junit.rules; + +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * Verifier is a base class for Rules like ErrorCollector, which can turn + * otherwise passing test methods into failing tests if a verification check is + * failed + * + *

      + *     public static class ErrorLogVerifier {
      + *        private ErrorLog errorLog = new ErrorLog();
      + *
      + *        @Rule
      + *        public Verifier verifier = new Verifier() {
      + *           @Override public void verify() {
      + *              assertTrue(errorLog.isEmpty());
      + *           }
      + *        }
      + *
      + *        @Test public void testThatMightWriteErrorLog() {
      + *           // ...
      + *        }
      + *     }
      + * 
      + * + * @since 4.7 + */ +public abstract class Verifier implements TestRule { + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + base.evaluate(); + verify(); + } + }; + } + + /** + * Override this to add verification logic. Overrides should throw an + * exception to indicate that verification failed. + */ + protected void verify() throws Throwable { + } +} diff --git a/src/main/java/org/junit/runner/Computer.java b/src/main/java/org/junit/runner/Computer.java new file mode 100644 index 000000000000..8bb4b20c1565 --- /dev/null +++ b/src/main/java/org/junit/runner/Computer.java @@ -0,0 +1,42 @@ +package org.junit.runner; + +import org.junit.runners.Suite; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; + +/** + * Represents a strategy for computing runners and suites. + * WARNING: this class is very likely to undergo serious changes in version 4.8 and + * beyond. + * + * @since 4.6 + */ +public class Computer { + /** + * Returns a new default computer, which runs tests in serial order + */ + public static Computer serial() { + return new Computer(); + } + + /** + * Create a suite for {@code classes}, building Runners with {@code builder}. + * Throws an InitializationError if Runner construction fails + */ + public Runner getSuite(final RunnerBuilder builder, + Class[] classes) throws InitializationError { + return new Suite(new RunnerBuilder() { + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + return getRunner(builder, testClass); + } + }, classes); + } + + /** + * Create a single-class runner for {@code testClass}, using {@code builder} + */ + protected Runner getRunner(RunnerBuilder builder, Class testClass) throws Throwable { + return builder.runnerForClass(testClass); + } +} diff --git a/src/main/java/org/junit/runner/Describable.java b/src/main/java/org/junit/runner/Describable.java new file mode 100644 index 000000000000..293fdb32a5c6 --- /dev/null +++ b/src/main/java/org/junit/runner/Describable.java @@ -0,0 +1,14 @@ +package org.junit.runner; + + +/** + * Represents an object that can describe itself + * + * @since 4.5 + */ +public interface Describable { + /** + * @return a {@link Description} showing the tests to be run by the receiver + */ + Description getDescription(); +} \ No newline at end of file diff --git a/src/main/java/org/junit/runner/Description.java b/src/main/java/org/junit/runner/Description.java new file mode 100644 index 000000000000..bbb833ec5b52 --- /dev/null +++ b/src/main/java/org/junit/runner/Description.java @@ -0,0 +1,316 @@ +package org.junit.runner; + +import java.io.Serializable; +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A Description describes a test which is to be run or has been run. Descriptions + * can be atomic (a single test) or compound (containing children tests). Descriptions are used + * to provide feedback about the tests that are about to run (for example, the tree view + * visible in many IDEs) or tests that have been run (for example, the failures view). + *

      + * Descriptions are implemented as a single class rather than a Composite because + * they are entirely informational. They contain no logic aside from counting their tests. + *

      + * In the past, we used the raw {@link junit.framework.TestCase}s and {@link junit.framework.TestSuite}s + * to display the tree of tests. This was no longer viable in JUnit 4 because atomic tests no longer have + * a superclass below {@link Object}. We needed a way to pass a class and name together. Description + * emerged from this. + * + * @see org.junit.runner.Request + * @see org.junit.runner.Runner + * @since 4.0 + */ +public class Description implements Serializable { + private static final long serialVersionUID = 1L; + + private static final Pattern METHOD_AND_CLASS_NAME_PATTERN = Pattern + .compile("([\\s\\S]*)\\((.*)\\)"); + + /** + * Create a Description named name. + * Generally, you will add children to this Description. + * + * @param name the name of the Description + * @param annotations meta-data about the test, for downstream interpreters + * @return a Description named name + */ + public static Description createSuiteDescription(String name, Annotation... annotations) { + return new Description(null, name, annotations); + } + + /** + * Create a Description named name. + * Generally, you will add children to this Description. + * + * @param name the name of the Description + * @param uniqueId an arbitrary object used to define uniqueness (in {@link #equals(Object)} + * @param annotations meta-data about the test, for downstream interpreters + * @return a Description named name + */ + public static Description createSuiteDescription(String name, Serializable uniqueId, Annotation... annotations) { + return new Description(null, name, uniqueId, annotations); + } + + /** + * Create a Description of a single test named name in the 'class' named + * className. Generally, this will be a leaf Description. This method is a better choice + * than {@link #createTestDescription(Class, String, Annotation...)} for test runners whose test cases are not + * defined in an actual Java Class. + * + * @param className the class name of the test + * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) + * @param annotations meta-data about the test, for downstream interpreters + * @return a Description named name + */ + public static Description createTestDescription(String className, String name, Annotation... annotations) { + return new Description(null, formatDisplayName(name, className), annotations); + } + + /** + * Create a Description of a single test named name in the class clazz. + * Generally, this will be a leaf Description. + * + * @param clazz the class of the test + * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) + * @param annotations meta-data about the test, for downstream interpreters + * @return a Description named name + */ + public static Description createTestDescription(Class clazz, String name, Annotation... annotations) { + return new Description(clazz, formatDisplayName(name, clazz.getName()), annotations); + } + + /** + * Create a Description of a single test named name in the class clazz. + * Generally, this will be a leaf Description. + * (This remains for binary compatibility with clients of JUnit 4.3) + * + * @param clazz the class of the test + * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) + * @return a Description named name + */ + public static Description createTestDescription(Class clazz, String name) { + return new Description(clazz, formatDisplayName(name, clazz.getName())); + } + + /** + * Create a Description of a single test named name in the class clazz. + * Generally, this will be a leaf Description. + * + * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) + * @return a Description named name + */ + public static Description createTestDescription(String className, String name, Serializable uniqueId) { + return new Description(null, formatDisplayName(name, className), uniqueId); + } + + private static String formatDisplayName(String name, String className) { + return String.format("%s(%s)", name, className); + } + + /** + * Create a Description named after testClass + * + * @param testClass A {@link Class} containing tests + * @return a Description of testClass + */ + public static Description createSuiteDescription(Class testClass) { + return new Description(testClass, testClass.getName(), testClass.getAnnotations()); + } + + /** + * Describes a Runner which runs no tests + */ + public static final Description EMPTY = new Description(null, "No Tests"); + + /** + * Describes a step in the test-running mechanism that goes so wrong no + * other description can be used (for example, an exception thrown from a Runner's + * constructor + */ + public static final Description TEST_MECHANISM = new Description(null, "Test mechanism"); + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final Collection fChildren = new ConcurrentLinkedQueue(); + private final String fDisplayName; + private final Serializable fUniqueId; + private final Annotation[] fAnnotations; + private volatile /* write-once */ Class fTestClass; + + private Description(Class clazz, String displayName, Annotation... annotations) { + this(clazz, displayName, displayName, annotations); + } + + private Description(Class testClass, String displayName, Serializable uniqueId, Annotation... annotations) { + if ((displayName == null) || (displayName.length() == 0)) { + throw new IllegalArgumentException( + "The display name must not be empty."); + } + if ((uniqueId == null)) { + throw new IllegalArgumentException( + "The unique id must not be null."); + } + this.fTestClass = testClass; + this.fDisplayName = displayName; + this.fUniqueId = uniqueId; + this.fAnnotations = annotations; + } + + /** + * @return a user-understandable label + */ + public String getDisplayName() { + return fDisplayName; + } + + /** + * Add Description as a child of the receiver. + * + * @param description the soon-to-be child. + */ + public void addChild(Description description) { + fChildren.add(description); + } + + /** + * Gets the copy of the children of this {@code Description}. + * Returns an empty list if there are no children. + */ + public ArrayList getChildren() { + return new ArrayList(fChildren); + } + + /** + * @return true if the receiver is a suite + */ + public boolean isSuite() { + return !isTest(); + } + + /** + * @return true if the receiver is an atomic test + */ + public boolean isTest() { + return fChildren.isEmpty(); + } + + /** + * @return the total number of atomic tests in the receiver + */ + public int testCount() { + if (isTest()) { + return 1; + } + int result = 0; + for (Description child : fChildren) { + result += child.testCount(); + } + return result; + } + + @Override + public int hashCode() { + return fUniqueId.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Description)) { + return false; + } + Description d = (Description) obj; + return fUniqueId.equals(d.fUniqueId); + } + + @Override + public String toString() { + return getDisplayName(); + } + + /** + * @return true if this is a description of a Runner that runs no tests + */ + public boolean isEmpty() { + return equals(EMPTY); + } + + /** + * @return a copy of this description, with no children (on the assumption that some of the + * children will be added back) + */ + public Description childlessCopy() { + return new Description(fTestClass, fDisplayName, fAnnotations); + } + + /** + * @return the annotation of type annotationType that is attached to this description node, + * or null if none exists + */ + public T getAnnotation(Class annotationType) { + for (Annotation each : fAnnotations) { + if (each.annotationType().equals(annotationType)) { + return annotationType.cast(each); + } + } + return null; + } + + /** + * @return all of the annotations attached to this description node + */ + public Collection getAnnotations() { + return Arrays.asList(fAnnotations); + } + + /** + * @return If this describes a method invocation, + * the class of the test instance. + */ + public Class getTestClass() { + if (fTestClass != null) { + return fTestClass; + } + String name = getClassName(); + if (name == null) { + return null; + } + try { + fTestClass = Class.forName(name, false, getClass().getClassLoader()); + return fTestClass; + } catch (ClassNotFoundException e) { + return null; + } + } + + /** + * @return If this describes a method invocation, + * the name of the class of the test instance + */ + public String getClassName() { + return fTestClass != null ? fTestClass.getName() : methodAndClassNamePatternGroupOrDefault(2, toString()); + } + + /** + * @return If this describes a method invocation, + * the name of the method (or null if not) + */ + public String getMethodName() { + return methodAndClassNamePatternGroupOrDefault(1, null); + } + + private String methodAndClassNamePatternGroupOrDefault(int group, + String defaultString) { + Matcher matcher = METHOD_AND_CLASS_NAME_PATTERN.matcher(toString()); + return matcher.matches() ? matcher.group(group) : defaultString; + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/runner/FilterFactories.java b/src/main/java/org/junit/runner/FilterFactories.java new file mode 100644 index 000000000000..020d39445d80 --- /dev/null +++ b/src/main/java/org/junit/runner/FilterFactories.java @@ -0,0 +1,82 @@ +package org.junit.runner; + +import org.junit.internal.Classes; +import org.junit.runner.FilterFactory.FilterNotCreatedException; +import org.junit.runner.manipulation.Filter; + +/** + * Utility class whose methods create a {@link FilterFactory}. + */ +class FilterFactories { + /** + * Creates a {@link Filter}. + * + * A filter specification is of the form "package.of.FilterFactory=args-to-filter-factory" or + * "package.of.FilterFactory". + * + * @param request the request that will be filtered + * @param filterSpec the filter specification + * @throws org.junit.runner.FilterFactory.FilterNotCreatedException + */ + public static Filter createFilterFromFilterSpec(Request request, String filterSpec) + throws FilterFactory.FilterNotCreatedException { + Description topLevelDescription = request.getRunner().getDescription(); + String[] tuple; + + if (filterSpec.contains("=")) { + tuple = filterSpec.split("=", 2); + } else { + tuple = new String[]{ filterSpec, "" }; + } + + return createFilter(tuple[0], new FilterFactoryParams(topLevelDescription, tuple[1])); + } + + /** + * Creates a {@link Filter}. + * + * @param filterFactoryFqcn The fully qualified class name of the {@link FilterFactory} + * @param params The arguments to the {@link FilterFactory} + */ + public static Filter createFilter(String filterFactoryFqcn, FilterFactoryParams params) + throws FilterFactory.FilterNotCreatedException { + FilterFactory filterFactory = createFilterFactory(filterFactoryFqcn); + + return filterFactory.createFilter(params); + } + + /** + * Creates a {@link Filter}. + * + * @param filterFactoryClass The class of the {@link FilterFactory} + * @param params The arguments to the {@link FilterFactory} + * + */ + public static Filter createFilter(Class filterFactoryClass, FilterFactoryParams params) + throws FilterFactory.FilterNotCreatedException { + FilterFactory filterFactory = createFilterFactory(filterFactoryClass); + + return filterFactory.createFilter(params); + } + + static FilterFactory createFilterFactory(String filterFactoryFqcn) throws FilterNotCreatedException { + Class filterFactoryClass; + + try { + filterFactoryClass = Classes.getClass(filterFactoryFqcn).asSubclass(FilterFactory.class); + } catch (Exception e) { + throw new FilterNotCreatedException(e); + } + + return createFilterFactory(filterFactoryClass); + } + + static FilterFactory createFilterFactory(Class filterFactoryClass) + throws FilterNotCreatedException { + try { + return filterFactoryClass.getConstructor().newInstance(); + } catch (Exception e) { + throw new FilterNotCreatedException(e); + } + } +} diff --git a/src/main/java/org/junit/runner/FilterFactory.java b/src/main/java/org/junit/runner/FilterFactory.java new file mode 100644 index 000000000000..e2bfb7358044 --- /dev/null +++ b/src/main/java/org/junit/runner/FilterFactory.java @@ -0,0 +1,25 @@ +package org.junit.runner; + +import org.junit.runner.manipulation.Filter; + +/** + * Extend this class to create a factory that creates {@link Filter}. + */ +public interface FilterFactory { + /** + * Creates a {@link Filter} given a {@link FilterFactoryParams} argument. + * + * @param params Parameters needed to create the {@link Filter} + */ + Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException; + + /** + * Exception thrown if the {@link Filter} cannot be created. + */ + @SuppressWarnings("serial") + class FilterNotCreatedException extends Exception { + public FilterNotCreatedException(Exception exception) { + super(exception.getMessage(), exception); + } + } +} diff --git a/src/main/java/org/junit/runner/FilterFactoryParams.java b/src/main/java/org/junit/runner/FilterFactoryParams.java new file mode 100644 index 000000000000..1e74ab91acd4 --- /dev/null +++ b/src/main/java/org/junit/runner/FilterFactoryParams.java @@ -0,0 +1,23 @@ +package org.junit.runner; + +public final class FilterFactoryParams { + private final Description topLevelDescription; + private final String args; + + public FilterFactoryParams(Description topLevelDescription, String args) { + if (args == null || topLevelDescription == null) { + throw new NullPointerException(); + } + + this.topLevelDescription = topLevelDescription; + this.args = args; + } + + public String getArgs() { + return args; + } + + public Description getTopLevelDescription() { + return topLevelDescription; + } +} diff --git a/src/main/java/org/junit/runner/JUnitCommandLineParseResult.java b/src/main/java/org/junit/runner/JUnitCommandLineParseResult.java new file mode 100644 index 000000000000..338340789ee8 --- /dev/null +++ b/src/main/java/org/junit/runner/JUnitCommandLineParseResult.java @@ -0,0 +1,147 @@ +package org.junit.runner; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.internal.Classes; +import org.junit.runner.FilterFactory.FilterNotCreatedException; +import org.junit.runner.manipulation.Filter; +import org.junit.runners.model.InitializationError; + +class JUnitCommandLineParseResult { + private final List filterSpecs = new ArrayList(); + private final List> classes = new ArrayList>(); + private final List parserErrors = new ArrayList(); + + /** + * Do not use. Testing purposes only. + */ + JUnitCommandLineParseResult() {} + + /** + * Returns filter specs parsed from command line. + */ + public List getFilterSpecs() { + return Collections.unmodifiableList(filterSpecs); + } + + /** + * Returns test classes parsed from command line. + */ + public List> getClasses() { + return Collections.unmodifiableList(classes); + } + + /** + * Parses the arguments. + * + * @param args Arguments + */ + public static JUnitCommandLineParseResult parse(String[] args) { + JUnitCommandLineParseResult result = new JUnitCommandLineParseResult(); + + result.parseArgs(args); + + return result; + } + + private void parseArgs(String[] args) { + parseParameters(parseOptions(args)); + } + + String[] parseOptions(String... args) { + for (int i = 0; i != args.length; ++i) { + String arg = args[i]; + + if (arg.equals("--")) { + return copyArray(args, i + 1, args.length); + } else if (arg.startsWith("--")) { + if (arg.startsWith("--filter=") || arg.equals("--filter")) { + String filterSpec; + if (arg.equals("--filter")) { + ++i; + + if (i < args.length) { + filterSpec = args[i]; + } else { + parserErrors.add(new CommandLineParserError(arg + " value not specified")); + break; + } + } else { + filterSpec = arg.substring(arg.indexOf('=') + 1); + } + + filterSpecs.add(filterSpec); + } else { + parserErrors.add(new CommandLineParserError("JUnit knows nothing about the " + arg + " option")); + } + } else { + return copyArray(args, i, args.length); + } + } + + return new String[]{}; + } + + private String[] copyArray(String[] args, int from, int to) { + String[] result = new String[to - from]; + for (int j = from; j != to; ++j) { + result[j - from] = args[j]; + } + return result; + } + + void parseParameters(String[] args) { + for (String arg : args) { + try { + classes.add(Classes.getClass(arg)); + } catch (ClassNotFoundException e) { + parserErrors.add(new IllegalArgumentException("Could not find class [" + arg + "]", e)); + } + } + } + + private Request errorReport(Throwable cause) { + return Request.errorReport(JUnitCommandLineParseResult.class, cause); + } + + /** + * Creates a {@link Request}. + * + * @param computer {@link Computer} to be used. + */ + public Request createRequest(Computer computer) { + if (parserErrors.isEmpty()) { + Request request = Request.classes( + computer, classes.toArray(new Class[classes.size()])); + return applyFilterSpecs(request); + } else { + return errorReport(new InitializationError(parserErrors)); + } + } + + private Request applyFilterSpecs(Request request) { + try { + for (String filterSpec : filterSpecs) { + Filter filter = FilterFactories.createFilterFromFilterSpec( + request, filterSpec); + request = request.filterWith(filter); + } + return request; + } catch (FilterNotCreatedException e) { + return errorReport(e); + } + } + + /** + * Exception used if there's a problem parsing the command line. + */ + public static class CommandLineParserError extends Exception { + private static final long serialVersionUID= 1L; + + public CommandLineParserError(String message) { + super(message); + } + } +} diff --git a/src/main/java/org/junit/runner/JUnitCore.java b/src/main/java/org/junit/runner/JUnitCore.java new file mode 100644 index 000000000000..c1479e004d5d --- /dev/null +++ b/src/main/java/org/junit/runner/JUnitCore.java @@ -0,0 +1,167 @@ +package org.junit.runner; + +import junit.runner.Version; +import org.junit.internal.JUnitSystem; +import org.junit.internal.RealSystem; +import org.junit.internal.TextListener; +import org.junit.internal.runners.JUnit38ClassRunner; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.RunNotifier; + +/** + * JUnitCore is a facade for running tests. It supports running JUnit 4 tests, + * JUnit 3.8.x tests, and mixtures. To run tests from the command line, run + * java org.junit.runner.JUnitCore TestClass1 TestClass2 .... + * For one-shot test runs, use the static method {@link #runClasses(Class[])}. + * If you want to add special listeners, + * create an instance of {@link org.junit.runner.JUnitCore} first and use it to run the tests. + * + * @see org.junit.runner.Result + * @see org.junit.runner.notification.RunListener + * @see org.junit.runner.Request + * @since 4.0 + */ +public class JUnitCore { + private final RunNotifier notifier = new RunNotifier(); + + /** + * Run the tests contained in the classes named in the args. + * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. + * Write feedback while tests are running and write + * stack traces for all failed tests after the tests all complete. + * + * @param args names of classes in which to find tests to run + */ + public static void main(String... args) { + Result result = new JUnitCore().runMain(new RealSystem(), args); + System.exit(result.wasSuccessful() ? 0 : 1); + } + + /** + * Run the tests contained in classes. Write feedback while the tests + * are running and write stack traces for all failed tests after all tests complete. This is + * similar to {@link #main(String[])}, but intended to be used programmatically. + * + * @param classes Classes in which to find tests + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public static Result runClasses(Class... classes) { + return runClasses(defaultComputer(), classes); + } + + /** + * Run the tests contained in classes. Write feedback while the tests + * are running and write stack traces for all failed tests after all tests complete. This is + * similar to {@link #main(String[])}, but intended to be used programmatically. + * + * @param computer Helps construct Runners from classes + * @param classes Classes in which to find tests + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public static Result runClasses(Computer computer, Class... classes) { + return new JUnitCore().run(computer, classes); + } + + /** + * @param system + * @param args from main() + */ + Result runMain(JUnitSystem system, String... args) { + system.out().println("JUnit version " + Version.id()); + + JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args); + + RunListener listener = new TextListener(system); + addListener(listener); + + return run(jUnitCommandLineParseResult.createRequest(defaultComputer())); + } + + /** + * @return the version number of this release + */ + public String getVersion() { + return Version.id(); + } + + /** + * Run all the tests in classes. + * + * @param classes the classes containing tests + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(Class... classes) { + return run(defaultComputer(), classes); + } + + /** + * Run all the tests in classes. + * + * @param computer Helps construct Runners from classes + * @param classes the classes containing tests + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(Computer computer, Class... classes) { + return run(Request.classes(computer, classes)); + } + + /** + * Run all the tests contained in request. + * + * @param request the request describing tests + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(Request request) { + return run(request.getRunner()); + } + + /** + * Run all the tests contained in JUnit 3.8.x test. Here for backward compatibility. + * + * @param test the old-style test + * @return a {@link Result} describing the details of the test run and the failed tests. + */ + public Result run(junit.framework.Test test) { + return run(new JUnit38ClassRunner(test)); + } + + /** + * Do not use. Testing purposes only. + */ + public Result run(Runner runner) { + Result result = new Result(); + RunListener listener = result.createListener(); + notifier.addFirstListener(listener); + try { + notifier.fireTestRunStarted(runner.getDescription()); + runner.run(notifier); + notifier.fireTestRunFinished(result); + } finally { + removeListener(listener); + } + return result; + } + + /** + * Add a listener to be notified as the tests run. + * + * @param listener the listener to add + * @see org.junit.runner.notification.RunListener + */ + public void addListener(RunListener listener) { + notifier.addListener(listener); + } + + /** + * Remove a listener. + * + * @param listener the listener to remove + */ + public void removeListener(RunListener listener) { + notifier.removeListener(listener); + } + + static Computer defaultComputer() { + return new Computer(); + } +} diff --git a/src/main/java/org/junit/runner/Request.java b/src/main/java/org/junit/runner/Request.java new file mode 100644 index 000000000000..fcb29e72f720 --- /dev/null +++ b/src/main/java/org/junit/runner/Request.java @@ -0,0 +1,169 @@ +package org.junit.runner; + +import java.util.Comparator; + +import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; +import org.junit.internal.requests.ClassRequest; +import org.junit.internal.requests.FilterRequest; +import org.junit.internal.requests.SortingRequest; +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.manipulation.Filter; +import org.junit.runners.model.InitializationError; + +/** + * A Request is an abstract description of tests to be run. Older versions of + * JUnit did not need such a concept--tests to be run were described either by classes containing + * tests or a tree of {@link org.junit.Test}s. However, we want to support filtering and sorting, + * so we need a more abstract specification than the tests themselves and a richer + * specification than just the classes. + * + *

      The flow when JUnit runs tests is that a Request specifies some tests to be run -> + * a {@link org.junit.runner.Runner} is created for each class implied by the Request -> + * the {@link org.junit.runner.Runner} returns a detailed {@link org.junit.runner.Description} + * which is a tree structure of the tests to be run. + * + * @since 4.0 + */ +public abstract class Request { + /** + * Create a Request that, when processed, will run a single test. + * This is done by filtering out all other tests. This method is used to support rerunning + * single tests. + * + * @param clazz the class of the test + * @param methodName the name of the test + * @return a Request that will cause a single test be run + */ + public static Request method(Class clazz, String methodName) { + Description method = Description.createTestDescription(clazz, methodName); + return Request.aClass(clazz).filterWith(method); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a class. The odd name is necessary because class is a reserved word. + * + * @param clazz the class containing the tests + * @return a Request that will cause all tests in the class to be run + */ + public static Request aClass(Class clazz) { + return new ClassRequest(clazz); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a class. If the class has a suite() method, it will be ignored. + * + * @param clazz the class containing the tests + * @return a Request that will cause all tests in the class to be run + */ + public static Request classWithoutSuiteMethod(Class clazz) { + return new ClassRequest(clazz, false); + } + + /** + * Create a Request that, when processed, will run all the tests + * in a set of classes. + * + * @param computer Helps construct Runners from classes + * @param classes the classes containing the tests + * @return a Request that will cause all tests in the classes to be run + */ + public static Request classes(Computer computer, Class... classes) { + try { + AllDefaultPossibilitiesBuilder builder = new AllDefaultPossibilitiesBuilder(true); + Runner suite = computer.getSuite(builder, classes); + return runner(suite); + } catch (InitializationError e) { + return runner(new ErrorReportingRunner(e, classes)); + } + } + + /** + * Create a Request that, when processed, will run all the tests + * in a set of classes with the default Computer. + * + * @param classes the classes containing the tests + * @return a Request that will cause all tests in the classes to be run + */ + public static Request classes(Class... classes) { + return classes(JUnitCore.defaultComputer(), classes); + } + + + /** + * Creates a {@link Request} that, when processed, will report an error for the given + * test class with the given cause. + */ + public static Request errorReport(Class klass, Throwable cause) { + return runner(new ErrorReportingRunner(klass, cause)); + } + + /** + * @param runner the runner to return + * @return a Request that will run the given runner when invoked + */ + public static Request runner(final Runner runner) { + return new Request() { + @Override + public Runner getRunner() { + return runner; + } + }; + } + + /** + * Returns a {@link Runner} for this Request + * + * @return corresponding {@link Runner} for this Request + */ + public abstract Runner getRunner(); + + /** + * Returns a Request that only contains those tests that should run when + * filter is applied + * + * @param filter The {@link Filter} to apply to this Request + * @return the filtered Request + */ + public Request filterWith(Filter filter) { + return new FilterRequest(this, filter); + } + + /** + * Returns a Request that only runs contains tests whose {@link Description} + * equals desiredDescription + * + * @param desiredDescription {@link Description} of those tests that should be run + * @return the filtered Request + */ + public Request filterWith(final Description desiredDescription) { + return filterWith(Filter.matchMethodDescription(desiredDescription)); + } + + /** + * Returns a Request whose Tests can be run in a certain order, defined by + * comparator + *

      + * For example, here is code to run a test suite in alphabetical order: + *

      +     * private static Comparator<Description> forward() {
      +     * return new Comparator<Description>() {
      +     * public int compare(Description o1, Description o2) {
      +     * return o1.getDisplayName().compareTo(o2.getDisplayName());
      +     * }
      +     * };
      +     * }
      +     *
      +     * public static main() {
      +     * new JUnitCore().run(Request.aClass(AllTests.class).sortWith(forward()));
      +     * }
      +     * 
      + * + * @param comparator definition of the order of the tests in this Request + * @return a Request with ordered Tests + */ + public Request sortWith(Comparator comparator) { + return new SortingRequest(this, comparator); + } +} diff --git a/src/main/java/org/junit/runner/Result.java b/src/main/java/org/junit/runner/Result.java new file mode 100644 index 000000000000..73ad059caefb --- /dev/null +++ b/src/main/java/org/junit/runner/Result.java @@ -0,0 +1,196 @@ +package org.junit.runner; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; +import java.io.ObjectStreamField; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + +/** + * A Result collects and summarizes information from running multiple tests. + * All tests are counted -- additional information is collected from tests that fail. + * + * @since 4.0 + */ +public class Result implements Serializable { + private static final long serialVersionUID = 1L; + private static final ObjectStreamField[] serialPersistentFields = + ObjectStreamClass.lookup(SerializedForm.class).getFields(); + private final AtomicInteger count; + private final AtomicInteger ignoreCount; + private final CopyOnWriteArrayList failures; + private final AtomicLong runTime; + private final AtomicLong startTime; + + /** Only set during deserialization process. */ + private SerializedForm serializedForm; + + public Result() { + count = new AtomicInteger(); + ignoreCount = new AtomicInteger(); + failures = new CopyOnWriteArrayList(); + runTime = new AtomicLong(); + startTime = new AtomicLong(); + } + + private Result(SerializedForm serializedForm) { + count = serializedForm.fCount; + ignoreCount = serializedForm.fIgnoreCount; + failures = new CopyOnWriteArrayList(serializedForm.fFailures); + runTime = new AtomicLong(serializedForm.fRunTime); + startTime = new AtomicLong(serializedForm.fStartTime); + } + + /** + * @return the number of tests run + */ + public int getRunCount() { + return count.get(); + } + + /** + * @return the number of tests that failed during the run + */ + public int getFailureCount() { + return failures.size(); + } + + /** + * @return the number of milliseconds it took to run the entire suite to run + */ + public long getRunTime() { + return runTime.get(); + } + + /** + * @return the {@link Failure}s describing tests that failed and the problems they encountered + */ + public List getFailures() { + return failures; + } + + /** + * @return the number of tests ignored during the run + */ + public int getIgnoreCount() { + return ignoreCount.get(); + } + + /** + * @return true if all tests succeeded + */ + public boolean wasSuccessful() { + return getFailureCount() == 0; + } + + private void writeObject(ObjectOutputStream s) throws IOException { + SerializedForm serializedForm = new SerializedForm(this); + serializedForm.serialize(s); + } + + private void readObject(ObjectInputStream s) + throws ClassNotFoundException, IOException { + serializedForm = SerializedForm.deserialize(s); + } + + private Object readResolve() { + return new Result(serializedForm); + } + + @RunListener.ThreadSafe + private class Listener extends RunListener { + @Override + public void testRunStarted(Description description) throws Exception { + startTime.set(System.currentTimeMillis()); + } + + @Override + public void testRunFinished(Result result) throws Exception { + long endTime = System.currentTimeMillis(); + runTime.addAndGet(endTime - startTime.get()); + } + + @Override + public void testFinished(Description description) throws Exception { + count.getAndIncrement(); + } + + @Override + public void testFailure(Failure failure) throws Exception { + failures.add(failure); + } + + @Override + public void testIgnored(Description description) throws Exception { + ignoreCount.getAndIncrement(); + } + + @Override + public void testAssumptionFailure(Failure failure) { + // do nothing: same as passing (for 4.5; may change in 4.6) + } + } + + /** + * Internal use only. + */ + public RunListener createListener() { + return new Listener(); + } + + /** + * Represents the serialized output of {@code Result}. The fields on this + * class match the files that {@code Result} had in JUnit 4.11. + */ + private static class SerializedForm implements Serializable { + private static final long serialVersionUID = 1L; + private final AtomicInteger fCount; + private final AtomicInteger fIgnoreCount; + private final List fFailures; + private final long fRunTime; + private final long fStartTime; + + public SerializedForm(Result result) { + fCount = result.count; + fIgnoreCount = result.ignoreCount; + fFailures = Collections.synchronizedList(new ArrayList(result.failures)); + fRunTime = result.runTime.longValue(); + fStartTime = result.startTime.longValue(); + } + + @SuppressWarnings("unchecked") + private SerializedForm(ObjectInputStream.GetField fields) throws IOException { + fCount = (AtomicInteger) fields.get("fCount", null); + fIgnoreCount = (AtomicInteger) fields.get("fIgnoreCount", null); + fFailures = (List) fields.get("fFailures", null); + fRunTime = fields.get("fRunTime", 0L); + fStartTime = fields.get("fStartTime", 0L); + } + + public void serialize(ObjectOutputStream s) throws IOException { + ObjectOutputStream.PutField fields = s.putFields(); + fields.put("fCount", fCount); + fields.put("fIgnoreCount", fIgnoreCount); + fields.put("fFailures", fFailures); + fields.put("fRunTime", fRunTime); + fields.put("fStartTime", fStartTime); + s.writeFields(); + } + + public static SerializedForm deserialize(ObjectInputStream s) + throws ClassNotFoundException, IOException { + ObjectInputStream.GetField fields = s.readFields(); + return new SerializedForm(fields); + } + } +} diff --git a/src/main/java/org/junit/runner/RunWith.java b/src/main/java/org/junit/runner/RunWith.java new file mode 100644 index 000000000000..3428ee28add4 --- /dev/null +++ b/src/main/java/org/junit/runner/RunWith.java @@ -0,0 +1,36 @@ +package org.junit.runner; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * When a class is annotated with @RunWith or extends a class annotated + * with @RunWith, JUnit will invoke the class it references to run the + * tests in that class instead of the runner built into JUnit. We added this feature late + * in development. While it seems powerful we expect the runner API to change as we learn + * how people really use it. Some of the classes that are currently internal will likely + * be refined and become public. + * + * For example, suites in JUnit 4 are built using RunWith, and a custom runner named Suite: + * + *
      + * @RunWith(Suite.class)
      + * @SuiteClasses({ATest.class, BTest.class, CTest.class})
      + * public class ABCSuite {
      + * }
      + * 
      + * + * @since 4.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface RunWith { + /** + * @return a Runner class (must have a constructor that takes a single Class to run) + */ + Class value(); +} diff --git a/src/main/java/org/junit/runner/Runner.java b/src/main/java/org/junit/runner/Runner.java new file mode 100644 index 000000000000..d728dd82c591 --- /dev/null +++ b/src/main/java/org/junit/runner/Runner.java @@ -0,0 +1,43 @@ +package org.junit.runner; + +import org.junit.runner.notification.RunNotifier; + +/** + * A Runner runs tests and notifies a {@link org.junit.runner.notification.RunNotifier} + * of significant events as it does so. You will need to subclass Runner + * when using {@link org.junit.runner.RunWith} to invoke a custom runner. When creating + * a custom runner, in addition to implementing the abstract methods here you must + * also provide a constructor that takes as an argument the {@link Class} containing + * the tests. + * + *

      The default runner implementation guarantees that the instances of the test case + * class will be constructed immediately before running the test and that the runner + * will retain no reference to the test case instances, generally making them + * available for garbage collection. + * + * @see org.junit.runner.Description + * @see org.junit.runner.RunWith + * @since 4.0 + */ +public abstract class Runner implements Describable { + /* + * (non-Javadoc) + * @see org.junit.runner.Describable#getDescription() + */ + public abstract Description getDescription(); + + /** + * Run the tests for this runner. + * + * @param notifier will be notified of events while tests are being run--tests being + * started, finishing, and failing + */ + public abstract void run(RunNotifier notifier); + + /** + * @return the number of tests to be run by the receiver + */ + public int testCount() { + return getDescription().testCount(); + } +} diff --git a/src/main/java/org/junit/runner/manipulation/Filter.java b/src/main/java/org/junit/runner/manipulation/Filter.java new file mode 100644 index 000000000000..0287351f47df --- /dev/null +++ b/src/main/java/org/junit/runner/manipulation/Filter.java @@ -0,0 +1,122 @@ +package org.junit.runner.manipulation; + +import org.junit.runner.Description; +import org.junit.runner.Request; + +/** + * The canonical case of filtering is when you want to run a single test method in a class. Rather + * than introduce runner API just for that one case, JUnit provides a general filtering mechanism. + * If you want to filter the tests to be run, extend Filter and apply an instance of + * your filter to the {@link org.junit.runner.Request} before running it (see + * {@link org.junit.runner.JUnitCore#run(Request)}. Alternatively, apply a Filter to + * a {@link org.junit.runner.Runner} before running tests (for example, in conjunction with + * {@link org.junit.runner.RunWith}. + * + * @since 4.0 + */ +public abstract class Filter { + /** + * A null Filter that passes all tests through. + */ + public static final Filter ALL = new Filter() { + @Override + public boolean shouldRun(Description description) { + return true; + } + + @Override + public String describe() { + return "all tests"; + } + + @Override + public void apply(Object child) throws NoTestsRemainException { + // do nothing + } + + @Override + public Filter intersect(Filter second) { + return second; + } + }; + + /** + * Returns a {@code Filter} that only runs the single method described by + * {@code desiredDescription} + */ + public static Filter matchMethodDescription(final Description desiredDescription) { + return new Filter() { + @Override + public boolean shouldRun(Description description) { + if (description.isTest()) { + return desiredDescription.equals(description); + } + + // explicitly check if any children want to run + for (Description each : description.getChildren()) { + if (shouldRun(each)) { + return true; + } + } + return false; + } + + @Override + public String describe() { + return String.format("Method %s", desiredDescription.getDisplayName()); + } + }; + } + + + /** + * @param description the description of the test to be run + * @return true if the test should be run + */ + public abstract boolean shouldRun(Description description); + + /** + * Returns a textual description of this Filter + * + * @return a textual description of this Filter + */ + public abstract String describe(); + + /** + * Invoke with a {@link org.junit.runner.Runner} to cause all tests it intends to run + * to first be checked with the filter. Only those that pass the filter will be run. + * + * @param child the runner to be filtered by the receiver + * @throws NoTestsRemainException if the receiver removes all tests + */ + public void apply(Object child) throws NoTestsRemainException { + if (!(child instanceof Filterable)) { + return; + } + Filterable filterable = (Filterable) child; + filterable.filter(this); + } + + /** + * Returns a new Filter that accepts the intersection of the tests accepted + * by this Filter and {@code second} + */ + public Filter intersect(final Filter second) { + if (second == this || second == ALL) { + return this; + } + final Filter first = this; + return new Filter() { + @Override + public boolean shouldRun(Description description) { + return first.shouldRun(description) + && second.shouldRun(description); + } + + @Override + public String describe() { + return first.describe() + " and " + second.describe(); + } + }; + } +} diff --git a/src/main/java/org/junit/runner/manipulation/Filterable.java b/src/main/java/org/junit/runner/manipulation/Filterable.java new file mode 100644 index 000000000000..d605027ec3b6 --- /dev/null +++ b/src/main/java/org/junit/runner/manipulation/Filterable.java @@ -0,0 +1,19 @@ +package org.junit.runner.manipulation; + +/** + * Runners that allow filtering should implement this interface. Implement {@link #filter(Filter)} + * to remove tests that don't pass the filter. + * + * @since 4.0 + */ +public interface Filterable { + + /** + * Remove tests that don't pass the parameter filter. + * + * @param filter the {@link Filter} to apply + * @throws NoTestsRemainException if all tests are filtered out + */ + void filter(Filter filter) throws NoTestsRemainException; + +} diff --git a/src/main/java/org/junit/runner/manipulation/NoTestsRemainException.java b/src/main/java/org/junit/runner/manipulation/NoTestsRemainException.java new file mode 100644 index 000000000000..21935bde64cf --- /dev/null +++ b/src/main/java/org/junit/runner/manipulation/NoTestsRemainException.java @@ -0,0 +1,10 @@ +package org.junit.runner.manipulation; + +/** + * Thrown when a filter removes all tests from a runner. + * + * @since 4.0 + */ +public class NoTestsRemainException extends Exception { + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/org/junit/runner/manipulation/Sortable.java b/src/main/java/org/junit/runner/manipulation/Sortable.java new file mode 100644 index 000000000000..0c59f330a371 --- /dev/null +++ b/src/main/java/org/junit/runner/manipulation/Sortable.java @@ -0,0 +1,20 @@ +package org.junit.runner.manipulation; + +/** + * Interface for runners that allow sorting of tests. By sorting tests based on when they last failed, most recently + * failed first, you can reduce the average time to the first test failing. Test sorting should not be used to + * cope with order dependencies between tests. Tests that are isolated from each other are less + * expensive to maintain and can be run individually. + * + * @since 4.0 + */ +public interface Sortable { + + /** + * Sorts the tests using sorter + * + * @param sorter the {@link Sorter} to use for sorting the tests + */ + void sort(Sorter sorter); + +} diff --git a/src/main/java/org/junit/runner/manipulation/Sorter.java b/src/main/java/org/junit/runner/manipulation/Sorter.java new file mode 100644 index 000000000000..20192d0c96e8 --- /dev/null +++ b/src/main/java/org/junit/runner/manipulation/Sorter.java @@ -0,0 +1,48 @@ +package org.junit.runner.manipulation; + +import java.util.Comparator; + +import org.junit.runner.Description; + +/** + * A Sorter orders tests. In general you will not need + * to use a Sorter directly. Instead, use {@link org.junit.runner.Request#sortWith(Comparator)}. + * + * @since 4.0 + */ +public class Sorter implements Comparator { + /** + * NULL is a Sorter that leaves elements in an undefined order + */ + public static final Sorter NULL = new Sorter(new Comparator() { + public int compare(Description o1, Description o2) { + return 0; + } + }); + + private final Comparator comparator; + + /** + * Creates a Sorter that uses comparator + * to sort tests + * + * @param comparator the {@link Comparator} to use when sorting tests + */ + public Sorter(Comparator comparator) { + this.comparator = comparator; + } + + /** + * Sorts the test in runner using comparator + */ + public void apply(Object object) { + if (object instanceof Sortable) { + Sortable sortable = (Sortable) object; + sortable.sort(this); + } + } + + public int compare(Description o1, Description o2) { + return comparator.compare(o1, o2); + } +} diff --git a/src/main/java/org/junit/runner/manipulation/package-info.java b/src/main/java/org/junit/runner/manipulation/package-info.java new file mode 100644 index 000000000000..ba5c3b2ed8ef --- /dev/null +++ b/src/main/java/org/junit/runner/manipulation/package-info.java @@ -0,0 +1,7 @@ +/** + * Provides classes to {@link org.junit.runner.manipulation.Filter filter} or {@link org.junit.runner.manipulation.Sorter sort} tests. + * + * @since 4.0 + * @see org.junit.runner.Runner + */ +package org.junit.runner.manipulation; \ No newline at end of file diff --git a/src/main/java/org/junit/runner/notification/Failure.java b/src/main/java/org/junit/runner/notification/Failure.java new file mode 100644 index 000000000000..267d157d7069 --- /dev/null +++ b/src/main/java/org/junit/runner/notification/Failure.java @@ -0,0 +1,83 @@ +package org.junit.runner.notification; + +import java.io.Serializable; + +import org.junit.internal.Throwables; +import org.junit.runner.Description; + +/** + * A Failure holds a description of the failed test and the + * exception that was thrown while running it. In most cases the {@link org.junit.runner.Description} + * will be of a single test. However, if problems are encountered while constructing the + * test (for example, if a {@link org.junit.BeforeClass} method is not static), it may describe + * something other than a single test. + * + * @since 4.0 + */ +public class Failure implements Serializable { + private static final long serialVersionUID = 1L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final Description fDescription; + private final Throwable fThrownException; + + /** + * Constructs a Failure with the given description and exception. + * + * @param description a {@link org.junit.runner.Description} of the test that failed + * @param thrownException the exception that was thrown while running the test + */ + public Failure(Description description, Throwable thrownException) { + this.fThrownException = thrownException; + this.fDescription = description; + } + + /** + * @return a user-understandable label for the test + */ + public String getTestHeader() { + return fDescription.getDisplayName(); + } + + /** + * @return the raw description of the context of the failure. + */ + public Description getDescription() { + return fDescription; + } + + /** + * @return the exception thrown + */ + + public Throwable getException() { + return fThrownException; + } + + @Override + public String toString() { + return getTestHeader() + ": " + fThrownException.getMessage(); + } + + /** + * Convenience method + * + * @return the printed form of the exception + */ + public String getTrace() { + return Throwables.getStacktrace(getException()); + } + + /** + * Convenience method + * + * @return the message of the thrown exception + */ + public String getMessage() { + return getException().getMessage(); + } +} diff --git a/src/main/java/org/junit/runner/notification/RunListener.java b/src/main/java/org/junit/runner/notification/RunListener.java new file mode 100644 index 000000000000..9048c5016f37 --- /dev/null +++ b/src/main/java/org/junit/runner/notification/RunListener.java @@ -0,0 +1,168 @@ +package org.junit.runner.notification; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.runner.Description; +import org.junit.runner.Result; + +/** + * Register an instance of this class with {@link RunNotifier} to be notified + * of events that occur during a test run. All of the methods in this class + * are abstract and have no implementation; override one or more methods to + * receive events. + *

      + * For example, suppose you have a Cowbell + * class that you want to make a noise whenever a test fails. You could write: + *

      + * public class RingingListener extends RunListener {
      + *    public void testFailure(Failure failure) {
      + *       Cowbell.ring();
      + *    }
      + * }
      + * 
      + *

      + * To invoke your listener, you need to run your tests through JUnitCore. + *

      + * public void main(String... args) {
      + *    JUnitCore core= new JUnitCore();
      + *    core.addListener(new RingingListener());
      + *    core.run(MyTestClass.class);
      + * }
      + * 
      + *

      + * If a listener throws an exception for a test event, the other listeners will + * have their {@link RunListener#testFailure(Failure)} called with a {@code Description} + * of {@link Description#TEST_MECHANISM} to indicate the failure. + *

      + * By default, JUnit will synchronize calls to your listener. If your listener + * is thread-safe and you want to allow JUnit to call your listener from + * multiple threads when tests are run in parallel, you can annotate your + * test class with {@link RunListener.ThreadSafe}. + *

      + * Listener methods will be called from the same thread as is running + * the test, unless otherwise indicated by the method Javadoc + * + * @see org.junit.runner.JUnitCore + * @since 4.0 + */ +public class RunListener { + + /** + * Called before any tests have been run. This may be called on an + * arbitrary thread. + * + * @param description describes the tests to be run + */ + public void testRunStarted(Description description) throws Exception { + } + + /** + * Called when all tests have finished. This may be called on an + * arbitrary thread. + * + * @param result the summary of the test run, including all the tests that failed + */ + public void testRunFinished(Result result) throws Exception { + } + + /** + * Called when a test suite is about to be started. If this method is + * called for a given {@link Description}, then {@link #testSuiteFinished(Description)} + * will also be called for the same {@code Description}. + * + *

      Note that not all runners will call this method, so runners should + * be prepared to handle {@link #testStarted(Description)} calls for tests + * where there was no cooresponding {@code testSuiteStarted()} call for + * the parent {@code Description}. + * + * @param description the description of the test suite that is about to be run + * (generally a class name) + * @since 4.13 + */ + public void testSuiteStarted(Description description) throws Exception { + } + + /** + * Called when a test suite has finished, whether the test suite succeeds or fails. + * This method will not be called for a given {@link Description} unless + * {@link #testSuiteStarted(Description)} was called for the same @code Description}. + * + * @param description the description of the test suite that just ran + * @since 4.13 + */ + public void testSuiteFinished(Description description) throws Exception { + } + + /** + * Called when an atomic test is about to be started. + * + * @param description the description of the test that is about to be run + * (generally a class and method name) + */ + public void testStarted(Description description) throws Exception { + } + + /** + * Called when an atomic test has finished, whether the test succeeds or fails. + * + * @param description the description of the test that just ran + */ + public void testFinished(Description description) throws Exception { + } + + /** + * Called when an atomic test fails, or when a listener throws an exception. + * + *

      In the case of a failure of an atomic test, this method will be called + * with the same {@code Description} passed to + * {@link #testStarted(Description)}, from the same thread that called + * {@link #testStarted(Description)}. + * + *

      In the case of a listener throwing an exception, this will be called with + * a {@code Description} of {@link Description#TEST_MECHANISM}, and may be called + * on an arbitrary thread. + * + * @param failure describes the test that failed and the exception that was thrown + */ + public void testFailure(Failure failure) throws Exception { + } + + /** + * Called when an atomic test flags that it assumes a condition that is + * false + * + * @param failure describes the test that failed and the + * {@link org.junit.AssumptionViolatedException} that was thrown + */ + public void testAssumptionFailure(Failure failure) { + } + + /** + * Called when a test will not be run, generally because a test method is annotated + * with {@link org.junit.Ignore}. + * + * @param description describes the test that will not be run + */ + public void testIgnored(Description description) throws Exception { + } + + + /** + * Indicates a {@code RunListener} that can have its methods called + * concurrently. This implies that the class is thread-safe (i.e. no set of + * listener calls can put the listener into an invalid state, even if those + * listener calls are being made by multiple threads without + * synchronization). + * + * @since 4.12 + */ + @Documented + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + public @interface ThreadSafe { + } +} diff --git a/src/main/java/org/junit/runner/notification/RunNotifier.java b/src/main/java/org/junit/runner/notification/RunNotifier.java new file mode 100644 index 000000000000..8b686cdf287a --- /dev/null +++ b/src/main/java/org/junit/runner/notification/RunNotifier.java @@ -0,0 +1,249 @@ +package org.junit.runner.notification; + +import static java.util.Arrays.asList; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.junit.runner.Description; +import org.junit.runner.Result; + +/** + * If you write custom runners, you may need to notify JUnit of your progress running tests. + * Do this by invoking the RunNotifier passed to your implementation of + * {@link org.junit.runner.Runner#run(RunNotifier)}. Future evolution of this class is likely to + * move {@link #fireTestRunStarted(Description)} and {@link #fireTestRunFinished(Result)} + * to a separate class since they should only be called once per run. + * + * @since 4.0 + */ +public class RunNotifier { + private final List listeners = new CopyOnWriteArrayList(); + private volatile boolean pleaseStop = false; + + /** + * Internal use only + */ + public void addListener(RunListener listener) { + if (listener == null) { + throw new NullPointerException("Cannot add a null listener"); + } + listeners.add(wrapIfNotThreadSafe(listener)); + } + + /** + * Internal use only + */ + public void removeListener(RunListener listener) { + if (listener == null) { + throw new NullPointerException("Cannot remove a null listener"); + } + listeners.remove(wrapIfNotThreadSafe(listener)); + } + + /** + * Wraps the given listener with {@link SynchronizedRunListener} if + * it is not annotated with {@link RunListener.ThreadSafe}. + */ + RunListener wrapIfNotThreadSafe(RunListener listener) { + return listener.getClass().isAnnotationPresent(RunListener.ThreadSafe.class) ? + listener : new SynchronizedRunListener(listener, this); + } + + + private abstract class SafeNotifier { + private final List currentListeners; + + SafeNotifier() { + this(listeners); + } + + SafeNotifier(List currentListeners) { + this.currentListeners = currentListeners; + } + + void run() { + int capacity = currentListeners.size(); + List safeListeners = new ArrayList(capacity); + List failures = new ArrayList(capacity); + for (RunListener listener : currentListeners) { + try { + notifyListener(listener); + safeListeners.add(listener); + } catch (Exception e) { + failures.add(new Failure(Description.TEST_MECHANISM, e)); + } + } + fireTestFailures(safeListeners, failures); + } + + abstract protected void notifyListener(RunListener each) throws Exception; + } + + /** + * Do not invoke. + */ + public void fireTestRunStarted(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunStarted(description); + } + }.run(); + } + + /** + * Do not invoke. + */ + public void fireTestRunFinished(final Result result) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testRunFinished(result); + } + }.run(); + } + + /** + * Invoke to tell listeners that a test suite is about to start. Runners are strongly + * encouraged--but not required--to call this method. If this method is called for + * a given {@link Description} then {@link #fireTestSuiteFinished(Description)} MUST + * be called for the same {@code Description}. + * + * @param description the description of the suite test (generally a class name) + * @since 4.13 + */ + public void fireTestSuiteStarted(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testSuiteStarted(description); + } + }.run(); + } + + /** + * Invoke to tell listeners that a test suite is about to finish. Always invoke + * this method if you invoke {@link #fireTestSuiteStarted(Description)} + * as listeners are likely to expect them to come in pairs. + * + * @param description the description of the suite test (generally a class name) + * @since 4.13 + */ + public void fireTestSuiteFinished(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testSuiteFinished(description); + } + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test is about to start. + * + * @param description the description of the atomic test (generally a class and method name) + * @throws StoppedByUserException thrown if a user has requested that the test run stop + */ + public void fireTestStarted(final Description description) throws StoppedByUserException { + if (pleaseStop) { + throw new StoppedByUserException(); + } + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testStarted(description); + } + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test failed. + * + * @param failure the description of the test that failed and the exception thrown + */ + public void fireTestFailure(Failure failure) { + fireTestFailures(listeners, asList(failure)); + } + + private void fireTestFailures(List listeners, + final List failures) { + if (!failures.isEmpty()) { + new SafeNotifier(listeners) { + @Override + protected void notifyListener(RunListener listener) throws Exception { + for (Failure each : failures) { + listener.testFailure(each); + } + } + }.run(); + } + } + + /** + * Invoke to tell listeners that an atomic test flagged that it assumed + * something false. + * + * @param failure the description of the test that failed and the + * {@link org.junit.AssumptionViolatedException} thrown + */ + public void fireTestAssumptionFailed(final Failure failure) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testAssumptionFailure(failure); + } + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test was ignored. + * + * @param description the description of the ignored test + */ + public void fireTestIgnored(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testIgnored(description); + } + }.run(); + } + + /** + * Invoke to tell listeners that an atomic test finished. Always invoke + * this method if you invoke {@link #fireTestStarted(Description)} + * as listeners are likely to expect them to come in pairs. + * + * @param description the description of the test that finished + */ + public void fireTestFinished(final Description description) { + new SafeNotifier() { + @Override + protected void notifyListener(RunListener each) throws Exception { + each.testFinished(description); + } + }.run(); + } + + /** + * Ask that the tests run stop before starting the next test. Phrased politely because + * the test currently running will not be interrupted. It seems a little odd to put this + * functionality here, but the RunNotifier is the only object guaranteed + * to be shared amongst the many runners involved. + */ + public void pleaseStop() { + pleaseStop = true; + } + + /** + * Internal use only. The Result's listener must be first. + */ + public void addFirstListener(RunListener listener) { + if (listener == null) { + throw new NullPointerException("Cannot add a null listener"); + } + listeners.add(0, wrapIfNotThreadSafe(listener)); + } +} diff --git a/src/main/java/org/junit/runner/notification/StoppedByUserException.java b/src/main/java/org/junit/runner/notification/StoppedByUserException.java new file mode 100644 index 000000000000..f5490f71919d --- /dev/null +++ b/src/main/java/org/junit/runner/notification/StoppedByUserException.java @@ -0,0 +1,12 @@ +package org.junit.runner.notification; + +/** + * Thrown when a user has requested that the test run stop. Writers of + * test running GUIs should be prepared to catch a StoppedByUserException. + * + * @see org.junit.runner.notification.RunNotifier + * @since 4.0 + */ +public class StoppedByUserException extends RuntimeException { + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/org/junit/runner/notification/SynchronizedRunListener.java b/src/main/java/org/junit/runner/notification/SynchronizedRunListener.java new file mode 100644 index 000000000000..0cd2f49444d7 --- /dev/null +++ b/src/main/java/org/junit/runner/notification/SynchronizedRunListener.java @@ -0,0 +1,134 @@ +package org.junit.runner.notification; + +import org.junit.runner.Description; +import org.junit.runner.Result; + +/** + * Thread-safe decorator for {@link RunListener} implementations that synchronizes + * calls to the delegate. + * + *

      This class synchronizes all listener calls on a RunNotifier instance. This is done because + * prior to JUnit 4.12, all listeners were called in a synchronized block in RunNotifier, + * so no two listeners were ever called concurrently. If we instead made the methods here + * sychronized, clients that added multiple listeners that called common code might see + * issues due to the reduced synchronization. + * + * @author Tibor Digana (tibor17) + * @author Kevin Cooney (kcooney) + * @since 4.12 + * + * @see RunNotifier + */ +@RunListener.ThreadSafe +final class SynchronizedRunListener extends RunListener { + private final RunListener listener; + private final Object monitor; + + SynchronizedRunListener(RunListener listener, Object monitor) { + this.listener = listener; + this.monitor = monitor; + } + + @Override + public void testRunStarted(Description description) throws Exception { + synchronized (monitor) { + listener.testRunStarted(description); + } + } + + @Override + public void testRunFinished(Result result) throws Exception { + synchronized (monitor) { + listener.testRunFinished(result); + } + } + + /** + * {@inheritDoc} + *

      + * Synchronized decorator for {@link RunListener#testSuiteStarted(Description)}. + * @param description the description of the test suite that is about to be run + * (generally a class name). + * @throws Exception if any occurs. + * @since 4.13 + */ + @Override + public void testSuiteStarted(Description description) throws Exception { + synchronized (monitor) { + listener.testSuiteStarted(description); + } + } + + /** + * {@inheritDoc} + *

      + * Synchronized decorator for {@link RunListener#testSuiteFinished(Description)}. + * @param description the description of the test suite that just ran. + * @throws Exception + * @since 4.13 + */ + @Override + public void testSuiteFinished(Description description) throws Exception { + synchronized (monitor) { + listener.testSuiteFinished(description); + } + } + + @Override + public void testStarted(Description description) throws Exception { + synchronized (monitor) { + listener.testStarted(description); + } + } + + @Override + public void testFinished(Description description) throws Exception { + synchronized (monitor) { + listener.testFinished(description); + } + } + + @Override + public void testFailure(Failure failure) throws Exception { + synchronized (monitor) { + listener.testFailure(failure); + } + } + + @Override + public void testAssumptionFailure(Failure failure) { + synchronized (monitor) { + listener.testAssumptionFailure(failure); + } + } + + @Override + public void testIgnored(Description description) throws Exception { + synchronized (monitor) { + listener.testIgnored(description); + } + } + + @Override + public int hashCode() { + return listener.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof SynchronizedRunListener)) { + return false; + } + SynchronizedRunListener that = (SynchronizedRunListener) other; + + return listener.equals(that.listener); + } + + @Override + public String toString() { + return listener.toString() + " (with synchronization wrapper)"; + } +} diff --git a/src/main/java/org/junit/runner/notification/package-info.java b/src/main/java/org/junit/runner/notification/package-info.java new file mode 100644 index 000000000000..0331c8f20799 --- /dev/null +++ b/src/main/java/org/junit/runner/notification/package-info.java @@ -0,0 +1,6 @@ +/** + * Provides information about a test run. + * + * @since 4.0 + */ +package org.junit.runner.notification; \ No newline at end of file diff --git a/src/main/java/org/junit/runner/package-info.java b/src/main/java/org/junit/runner/package-info.java new file mode 100644 index 000000000000..e19fa0bd0f2f --- /dev/null +++ b/src/main/java/org/junit/runner/package-info.java @@ -0,0 +1,6 @@ +/** + * Provides classes used to describe, collect, run and analyze multiple tests. + * + * @since 4.0 + */ +package org.junit.runner; \ No newline at end of file diff --git a/src/main/java/org/junit/runners/AllTests.java b/src/main/java/org/junit/runners/AllTests.java new file mode 100644 index 000000000000..416c99d3b59d --- /dev/null +++ b/src/main/java/org/junit/runners/AllTests.java @@ -0,0 +1,27 @@ +package org.junit.runners; + +import org.junit.internal.runners.SuiteMethod; + +/** + * Runner for use with JUnit 3.8.x-style AllTests classes + * (those that only implement a static suite() + * method). For example: + *

      + * @RunWith(AllTests.class)
      + * public class ProductTests {
      + *    public static junit.framework.Test suite() {
      + *       ...
      + *    }
      + * }
      + * 
      + * + * @since 4.0 + */ +public class AllTests extends SuiteMethod { + /** + * Only called reflectively. Do not use programmatically. + */ + public AllTests(Class klass) throws Throwable { + super(klass); + } +} diff --git a/src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java b/src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java new file mode 100644 index 000000000000..822f8dc47bfa --- /dev/null +++ b/src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java @@ -0,0 +1,460 @@ +package org.junit.runners; + +import static org.junit.internal.runners.rules.RuleMemberValidator.RULE_METHOD_VALIDATOR; +import static org.junit.internal.runners.rules.RuleMemberValidator.RULE_VALIDATOR; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.Test.None; +import org.junit.internal.runners.model.ReflectiveCallable; +import org.junit.internal.runners.statements.ExpectException; +import org.junit.internal.runners.statements.Fail; +import org.junit.internal.runners.statements.FailOnTimeout; +import org.junit.internal.runners.statements.InvokeMethod; +import org.junit.internal.runners.statements.RunAfters; +import org.junit.internal.runners.statements.RunBefores; +import org.junit.rules.MethodRule; +import org.junit.rules.RunRules; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +/** + * Implements the JUnit 4 standard test case class model, as defined by the + * annotations in the org.junit package. Many users will never notice this + * class: it is now the default test class runner, but it should have exactly + * the same behavior as the old test class runner ({@code JUnit4ClassRunner}). + *

      + * BlockJUnit4ClassRunner has advantages for writers of custom JUnit runners + * that are slight changes to the default behavior, however: + * + *

        + *
      • It has a much simpler implementation based on {@link Statement}s, + * allowing new operations to be inserted into the appropriate point in the + * execution flow. + * + *
      • It is published, and extension and reuse are encouraged, whereas {@code + * JUnit4ClassRunner} was in an internal package, and is now deprecated. + *
      + *

      + * In turn, in 2009 we introduced {@link Rule}s. In many cases where extending + * BlockJUnit4ClassRunner was necessary to add new behavior, {@link Rule}s can + * be used, which makes the extension more reusable and composable. + * + * @since 4.5 + */ +public class BlockJUnit4ClassRunner extends ParentRunner { + + private final ConcurrentMap methodDescriptions = new ConcurrentHashMap(); + + /** + * Creates a BlockJUnit4ClassRunner to run {@code testClass} + * + * @throws InitializationError if the test class is malformed. + */ + public BlockJUnit4ClassRunner(Class testClass) throws InitializationError { + super(testClass); + } + + // + // Implementation of ParentRunner + // + + @Override + protected void runChild(final FrameworkMethod method, RunNotifier notifier) { + Description description = describeChild(method); + if (isIgnored(method)) { + notifier.fireTestIgnored(description); + } else { + Statement statement; + try { + statement = methodBlock(method); + } + catch (Throwable ex) { + statement = new Fail(ex); + } + runLeaf(statement, description, notifier); + } + } + + /** + * Evaluates whether {@link FrameworkMethod}s are ignored based on the + * {@link Ignore} annotation. + */ + @Override + protected boolean isIgnored(FrameworkMethod child) { + return child.getAnnotation(Ignore.class) != null; + } + + @Override + protected Description describeChild(FrameworkMethod method) { + Description description = methodDescriptions.get(method); + + if (description == null) { + description = Description.createTestDescription(getTestClass().getJavaClass(), + testName(method), method.getAnnotations()); + methodDescriptions.putIfAbsent(method, description); + } + + return description; + } + + @Override + protected List getChildren() { + return computeTestMethods(); + } + + // + // Override in subclasses + // + + /** + * Returns the methods that run tests. Default implementation returns all + * methods annotated with {@code @Test} on this class and superclasses that + * are not overridden. + */ + protected List computeTestMethods() { + return getTestClass().getAnnotatedMethods(Test.class); + } + + @Override + protected void collectInitializationErrors(List errors) { + super.collectInitializationErrors(errors); + + validateNoNonStaticInnerClass(errors); + validateConstructor(errors); + validateInstanceMethods(errors); + validateFields(errors); + validateMethods(errors); + } + + protected void validateNoNonStaticInnerClass(List errors) { + if (getTestClass().isANonStaticInnerClass()) { + String gripe = "The inner class " + getTestClass().getName() + + " is not static."; + errors.add(new Exception(gripe)); + } + } + + /** + * Adds to {@code errors} if the test class has more than one constructor, + * or if the constructor takes parameters. Override if a subclass requires + * different validation rules. + */ + protected void validateConstructor(List errors) { + validateOnlyOneConstructor(errors); + validateZeroArgConstructor(errors); + } + + /** + * Adds to {@code errors} if the test class has more than one constructor + * (do not override) + */ + protected void validateOnlyOneConstructor(List errors) { + if (!hasOneConstructor()) { + String gripe = "Test class should have exactly one public constructor"; + errors.add(new Exception(gripe)); + } + } + + /** + * Adds to {@code errors} if the test class's single constructor takes + * parameters (do not override) + */ + protected void validateZeroArgConstructor(List errors) { + if (!getTestClass().isANonStaticInnerClass() + && hasOneConstructor() + && (getTestClass().getOnlyConstructor().getParameterTypes().length != 0)) { + String gripe = "Test class should have exactly one public zero-argument constructor"; + errors.add(new Exception(gripe)); + } + } + + private boolean hasOneConstructor() { + return getTestClass().getJavaClass().getConstructors().length == 1; + } + + /** + * Adds to {@code errors} for each method annotated with {@code @Test}, + * {@code @Before}, or {@code @After} that is not a public, void instance + * method with no arguments. + * @deprecated + */ + @Deprecated + protected void validateInstanceMethods(List errors) { + validatePublicVoidNoArgMethods(After.class, false, errors); + validatePublicVoidNoArgMethods(Before.class, false, errors); + validateTestMethods(errors); + + if (computeTestMethods().isEmpty()) { + errors.add(new Exception("No runnable methods")); + } + } + + protected void validateFields(List errors) { + RULE_VALIDATOR.validate(getTestClass(), errors); + } + + private void validateMethods(List errors) { + RULE_METHOD_VALIDATOR.validate(getTestClass(), errors); + } + + /** + * Adds to {@code errors} for each method annotated with {@code @Test}that + * is not a public, void instance method with no arguments. + */ + protected void validateTestMethods(List errors) { + validatePublicVoidNoArgMethods(Test.class, false, errors); + } + + /** + * Returns a new fixture for running a test. Default implementation executes + * the test class's no-argument constructor (validation should have ensured + * one exists). + */ + protected Object createTest() throws Exception { + return getTestClass().getOnlyConstructor().newInstance(); + } + + /** + * Returns a new fixture to run a particular test {@code method} against. + * Default implementation executes the no-argument {@link #createTest()} method. + * + * @since 4.13 + */ + protected Object createTest(FrameworkMethod method) throws Exception { + return createTest(); + } + + /** + * Returns the name that describes {@code method} for {@link Description}s. + * Default implementation is the method's name + */ + protected String testName(FrameworkMethod method) { + return method.getName(); + } + + /** + * Returns a Statement that, when executed, either returns normally if + * {@code method} passes, or throws an exception if {@code method} fails. + * + * Here is an outline of the default implementation: + * + *

        + *
      • Invoke {@code method} on the result of {@link #createTest(org.junit.runners.model.FrameworkMethod)}, and + * throw any exceptions thrown by either operation. + *
      • HOWEVER, if {@code method}'s {@code @Test} annotation has the {@code + * expecting} attribute, return normally only if the previous step threw an + * exception of the correct type, and throw an exception otherwise. + *
      • HOWEVER, if {@code method}'s {@code @Test} annotation has the {@code + * timeout} attribute, throw an exception if the previous step takes more + * than the specified number of milliseconds. + *
      • ALWAYS run all non-overridden {@code @Before} methods on this class + * and superclasses before any of the previous steps; if any throws an + * Exception, stop execution and pass the exception on. + *
      • ALWAYS run all non-overridden {@code @After} methods on this class + * and superclasses after any of the previous steps; all After methods are + * always executed: exceptions thrown by previous steps are combined, if + * necessary, with exceptions from After methods into a + * {@link MultipleFailureException}. + *
      • ALWAYS allow {@code @Rule} fields to modify the execution of the + * above steps. A {@code Rule} may prevent all execution of the above steps, + * or add additional behavior before and after, or modify thrown exceptions. + * For more information, see {@link TestRule} + *
      + * + * This can be overridden in subclasses, either by overriding this method, + * or the implementations creating each sub-statement. + */ + protected Statement methodBlock(final FrameworkMethod method) { + Object test; + try { + test = new ReflectiveCallable() { + @Override + protected Object runReflectiveCall() throws Throwable { + return createTest(method); + } + }.run(); + } catch (Throwable e) { + return new Fail(e); + } + + Statement statement = methodInvoker(method, test); + statement = possiblyExpectingExceptions(method, test, statement); + statement = withPotentialTimeout(method, test, statement); + statement = withBefores(method, test, statement); + statement = withAfters(method, test, statement); + statement = withRules(method, test, statement); + return statement; + } + + // + // Statement builders + // + + /** + * Returns a {@link Statement} that invokes {@code method} on {@code test} + */ + protected Statement methodInvoker(FrameworkMethod method, Object test) { + return new InvokeMethod(method, test); + } + + /** + * Returns a {@link Statement}: if {@code method}'s {@code @Test} annotation + * has the {@code expecting} attribute, return normally only if {@code next} + * throws an exception of the correct type, and throw an exception + * otherwise. + */ + protected Statement possiblyExpectingExceptions(FrameworkMethod method, + Object test, Statement next) { + Test annotation = method.getAnnotation(Test.class); + return expectsException(annotation) ? new ExpectException(next, + getExpectedException(annotation)) : next; + } + + /** + * Returns a {@link Statement}: if {@code method}'s {@code @Test} annotation + * has the {@code timeout} attribute, throw an exception if {@code next} + * takes more than the specified number of milliseconds. + * @deprecated + */ + @Deprecated + protected Statement withPotentialTimeout(FrameworkMethod method, + Object test, Statement next) { + long timeout = getTimeout(method.getAnnotation(Test.class)); + if (timeout <= 0) { + return next; + } + return FailOnTimeout.builder() + .withTimeout(timeout, TimeUnit.MILLISECONDS) + .build(next); + } + + /** + * Returns a {@link Statement}: run all non-overridden {@code @Before} + * methods on this class and superclasses before running {@code next}; if + * any throws an Exception, stop execution and pass the exception on. + */ + protected Statement withBefores(FrameworkMethod method, Object target, + Statement statement) { + List befores = getTestClass().getAnnotatedMethods( + Before.class); + return befores.isEmpty() ? statement : new RunBefores(statement, + befores, target); + } + + /** + * Returns a {@link Statement}: run all non-overridden {@code @After} + * methods on this class and superclasses before running {@code next}; all + * After methods are always executed: exceptions thrown by previous steps + * are combined, if necessary, with exceptions from After methods into a + * {@link MultipleFailureException}. + */ + protected Statement withAfters(FrameworkMethod method, Object target, + Statement statement) { + List afters = getTestClass().getAnnotatedMethods( + After.class); + return afters.isEmpty() ? statement : new RunAfters(statement, afters, + target); + } + + private Statement withRules(FrameworkMethod method, Object target, + Statement statement) { + List testRules = getTestRules(target); + Statement result = statement; + result = withMethodRules(method, testRules, target, result); + result = withTestRules(method, testRules, result); + + return result; + } + + private Statement withMethodRules(FrameworkMethod method, List testRules, + Object target, Statement result) { + Statement withMethodRules = result; + for (org.junit.rules.MethodRule each : getMethodRules(target)) { + if (!(each instanceof TestRule && testRules.contains(each))) { + withMethodRules = each.apply(withMethodRules, method, target); + } + } + return withMethodRules; + } + + private List getMethodRules(Object target) { + return rules(target); + } + + /** + * @param target the test case instance + * @return a list of MethodRules that should be applied when executing this + * test + */ + protected List rules(Object target) { + List rules = getTestClass().getAnnotatedMethodValues(target, + Rule.class, MethodRule.class); + + rules.addAll(getTestClass().getAnnotatedFieldValues(target, + Rule.class, MethodRule.class)); + + return rules; + } + + /** + * Returns a {@link Statement}: apply all non-static fields + * annotated with {@link Rule}. + * + * @param statement The base statement + * @return a RunRules statement if any class-level {@link Rule}s are + * found, or the base statement + */ + private Statement withTestRules(FrameworkMethod method, List testRules, + Statement statement) { + return testRules.isEmpty() ? statement : + new RunRules(statement, testRules, describeChild(method)); + } + + /** + * @param target the test case instance + * @return a list of TestRules that should be applied when executing this + * test + */ + protected List getTestRules(Object target) { + List result = getTestClass().getAnnotatedMethodValues(target, + Rule.class, TestRule.class); + + result.addAll(getTestClass().getAnnotatedFieldValues(target, + Rule.class, TestRule.class)); + + return result; + } + + private Class getExpectedException(Test annotation) { + if (annotation == null || annotation.expected() == None.class) { + return null; + } else { + return annotation.expected(); + } + } + + private boolean expectsException(Test annotation) { + return getExpectedException(annotation) != null; + } + + private long getTimeout(Test annotation) { + if (annotation == null) { + return 0; + } + return annotation.timeout(); + } +} diff --git a/src/main/java/org/junit/runners/JUnit4.java b/src/main/java/org/junit/runners/JUnit4.java new file mode 100644 index 000000000000..6ba28c2fd431 --- /dev/null +++ b/src/main/java/org/junit/runners/JUnit4.java @@ -0,0 +1,24 @@ +package org.junit.runners; + +import org.junit.runners.model.InitializationError; + +/** + * Aliases the current default JUnit 4 class runner, for future-proofing. If + * future versions of JUnit change the default Runner class, they will also + * change the definition of this class. Developers wanting to explicitly tag a + * class as a JUnit 4 class should use {@code @RunWith(JUnit4.class)}, not, + * for example in JUnit 4.5, {@code @RunWith(BlockJUnit4ClassRunner.class)}. + * This is the only way this class should be used--any extension that + * depends on the implementation details of this class is likely to break + * in future versions. + * + * @since 4.5 + */ +public final class JUnit4 extends BlockJUnit4ClassRunner { + /** + * Constructs a new instance of the default runner + */ + public JUnit4(Class klass) throws InitializationError { + super(klass); + } +} diff --git a/src/main/java/org/junit/runners/MethodSorters.java b/src/main/java/org/junit/runners/MethodSorters.java new file mode 100644 index 000000000000..5821892f0553 --- /dev/null +++ b/src/main/java/org/junit/runners/MethodSorters.java @@ -0,0 +1,41 @@ +package org.junit.runners; + +import java.lang.reflect.Method; +import java.util.Comparator; + +import org.junit.internal.MethodSorter; + +/** + * Sort the methods into a specified execution order. + * Defines common {@link MethodSorter} implementations. + * + * @since 4.11 + */ +public enum MethodSorters { + /** + * Sorts the test methods by the method name, in lexicographic order, + * with {@link Method#toString()} used as a tiebreaker + */ + NAME_ASCENDING(MethodSorter.NAME_ASCENDING), + + /** + * Leaves the test methods in the order returned by the JVM. + * Note that the order from the JVM may vary from run to run + */ + JVM(null), + + /** + * Sorts the test methods in a deterministic, but not predictable, order + */ + DEFAULT(MethodSorter.DEFAULT); + + private final Comparator comparator; + + private MethodSorters(Comparator comparator) { + this.comparator = comparator; + } + + public Comparator getComparator() { + return comparator; + } +} diff --git a/src/main/java/org/junit/runners/Parameterized.java b/src/main/java/org/junit/runners/Parameterized.java new file mode 100644 index 000000000000..cc7c804f4daa --- /dev/null +++ b/src/main/java/org/junit/runners/Parameterized.java @@ -0,0 +1,360 @@ +package org.junit.runners; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.runner.Runner; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; +import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory; +import org.junit.runners.parameterized.ParametersRunnerFactory; +import org.junit.runners.parameterized.TestWithParameters; + +/** + * The custom runner Parameterized implements parameterized tests. + * When running a parameterized test class, instances are created for the + * cross-product of the test methods and the test data elements. + *

      + * For example, to test the + operator, write: + *

      + * @RunWith(Parameterized.class)
      + * public class AdditionTest {
      + *     @Parameters(name = "{index}: {0} + {1} = {2}")
      + *     public static Iterable<Object[]> data() {
      + *         return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 },
      + *                 { 3, 2, 5 }, { 4, 3, 7 } });
      + *     }
      + *
      + *     private int firstSummand;
      + *
      + *     private int secondSummand;
      + *
      + *     private int sum;
      + *
      + *     public AdditionTest(int firstSummand, int secondSummand, int sum) {
      + *         this.firstSummand = firstSummand;
      + *         this.secondSummand = secondSummand;
      + *         this.sum = sum;
      + *     }
      + *
      + *     @Test
      + *     public void test() {
      + *         assertEquals(sum, firstSummand + secondSummand);
      + *     }
      + * }
      + * 
      + *

      + * Each instance of AdditionTest will be constructed using the + * three-argument constructor and the data values in the + * @Parameters method. + *

      + * In order that you can easily identify the individual tests, you may provide a + * name for the @Parameters annotation. This name is allowed + * to contain placeholders, which are replaced at runtime. The placeholders are + *

      + *
      {index}
      + *
      the current parameter index
      + *
      {0}
      + *
      the first parameter value
      + *
      {1}
      + *
      the second parameter value
      + *
      ...
      + *
      ...
      + *
      + *

      + * In the example given above, the Parameterized runner creates + * names like [2: 3 + 2 = 5]. If you don't use the name parameter, + * then the current parameter index is used as name. + *

      + * You can also write: + *

      + * @RunWith(Parameterized.class)
      + * public class AdditionTest {
      + *     @Parameters(name = "{index}: {0} + {1} = {2}")
      + *     public static Iterable<Object[]> data() {
      + *         return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 },
      + *                 { 3, 2, 5 }, { 4, 3, 7 } });
      + *     }
      + *
      + *     @Parameter(0)
      + *     public int firstSummand;
      + *
      + *     @Parameter(1)
      + *     public int secondSummand;
      + *
      + *     @Parameter(2)
      + *     public int sum;
      + *
      + *     @Test
      + *     public void test() {
      + *         assertEquals(sum, firstSummand + secondSummand);
      + *     }
      + * }
      + * 
      + *

      + * Each instance of AdditionTest will be constructed with the default constructor + * and fields annotated by @Parameter will be initialized + * with the data values in the @Parameters method. + * + *

      + * The parameters can be provided as an array, too: + * + *

      + * @Parameters
      + * public static Object[][] data() {
      + * 	return new Object[][] { { 0, 0, 0 }, { 1, 1, 2 }, { 3, 2, 5 }, { 4, 3, 7 } } };
      + * }
      + * 
      + * + *

      Tests with single parameter

      + *

      + * If your test needs a single parameter only, you don't have to wrap it with an + * array. Instead you can provide an Iterable or an array of + * objects. + *

      + * @Parameters
      + * public static Iterable<? extends Object> data() {
      + * 	return Arrays.asList("first test", "second test");
      + * }
      + * 
      + *

      + * or + *

      + * @Parameters
      + * public static Object[] data() {
      + * 	return new Object[] { "first test", "second test" };
      + * }
      + * 
      + * + *

      Create different runners

      + *

      + * By default the {@code Parameterized} runner creates a slightly modified + * {@link BlockJUnit4ClassRunner} for each set of parameters. You can build an + * own {@code Parameterized} runner that creates another runner for each set of + * parameters. Therefore you have to build a {@link ParametersRunnerFactory} + * that creates a runner for each {@link TestWithParameters}. ( + * {@code TestWithParameters} are bundling the parameters and the test name.) + * The factory must have a public zero-arg constructor. + * + *

      + * public class YourRunnerFactory implements ParametersRunnerFactory {
      + *     public Runner createRunnerForTestWithParameters(TestWithParameters test)
      + *             throws InitializationError {
      + *         return YourRunner(test);
      + *     }
      + * }
      + * 
      + *

      + * Use the {@link UseParametersRunnerFactory} to tell the {@code Parameterized} + * runner that it should use your factory. + * + *

      + * @RunWith(Parameterized.class)
      + * @UseParametersRunnerFactory(YourRunnerFactory.class)
      + * public class YourTest {
      + *     ...
      + * }
      + * 
      + * + * @since 4.0 + */ +public class Parameterized extends Suite { + /** + * Annotation for a method which provides parameters to be injected into the + * test class constructor by Parameterized. The method has to + * be public and static. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + public @interface Parameters { + /** + * Optional pattern to derive the test's name from the parameters. Use + * numbers in braces to refer to the parameters or the additional data + * as follows: + *
      +         * {index} - the current parameter index
      +         * {0} - the first parameter value
      +         * {1} - the second parameter value
      +         * etc...
      +         * 
      + *

      + * Default value is "{index}" for compatibility with previous JUnit + * versions. + * + * @return {@link MessageFormat} pattern string, except the index + * placeholder. + * @see MessageFormat + */ + String name() default "{index}"; + } + + /** + * Annotation for fields of the test class which will be initialized by the + * method annotated by Parameters. + * By using directly this annotation, the test class constructor isn't needed. + * Index range must start at 0. + * Default value is 0. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface Parameter { + /** + * Method that returns the index of the parameter in the array + * returned by the method annotated by Parameters. + * Index range must start at 0. + * Default value is 0. + * + * @return the index of the parameter. + */ + int value() default 0; + } + + /** + * Add this annotation to your test class if you want to generate a special + * runner. You have to specify a {@link ParametersRunnerFactory} class that + * creates such runners. The factory must have a public zero-arg + * constructor. + */ + @Retention(RetentionPolicy.RUNTIME) + @Inherited + @Target(ElementType.TYPE) + public @interface UseParametersRunnerFactory { + /** + * @return a {@link ParametersRunnerFactory} class (must have a default + * constructor) + */ + Class value() default BlockJUnit4ClassRunnerWithParametersFactory.class; + } + + /** + * Only called reflectively. Do not use programmatically. + */ + public Parameterized(Class klass) throws Throwable { + super(klass, RunnersFactory.createRunnersForClass(klass)); + } + + private static class RunnersFactory { + private static final ParametersRunnerFactory DEFAULT_FACTORY = new BlockJUnit4ClassRunnerWithParametersFactory(); + + private final TestClass testClass; + + static List createRunnersForClass(Class klass) + throws Throwable { + return new RunnersFactory(klass).createRunners(); + } + + private RunnersFactory(Class klass) { + testClass = new TestClass(klass); + } + + private List createRunners() throws Throwable { + Parameters parameters = getParametersMethod().getAnnotation( + Parameters.class); + return Collections.unmodifiableList(createRunnersForParameters( + allParameters(), parameters.name(), + getParametersRunnerFactory())); + } + + private ParametersRunnerFactory getParametersRunnerFactory() + throws InstantiationException, IllegalAccessException { + UseParametersRunnerFactory annotation = testClass + .getAnnotation(UseParametersRunnerFactory.class); + if (annotation == null) { + return DEFAULT_FACTORY; + } else { + Class factoryClass = annotation + .value(); + return factoryClass.newInstance(); + } + } + + private TestWithParameters createTestWithNotNormalizedParameters( + String pattern, int index, Object parametersOrSingleParameter) { + Object[] parameters = (parametersOrSingleParameter instanceof Object[]) ? (Object[]) parametersOrSingleParameter + : new Object[] { parametersOrSingleParameter }; + return createTestWithParameters(testClass, pattern, index, + parameters); + } + + @SuppressWarnings("unchecked") + private Iterable allParameters() throws Throwable { + Object parameters = getParametersMethod().invokeExplosively(null); + if (parameters instanceof Iterable) { + return (Iterable) parameters; + } else if (parameters instanceof Object[]) { + return Arrays.asList((Object[]) parameters); + } else { + throw parametersMethodReturnedWrongType(); + } + } + + private FrameworkMethod getParametersMethod() throws Exception { + List methods = testClass + .getAnnotatedMethods(Parameters.class); + for (FrameworkMethod each : methods) { + if (each.isStatic() && each.isPublic()) { + return each; + } + } + + throw new Exception("No public static parameters method on class " + + testClass.getName()); + } + + private List createRunnersForParameters( + Iterable allParameters, String namePattern, + ParametersRunnerFactory runnerFactory) throws Exception { + try { + List tests = createTestsForParameters( + allParameters, namePattern); + List runners = new ArrayList(); + for (TestWithParameters test : tests) { + runners.add(runnerFactory + .createRunnerForTestWithParameters(test)); + } + return runners; + } catch (ClassCastException e) { + throw parametersMethodReturnedWrongType(); + } + } + + private List createTestsForParameters( + Iterable allParameters, String namePattern) + throws Exception { + int i = 0; + List children = new ArrayList(); + for (Object parametersOfSingleTest : allParameters) { + children.add(createTestWithNotNormalizedParameters(namePattern, + i++, parametersOfSingleTest)); + } + return children; + } + + private Exception parametersMethodReturnedWrongType() throws Exception { + String className = testClass.getName(); + String methodName = getParametersMethod().getName(); + String message = MessageFormat.format( + "{0}.{1}() must return an Iterable of arrays.", className, + methodName); + return new Exception(message); + } + + private TestWithParameters createTestWithParameters( + TestClass testClass, String pattern, int index, + Object[] parameters) { + String finalPattern = pattern.replaceAll("\\{index\\}", + Integer.toString(index)); + String name = MessageFormat.format(finalPattern, parameters); + return new TestWithParameters("[" + name + "]", testClass, + Arrays.asList(parameters)); + } + } +} diff --git a/src/main/java/org/junit/runners/ParentRunner.java b/src/main/java/org/junit/runners/ParentRunner.java new file mode 100755 index 000000000000..0babec2f3782 --- /dev/null +++ b/src/main/java/org/junit/runners/ParentRunner.java @@ -0,0 +1,456 @@ +package org.junit.runners; + +import static org.junit.internal.runners.rules.RuleMemberValidator.CLASS_RULE_METHOD_VALIDATOR; +import static org.junit.internal.runners.rules.RuleMemberValidator.CLASS_RULE_VALIDATOR; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.internal.AssumptionViolatedException; +import org.junit.internal.runners.model.EachTestNotifier; +import org.junit.internal.runners.statements.RunAfters; +import org.junit.internal.runners.statements.RunBefores; +import org.junit.rules.RunRules; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +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.runner.manipulation.Sortable; +import org.junit.runner.manipulation.Sorter; +import org.junit.runner.notification.RunNotifier; +import org.junit.runner.notification.StoppedByUserException; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.InvalidTestClassError; +import org.junit.runners.model.RunnerScheduler; +import org.junit.runners.model.Statement; +import org.junit.runners.model.TestClass; +import org.junit.validator.AnnotationsValidator; +import org.junit.validator.PublicClassValidator; +import org.junit.validator.TestClassValidator; + +/** + * Provides most of the functionality specific to a Runner that implements a + * "parent node" in the test tree, with children defined by objects of some data + * type {@code T}. (For {@link BlockJUnit4ClassRunner}, {@code T} is + * {@link Method} . For {@link Suite}, {@code T} is {@link Class}.) Subclasses + * must implement finding the children of the node, describing each child, and + * running each child. ParentRunner will filter and sort children, handle + * {@code @BeforeClass} and {@code @AfterClass} methods, + * handle annotated {@link ClassRule}s, create a composite + * {@link Description}, and run children sequentially. + * + * @since 4.5 + */ +public abstract class ParentRunner extends Runner implements Filterable, + Sortable { + private static final List VALIDATORS = Arrays.asList( + new AnnotationsValidator(), new PublicClassValidator()); + + private final Object childrenLock = new Object(); + private final TestClass testClass; + + // Guarded by childrenLock + private volatile Collection filteredChildren = null; + + private volatile RunnerScheduler scheduler = new RunnerScheduler() { + public void schedule(Runnable childStatement) { + childStatement.run(); + } + + public void finished() { + // do nothing + } + }; + + /** + * Constructs a new {@code ParentRunner} that will run {@code @TestClass} + */ + protected ParentRunner(Class testClass) throws InitializationError { + this.testClass = createTestClass(testClass); + validate(); + } + + protected TestClass createTestClass(Class testClass) { + return new TestClass(testClass); + } + + // + // Must be overridden + // + + /** + * Returns a list of objects that define the children of this Runner. + */ + protected abstract List getChildren(); + + /** + * Returns a {@link Description} for {@code child}, which can be assumed to + * be an element of the list returned by {@link ParentRunner#getChildren()} + */ + protected abstract Description describeChild(T child); + + /** + * Runs the test corresponding to {@code child}, which can be assumed to be + * an element of the list returned by {@link ParentRunner#getChildren()}. + * Subclasses are responsible for making sure that relevant test events are + * reported through {@code notifier} + */ + protected abstract void runChild(T child, RunNotifier notifier); + + // + // May be overridden + // + + /** + * Adds to {@code errors} a throwable for each problem noted with the test class (available from {@link #getTestClass()}). + * Default implementation adds an error for each method annotated with + * {@code @BeforeClass} or {@code @AfterClass} that is not + * {@code public static void} with no arguments. + */ + protected void collectInitializationErrors(List errors) { + validatePublicVoidNoArgMethods(BeforeClass.class, true, errors); + validatePublicVoidNoArgMethods(AfterClass.class, true, errors); + validateClassRules(errors); + applyValidators(errors); + } + + private void applyValidators(List errors) { + if (getTestClass().getJavaClass() != null) { + for (TestClassValidator each : VALIDATORS) { + errors.addAll(each.validateTestClass(getTestClass())); + } + } + } + + /** + * Adds to {@code errors} if any method in this class is annotated with + * {@code annotation}, but: + *
        + *
      • is not public, or + *
      • takes parameters, or + *
      • returns something other than void, or + *
      • is static (given {@code isStatic is false}), or + *
      • is not static (given {@code isStatic is true}). + *
      + */ + protected void validatePublicVoidNoArgMethods(Class annotation, + boolean isStatic, List errors) { + List methods = getTestClass().getAnnotatedMethods(annotation); + + for (FrameworkMethod eachTestMethod : methods) { + eachTestMethod.validatePublicVoidNoArg(isStatic, errors); + } + } + + private void validateClassRules(List errors) { + CLASS_RULE_VALIDATOR.validate(getTestClass(), errors); + CLASS_RULE_METHOD_VALIDATOR.validate(getTestClass(), errors); + } + + /** + * Constructs a {@code Statement} to run all of the tests in the test class. + * Override to add pre-/post-processing. Here is an outline of the + * implementation: + *
        + *
      1. Determine the children to be run using {@link #getChildren()} + * (subject to any imposed filter and sort).
      2. + *
      3. If there are any children remaining after filtering and ignoring, + * construct a statement that will: + *
          + *
        1. Apply all {@code ClassRule}s on the test-class and superclasses.
        2. + *
        3. Run all non-overridden {@code @BeforeClass} methods on the test-class + * and superclasses; if any throws an Exception, stop execution and pass the + * exception on.
        4. + *
        5. Run all remaining tests on the test-class.
        6. + *
        7. Run all non-overridden {@code @AfterClass} methods on the test-class + * and superclasses: exceptions thrown by previous steps are combined, if + * necessary, with exceptions from AfterClass methods into a + * {@link org.junit.runners.model.MultipleFailureException}.
        8. + *
        + *
      4. + *
      + * + * @return {@code Statement} + */ + protected Statement classBlock(final RunNotifier notifier) { + Statement statement = childrenInvoker(notifier); + if (!areAllChildrenIgnored()) { + statement = withBeforeClasses(statement); + statement = withAfterClasses(statement); + statement = withClassRules(statement); + } + return statement; + } + + private boolean areAllChildrenIgnored() { + for (T child : getFilteredChildren()) { + if (!isIgnored(child)) { + return false; + } + } + return true; + } + + /** + * Returns a {@link Statement}: run all non-overridden {@code @BeforeClass} methods on this class + * and superclasses before executing {@code statement}; if any throws an + * Exception, stop execution and pass the exception on. + */ + protected Statement withBeforeClasses(Statement statement) { + List befores = testClass + .getAnnotatedMethods(BeforeClass.class); + return befores.isEmpty() ? statement : + new RunBefores(statement, befores, null); + } + + /** + * Returns a {@link Statement}: run all non-overridden {@code @AfterClass} methods on this class + * and superclasses after executing {@code statement}; all AfterClass methods are + * always executed: exceptions thrown by previous steps are combined, if + * necessary, with exceptions from AfterClass methods into a + * {@link org.junit.runners.model.MultipleFailureException}. + */ + protected Statement withAfterClasses(Statement statement) { + List afters = testClass + .getAnnotatedMethods(AfterClass.class); + return afters.isEmpty() ? statement : + new RunAfters(statement, afters, null); + } + + /** + * Returns a {@link Statement}: apply all + * static fields assignable to {@link TestRule} + * annotated with {@link ClassRule}. + * + * @param statement the base statement + * @return a RunRules statement if any class-level {@link Rule}s are + * found, or the base statement + */ + private Statement withClassRules(Statement statement) { + List classRules = classRules(); + return classRules.isEmpty() ? statement : + new RunRules(statement, classRules, getDescription()); + } + + /** + * @return the {@code ClassRule}s that can transform the block that runs + * each method in the tested class. + */ + protected List classRules() { + List result = testClass.getAnnotatedMethodValues(null, ClassRule.class, TestRule.class); + result.addAll(testClass.getAnnotatedFieldValues(null, ClassRule.class, TestRule.class)); + return result; + } + + /** + * Returns a {@link Statement}: Call {@link #runChild(Object, RunNotifier)} + * on each object returned by {@link #getChildren()} (subject to any imposed + * filter and sort) + */ + protected Statement childrenInvoker(final RunNotifier notifier) { + return new Statement() { + @Override + public void evaluate() { + runChildren(notifier); + } + }; + } + + /** + * Evaluates whether a child is ignored. The default implementation always + * returns false. + * + *

      {@link BlockJUnit4ClassRunner}, for example, overrides this method to + * filter tests based on the {@link Ignore} annotation. + */ + protected boolean isIgnored(T child) { + return false; + } + + private void runChildren(final RunNotifier notifier) { + final RunnerScheduler currentScheduler = scheduler; + try { + for (final T each : getFilteredChildren()) { + currentScheduler.schedule(new Runnable() { + public void run() { + ParentRunner.this.runChild(each, notifier); + } + }); + } + } finally { + currentScheduler.finished(); + } + } + + /** + * Returns a name used to describe this Runner + */ + protected String getName() { + return testClass.getName(); + } + + // + // Available for subclasses + // + + /** + * Returns a {@link TestClass} object wrapping the class to be executed. + */ + public final TestClass getTestClass() { + return testClass; + } + + /** + * Runs a {@link Statement} that represents a leaf (aka atomic) test. + */ + protected final void runLeaf(Statement statement, Description description, + RunNotifier notifier) { + EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); + eachNotifier.fireTestStarted(); + try { + statement.evaluate(); + } catch (AssumptionViolatedException e) { + eachNotifier.addFailedAssumption(e); + } catch (Throwable e) { + eachNotifier.addFailure(e); + } finally { + eachNotifier.fireTestFinished(); + } + } + + /** + * @return the annotations that should be attached to this runner's + * description. + */ + protected Annotation[] getRunnerAnnotations() { + return testClass.getAnnotations(); + } + + // + // Implementation of Runner + // + + @Override + public Description getDescription() { + Description description = Description.createSuiteDescription(getName(), + getRunnerAnnotations()); + for (T child : getFilteredChildren()) { + description.addChild(describeChild(child)); + } + return description; + } + + @Override + public void run(final RunNotifier notifier) { + EachTestNotifier testNotifier = new EachTestNotifier(notifier, + getDescription()); + testNotifier.fireTestSuiteStarted(); + try { + Statement statement = classBlock(notifier); + statement.evaluate(); + } catch (AssumptionViolatedException e) { + testNotifier.addFailedAssumption(e); + } catch (StoppedByUserException e) { + throw e; + } catch (Throwable e) { + testNotifier.addFailure(e); + } finally { + testNotifier.fireTestSuiteFinished(); + } + } + + // + // Implementation of Filterable and Sortable + // + + public void filter(Filter filter) throws NoTestsRemainException { + synchronized (childrenLock) { + List children = new ArrayList(getFilteredChildren()); + for (Iterator iter = children.iterator(); iter.hasNext(); ) { + T each = iter.next(); + if (shouldRun(filter, each)) { + try { + filter.apply(each); + } catch (NoTestsRemainException e) { + iter.remove(); + } + } else { + iter.remove(); + } + } + filteredChildren = Collections.unmodifiableCollection(children); + if (filteredChildren.isEmpty()) { + throw new NoTestsRemainException(); + } + } + } + + public void sort(Sorter sorter) { + synchronized (childrenLock) { + for (T each : getFilteredChildren()) { + sorter.apply(each); + } + List sortedChildren = new ArrayList(getFilteredChildren()); + Collections.sort(sortedChildren, comparator(sorter)); + filteredChildren = Collections.unmodifiableCollection(sortedChildren); + } + } + + // + // Private implementation + // + + private void validate() throws InitializationError { + List errors = new ArrayList(); + collectInitializationErrors(errors); + if (!errors.isEmpty()) { + throw new InvalidTestClassError(testClass.getJavaClass(), errors); + } + } + + private Collection getFilteredChildren() { + if (filteredChildren == null) { + synchronized (childrenLock) { + if (filteredChildren == null) { + filteredChildren = Collections.unmodifiableCollection(getChildren()); + } + } + } + return filteredChildren; + } + + private boolean shouldRun(Filter filter, T each) { + return filter.shouldRun(describeChild(each)); + } + + private Comparator comparator(final Sorter sorter) { + return new Comparator() { + public int compare(T o1, T o2) { + return sorter.compare(describeChild(o1), describeChild(o2)); + } + }; + } + + /** + * Sets a scheduler that determines the order and parallelization + * of children. Highly experimental feature that may change. + */ + public void setScheduler(RunnerScheduler scheduler) { + this.scheduler = scheduler; + } +} diff --git a/src/main/java/org/junit/runners/Suite.java b/src/main/java/org/junit/runners/Suite.java new file mode 100644 index 000000000000..6652bbcad980 --- /dev/null +++ b/src/main/java/org/junit/runners/Suite.java @@ -0,0 +1,130 @@ +package org.junit.runners; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.Collections; +import java.util.List; + +import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; + +/** + * Using Suite as a runner allows you to manually + * build a suite containing tests from many classes. It is the JUnit 4 equivalent of the JUnit 3.8.x + * static {@link junit.framework.Test} suite() method. To use it, annotate a class + * with @RunWith(Suite.class) and @SuiteClasses({TestClass1.class, ...}). + * When you run this class, it will run all the tests in all the suite classes. + * + * @since 4.0 + */ +public class Suite extends ParentRunner { + /** + * Returns an empty suite. + */ + public static Runner emptySuite() { + try { + return new Suite((Class) null, new Class[0]); + } catch (InitializationError e) { + throw new RuntimeException("This shouldn't be possible"); + } + } + + /** + * The SuiteClasses annotation specifies the classes to be run when a class + * annotated with @RunWith(Suite.class) is run. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @Inherited + public @interface SuiteClasses { + /** + * @return the classes to be run + */ + Class[] value(); + } + + private static Class[] getAnnotatedClasses(Class klass) throws InitializationError { + SuiteClasses annotation = klass.getAnnotation(SuiteClasses.class); + if (annotation == null) { + throw new InitializationError(String.format("class '%s' must have a SuiteClasses annotation", klass.getName())); + } + return annotation.value(); + } + + private final List runners; + + /** + * Called reflectively on classes annotated with @RunWith(Suite.class) + * + * @param klass the root class + * @param builder builds runners for classes in the suite + */ + public Suite(Class klass, RunnerBuilder builder) throws InitializationError { + this(builder, klass, getAnnotatedClasses(klass)); + } + + /** + * Call this when there is no single root class (for example, multiple class names + * passed on the command line to {@link org.junit.runner.JUnitCore} + * + * @param builder builds runners for classes in the suite + * @param classes the classes in the suite + */ + public Suite(RunnerBuilder builder, Class[] classes) throws InitializationError { + this(null, builder.runners(null, classes)); + } + + /** + * Call this when the default builder is good enough. Left in for compatibility with JUnit 4.4. + * + * @param klass the root of the suite + * @param suiteClasses the classes in the suite + */ + protected Suite(Class klass, Class[] suiteClasses) throws InitializationError { + this(new AllDefaultPossibilitiesBuilder(true), klass, suiteClasses); + } + + /** + * Called by this class and subclasses once the classes making up the suite have been determined + * + * @param builder builds runners for classes in the suite + * @param klass the root of the suite + * @param suiteClasses the classes in the suite + */ + protected Suite(RunnerBuilder builder, Class klass, Class[] suiteClasses) throws InitializationError { + this(klass, builder.runners(klass, suiteClasses)); + } + + /** + * Called by this class and subclasses once the runners making up the suite have been determined + * + * @param klass root of the suite + * @param runners for each class in the suite, a {@link Runner} + */ + protected Suite(Class klass, List runners) throws InitializationError { + super(klass); + this.runners = Collections.unmodifiableList(runners); + } + + @Override + protected List getChildren() { + return runners; + } + + @Override + protected Description describeChild(Runner child) { + return child.getDescription(); + } + + @Override + protected void runChild(Runner runner, final RunNotifier notifier) { + runner.run(notifier); + } +} diff --git a/src/main/java/org/junit/runners/model/Annotatable.java b/src/main/java/org/junit/runners/model/Annotatable.java new file mode 100644 index 000000000000..8eff6fd27a71 --- /dev/null +++ b/src/main/java/org/junit/runners/model/Annotatable.java @@ -0,0 +1,20 @@ +package org.junit.runners.model; + +import java.lang.annotation.Annotation; + +/** + * A model element that may have annotations. + * + * @since 4.12 + */ +public interface Annotatable { + /** + * Returns the model elements' annotations. + */ + Annotation[] getAnnotations(); + + /** + * Returns the annotation on the model element of the given type, or @code{null} + */ + T getAnnotation(Class annotationType); +} diff --git a/src/main/java/org/junit/runners/model/FrameworkField.java b/src/main/java/org/junit/runners/model/FrameworkField.java new file mode 100644 index 000000000000..945e3899eb30 --- /dev/null +++ b/src/main/java/org/junit/runners/model/FrameworkField.java @@ -0,0 +1,80 @@ +package org.junit.runners.model; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; + +import org.junit.runners.BlockJUnit4ClassRunner; + +/** + * Represents a field on a test class (currently used only for Rules in + * {@link BlockJUnit4ClassRunner}, but custom runners can make other uses) + * + * @since 4.7 + */ +public class FrameworkField extends FrameworkMember { + private final Field field; + + FrameworkField(Field field) { + if (field == null) { + throw new NullPointerException( + "FrameworkField cannot be created without an underlying field."); + } + this.field = field; + } + + @Override + public String getName() { + return getField().getName(); + } + + public Annotation[] getAnnotations() { + return field.getAnnotations(); + } + + public T getAnnotation(Class annotationType) { + return field.getAnnotation(annotationType); + } + + @Override + public boolean isShadowedBy(FrameworkField otherMember) { + return otherMember.getName().equals(getName()); + } + + @Override + protected int getModifiers() { + return field.getModifiers(); + } + + /** + * @return the underlying java Field + */ + public Field getField() { + return field; + } + + /** + * @return the underlying Java Field type + * @see java.lang.reflect.Field#getType() + */ + @Override + public Class getType() { + return field.getType(); + } + + @Override + public Class getDeclaringClass() { + return field.getDeclaringClass(); + } + + /** + * Attempts to retrieve the value of this field on {@code target} + */ + public Object get(Object target) throws IllegalArgumentException, IllegalAccessException { + return field.get(target); + } + + @Override + public String toString() { + return field.toString(); + } +} diff --git a/src/main/java/org/junit/runners/model/FrameworkMember.java b/src/main/java/org/junit/runners/model/FrameworkMember.java new file mode 100644 index 000000000000..724f096ebacc --- /dev/null +++ b/src/main/java/org/junit/runners/model/FrameworkMember.java @@ -0,0 +1,45 @@ +package org.junit.runners.model; + +import java.lang.reflect.Modifier; +import java.util.List; + +/** + * Parent class for {@link FrameworkField} and {@link FrameworkMethod} + * + * @since 4.7 + */ +public abstract class FrameworkMember> implements + Annotatable { + abstract boolean isShadowedBy(T otherMember); + + boolean isShadowedBy(List members) { + for (T each : members) { + if (isShadowedBy(each)) { + return true; + } + } + return false; + } + + protected abstract int getModifiers(); + + /** + * Returns true if this member is static, false if not. + */ + public boolean isStatic() { + return Modifier.isStatic(getModifiers()); + } + + /** + * Returns true if this member is public, false if not. + */ + public boolean isPublic() { + return Modifier.isPublic(getModifiers()); + } + + public abstract String getName(); + + public abstract Class getType(); + + public abstract Class getDeclaringClass(); +} diff --git a/src/main/java/org/junit/runners/model/FrameworkMethod.java b/src/main/java/org/junit/runners/model/FrameworkMethod.java new file mode 100644 index 000000000000..3580052ed957 --- /dev/null +++ b/src/main/java/org/junit/runners/model/FrameworkMethod.java @@ -0,0 +1,202 @@ +package org.junit.runners.model; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.List; + +import org.junit.internal.runners.model.ReflectiveCallable; + +/** + * Represents a method on a test class to be invoked at the appropriate point in + * test execution. These methods are usually marked with an annotation (such as + * {@code @Test}, {@code @Before}, {@code @After}, {@code @BeforeClass}, + * {@code @AfterClass}, etc.) + * + * @since 4.5 + */ +public class FrameworkMethod extends FrameworkMember { + private final Method method; + + /** + * Returns a new {@code FrameworkMethod} for {@code method} + */ + public FrameworkMethod(Method method) { + if (method == null) { + throw new NullPointerException( + "FrameworkMethod cannot be created without an underlying method."); + } + this.method = method; + } + + /** + * Returns the underlying Java method + */ + public Method getMethod() { + return method; + } + + /** + * Returns the result of invoking this method on {@code target} with + * parameters {@code params}. {@link InvocationTargetException}s thrown are + * unwrapped, and their causes rethrown. + */ + public Object invokeExplosively(final Object target, final Object... params) + throws Throwable { + return new ReflectiveCallable() { + @Override + protected Object runReflectiveCall() throws Throwable { + return method.invoke(target, params); + } + }.run(); + } + + /** + * Returns the method's name + */ + @Override + public String getName() { + return method.getName(); + } + + /** + * Adds to {@code errors} if this method: + *

        + *
      • is not public, or + *
      • takes parameters, or + *
      • returns something other than void, or + *
      • is static (given {@code isStatic is false}), or + *
      • is not static (given {@code isStatic is true}). + *
      + */ + public void validatePublicVoidNoArg(boolean isStatic, List errors) { + validatePublicVoid(isStatic, errors); + if (method.getParameterTypes().length != 0) { + errors.add(new Exception("Method " + method.getName() + " should have no parameters")); + } + } + + + /** + * Adds to {@code errors} if this method: + *
        + *
      • is not public, or + *
      • returns something other than void, or + *
      • is static (given {@code isStatic is false}), or + *
      • is not static (given {@code isStatic is true}). + *
      + */ + public void validatePublicVoid(boolean isStatic, List errors) { + if (isStatic() != isStatic) { + String state = isStatic ? "should" : "should not"; + errors.add(new Exception("Method " + method.getName() + "() " + state + " be static")); + } + if (!isPublic()) { + errors.add(new Exception("Method " + method.getName() + "() should be public")); + } + if (method.getReturnType() != Void.TYPE) { + errors.add(new Exception("Method " + method.getName() + "() should be void")); + } + } + + @Override + protected int getModifiers() { + return method.getModifiers(); + } + + /** + * Returns the return type of the method + */ + public Class getReturnType() { + return method.getReturnType(); + } + + /** + * Returns the return type of the method + */ + @Override + public Class getType() { + return getReturnType(); + } + + /** + * Returns the class where the method is actually declared + */ + @Override + public Class getDeclaringClass() { + return method.getDeclaringClass(); + } + + public void validateNoTypeParametersOnArgs(List errors) { + new NoGenericTypeParametersValidator(method).validate(errors); + } + + @Override + public boolean isShadowedBy(FrameworkMethod other) { + if (!other.getName().equals(getName())) { + return false; + } + if (other.getParameterTypes().length != getParameterTypes().length) { + return false; + } + for (int i = 0; i < other.getParameterTypes().length; i++) { + if (!other.getParameterTypes()[i].equals(getParameterTypes()[i])) { + return false; + } + } + return true; + } + + @Override + public boolean equals(Object obj) { + if (!FrameworkMethod.class.isInstance(obj)) { + return false; + } + return ((FrameworkMethod) obj).method.equals(method); + } + + @Override + public int hashCode() { + return method.hashCode(); + } + + /** + * Returns true if this is a no-arg method that returns a value assignable + * to {@code type} + * + * @deprecated This is used only by the Theories runner, and does not + * use all the generic type info that it ought to. It will be replaced + * with a forthcoming ParameterSignature#canAcceptResultOf(FrameworkMethod) + * once Theories moves to junit-contrib. + */ + @Deprecated + public boolean producesType(Type type) { + return getParameterTypes().length == 0 && type instanceof Class + && ((Class) type).isAssignableFrom(method.getReturnType()); + } + + private Class[] getParameterTypes() { + return method.getParameterTypes(); + } + + /** + * Returns the annotations on this method + */ + public Annotation[] getAnnotations() { + return method.getAnnotations(); + } + + /** + * Returns the annotation of type {@code annotationType} on this method, if + * one exists. + */ + public T getAnnotation(Class annotationType) { + return method.getAnnotation(annotationType); + } + + @Override + public String toString() { + return method.toString(); + } +} diff --git a/src/main/java/org/junit/runners/model/InitializationError.java b/src/main/java/org/junit/runners/model/InitializationError.java new file mode 100644 index 000000000000..dd9c8b33c696 --- /dev/null +++ b/src/main/java/org/junit/runners/model/InitializationError.java @@ -0,0 +1,47 @@ +package org.junit.runners.model; + +import java.util.Arrays; +import java.util.List; + +/** + * Represents one or more problems encountered while initializing a Runner + * + * @since 4.5 + */ +public class InitializationError extends Exception { + private static final long serialVersionUID = 1L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final List fErrors; + + /** + * Construct a new {@code InitializationError} with one or more + * errors {@code errors} as causes + */ + public InitializationError(List errors) { + this.fErrors = errors; + } + + public InitializationError(Throwable error) { + this(Arrays.asList(error)); + } + + /** + * Construct a new {@code InitializationError} with one cause + * with message {@code string} + */ + public InitializationError(String string) { + this(new Exception(string)); + } + + /** + * Returns one or more Throwables that led to this initialization error. + */ + public List getCauses() { + return fErrors; + } +} diff --git a/src/main/java/org/junit/runners/model/InvalidTestClassError.java b/src/main/java/org/junit/runners/model/InvalidTestClassError.java new file mode 100644 index 000000000000..57be61093a61 --- /dev/null +++ b/src/main/java/org/junit/runners/model/InvalidTestClassError.java @@ -0,0 +1,39 @@ +package org.junit.runners.model; + +import java.util.List; + +/** + * Thrown by {@link org.junit.runner.Runner}s in case the class under test is not valid. + *

      + * Its message conveniently lists all of the validation errors. + * + * @since 4.13 + */ +public class InvalidTestClassError extends InitializationError { + private static final long serialVersionUID = 1L; + + private final String message; + + public InvalidTestClassError(Class offendingTestClass, List validationErrors) { + super(validationErrors); + this.message = createMessage(offendingTestClass, validationErrors); + } + + private static String createMessage(Class testClass, List validationErrors) { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("Invalid test class '%s':", testClass.getName())); + int i = 1; + for (Throwable error : validationErrors) { + sb.append("\n " + (i++) + ". " + error.getMessage()); + } + return sb.toString(); + } + + /** + * @return a message with a list of all of the validation errors + */ + @Override + public String getMessage() { + return message; + } +} diff --git a/src/main/java/org/junit/runners/model/MultipleFailureException.java b/src/main/java/org/junit/runners/model/MultipleFailureException.java new file mode 100644 index 000000000000..809588b8118a --- /dev/null +++ b/src/main/java/org/junit/runners/model/MultipleFailureException.java @@ -0,0 +1,69 @@ +package org.junit.runners.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.internal.Throwables; + +/** + * Collects multiple {@code Throwable}s into one exception. + * + * @since 4.9 + */ +public class MultipleFailureException extends Exception { + private static final long serialVersionUID = 1L; + + /* + * We have to use the f prefix until the next major release to ensure + * serialization compatibility. + * See https://github.com/junit-team/junit4/issues/976 + */ + private final List fErrors; + + public MultipleFailureException(List errors) { + this.fErrors = new ArrayList(errors); + } + + public List getFailures() { + return Collections.unmodifiableList(fErrors); + } + + @Override + public String getMessage() { + StringBuilder sb = new StringBuilder( + String.format("There were %d errors:", fErrors.size())); + for (Throwable e : fErrors) { + sb.append(String.format("\n %s(%s)", e.getClass().getName(), e.getMessage())); + } + return sb.toString(); + } + + /** + * Asserts that a list of throwables is empty. If it isn't empty, + * will throw {@link MultipleFailureException} (if there are + * multiple throwables in the list) or the first element in the list + * (if there is only one element). + * + * @param errors list to check + * @throws Exception or Error if the list is not empty + */ + @SuppressWarnings("deprecation") + public static void assertEmpty(List errors) throws Exception { + if (errors.isEmpty()) { + return; + } + if (errors.size() == 1) { + throw Throwables.rethrowAsException(errors.get(0)); + } + + /* + * Many places in the code are documented to throw + * org.junit.internal.runners.model.MultipleFailureException. + * That class now extends this one, so we throw the internal + * exception in case developers have tests that catch + * MultipleFailureException. + */ + throw new org.junit.internal.runners.model.MultipleFailureException(errors); + } +} diff --git a/src/main/java/org/junit/runners/model/NoGenericTypeParametersValidator.java b/src/main/java/org/junit/runners/model/NoGenericTypeParametersValidator.java new file mode 100644 index 000000000000..386b7ffabbc7 --- /dev/null +++ b/src/main/java/org/junit/runners/model/NoGenericTypeParametersValidator.java @@ -0,0 +1,58 @@ +package org.junit.runners.model; + +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.List; + +class NoGenericTypeParametersValidator { + private final Method method; + + NoGenericTypeParametersValidator(Method method) { + this.method = method; + } + + void validate(List errors) { + for (Type each : method.getGenericParameterTypes()) { + validateNoTypeParameterOnType(each, errors); + } + } + + private void validateNoTypeParameterOnType(Type type, List errors) { + if (type instanceof TypeVariable) { + errors.add(new Exception("Method " + method.getName() + + "() contains unresolved type variable " + type)); + } else if (type instanceof ParameterizedType) { + validateNoTypeParameterOnParameterizedType((ParameterizedType) type, errors); + } else if (type instanceof WildcardType) { + validateNoTypeParameterOnWildcardType((WildcardType) type, errors); + } else if (type instanceof GenericArrayType) { + validateNoTypeParameterOnGenericArrayType((GenericArrayType) type, errors); + } + } + + private void validateNoTypeParameterOnParameterizedType(ParameterizedType parameterized, + List errors) { + for (Type each : parameterized.getActualTypeArguments()) { + validateNoTypeParameterOnType(each, errors); + } + } + + private void validateNoTypeParameterOnWildcardType(WildcardType wildcard, + List errors) { + for (Type each : wildcard.getUpperBounds()) { + validateNoTypeParameterOnType(each, errors); + } + for (Type each : wildcard.getLowerBounds()) { + validateNoTypeParameterOnType(each, errors); + } + } + + private void validateNoTypeParameterOnGenericArrayType( + GenericArrayType arrayType, List errors) { + validateNoTypeParameterOnType(arrayType.getGenericComponentType(), errors); + } +} \ No newline at end of file diff --git a/src/main/java/org/junit/runners/model/RunnerBuilder.java b/src/main/java/org/junit/runners/model/RunnerBuilder.java new file mode 100644 index 000000000000..bc6f85f04813 --- /dev/null +++ b/src/main/java/org/junit/runners/model/RunnerBuilder.java @@ -0,0 +1,115 @@ +package org.junit.runners.model; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.Runner; + +/** + * A RunnerBuilder is a strategy for constructing runners for classes. + * + * Only writers of custom runners should use RunnerBuilders. A custom runner class with a constructor taking + * a RunnerBuilder parameter will be passed the instance of RunnerBuilder used to build that runner itself. + * For example, + * imagine a custom runner that builds suites based on a list of classes in a text file: + * + *

      + * \@RunWith(TextFileSuite.class)
      + * \@SuiteSpecFile("mysuite.txt")
      + * class MySuite {}
      + * 
      + * + * The implementation of TextFileSuite might include: + * + *
      + * public TextFileSuite(Class testClass, RunnerBuilder builder) {
      + *   // ...
      + *   for (String className : readClassNames())
      + *     addRunner(builder.runnerForClass(Class.forName(className)));
      + *   // ...
      + * }
      + * 
      + * + * @see org.junit.runners.Suite + * @since 4.5 + */ +public abstract class RunnerBuilder { + private final Set> parents = new HashSet>(); + + /** + * Override to calculate the correct runner for a test class at runtime. + * + * @param testClass class to be run + * @return a Runner + * @throws Throwable if a runner cannot be constructed + */ + public abstract Runner runnerForClass(Class testClass) throws Throwable; + + /** + * Always returns a runner for the given test class. + * + *

      In case of an exception a runner will be returned that prints an error instead of running + * tests. + * + *

      Note that some of the internal JUnit implementations of RunnerBuilder will return + * {@code null} from this method, but no RunnerBuilder passed to a Runner constructor will + * return {@code null} from this method. + * + * @param testClass class to be run + * @return a Runner + */ + public Runner safeRunnerForClass(Class testClass) { + try { + return runnerForClass(testClass); + } catch (Throwable e) { + return new ErrorReportingRunner(testClass, e); + } + } + + Class addParent(Class parent) throws InitializationError { + if (!parents.add(parent)) { + throw new InitializationError(String.format("class '%s' (possibly indirectly) contains itself as a SuiteClass", parent.getName())); + } + return parent; + } + + void removeParent(Class klass) { + parents.remove(klass); + } + + /** + * Constructs and returns a list of Runners, one for each child class in + * {@code children}. Care is taken to avoid infinite recursion: + * this builder will throw an exception if it is requested for another + * runner for {@code parent} before this call completes. + */ + public List runners(Class parent, Class[] children) + throws InitializationError { + addParent(parent); + + try { + return runners(children); + } finally { + removeParent(parent); + } + } + + public List runners(Class parent, List> children) + throws InitializationError { + return runners(parent, children.toArray(new Class[0])); + } + + private List runners(Class[] children) { + List runners = new ArrayList(); + for (Class each : children) { + Runner childRunner = safeRunnerForClass(each); + if (childRunner != null) { + runners.add(childRunner); + } + } + return runners; + } +} diff --git a/src/main/java/org/junit/runners/model/RunnerScheduler.java b/src/main/java/org/junit/runners/model/RunnerScheduler.java new file mode 100644 index 000000000000..db43308b8ed9 --- /dev/null +++ b/src/main/java/org/junit/runners/model/RunnerScheduler.java @@ -0,0 +1,23 @@ +package org.junit.runners.model; + +/** + * Represents a strategy for scheduling when individual test methods + * should be run (in serial or parallel) + * + * WARNING: still experimental, may go away. + * + * @since 4.7 + */ +public interface RunnerScheduler { + /** + * Schedule a child statement to run + */ + void schedule(Runnable childStatement); + + /** + * Override to implement any behavior that must occur + * after all children have been scheduled (for example, + * waiting for them all to finish) + */ + void finished(); +} diff --git a/src/main/java/org/junit/runners/model/Statement.java b/src/main/java/org/junit/runners/model/Statement.java new file mode 100644 index 000000000000..fa53fa1a555a --- /dev/null +++ b/src/main/java/org/junit/runners/model/Statement.java @@ -0,0 +1,15 @@ +package org.junit.runners.model; + + +/** + * Represents one or more actions to be taken at runtime in the course + * of running a JUnit test suite. + * + * @since 4.5 + */ +public abstract class Statement { + /** + * Run the action, throwing a {@code Throwable} if anything goes wrong. + */ + public abstract void evaluate() throws Throwable; +} \ No newline at end of file diff --git a/src/main/java/org/junit/runners/model/TestClass.java b/src/main/java/org/junit/runners/model/TestClass.java new file mode 100755 index 000000000000..679c642147c8 --- /dev/null +++ b/src/main/java/org/junit/runners/model/TestClass.java @@ -0,0 +1,313 @@ +package org.junit.runners.model; + +import static java.lang.reflect.Modifier.isStatic; +import static org.junit.internal.MethodSorter.NAME_ASCENDING; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.internal.MethodSorter; + +/** + * Wraps a class to be run, providing method validation and annotation searching + * + * @since 4.5 + */ +public class TestClass implements Annotatable { + private static final FieldComparator FIELD_COMPARATOR = new FieldComparator(); + private static final MethodComparator METHOD_COMPARATOR = new MethodComparator(); + + private final Class clazz; + private final Map, List> methodsForAnnotations; + private final Map, List> fieldsForAnnotations; + + /** + * Creates a {@code TestClass} wrapping {@code clazz}. Each time this + * constructor executes, the class is scanned for annotations, which can be + * an expensive process (we hope in future JDK's it will not be.) Therefore, + * try to share instances of {@code TestClass} where possible. + */ + public TestClass(Class clazz) { + this.clazz = clazz; + if (clazz != null && clazz.getConstructors().length > 1) { + throw new IllegalArgumentException( + "Test class can only have one constructor"); + } + + Map, List> methodsForAnnotations = + new LinkedHashMap, List>(); + Map, List> fieldsForAnnotations = + new LinkedHashMap, List>(); + + scanAnnotatedMembers(methodsForAnnotations, fieldsForAnnotations); + + this.methodsForAnnotations = makeDeeplyUnmodifiable(methodsForAnnotations); + this.fieldsForAnnotations = makeDeeplyUnmodifiable(fieldsForAnnotations); + } + + protected void scanAnnotatedMembers(Map, List> methodsForAnnotations, Map, List> fieldsForAnnotations) { + for (Class eachClass : getSuperClasses(clazz)) { + for (Method eachMethod : MethodSorter.getDeclaredMethods(eachClass)) { + addToAnnotationLists(new FrameworkMethod(eachMethod), methodsForAnnotations); + } + // ensuring fields are sorted to make sure that entries are inserted + // and read from fieldForAnnotations in a deterministic order + for (Field eachField : getSortedDeclaredFields(eachClass)) { + addToAnnotationLists(new FrameworkField(eachField), fieldsForAnnotations); + } + } + } + + private static Field[] getSortedDeclaredFields(Class clazz) { + Field[] declaredFields = clazz.getDeclaredFields(); + Arrays.sort(declaredFields, FIELD_COMPARATOR); + return declaredFields; + } + + protected static > void addToAnnotationLists(T member, + Map, List> map) { + for (Annotation each : member.getAnnotations()) { + Class type = each.annotationType(); + List members = getAnnotatedMembers(map, type, true); + if (member.isShadowedBy(members)) { + return; + } + if (runsTopToBottom(type)) { + members.add(0, member); + } else { + members.add(member); + } + } + } + + private static > Map, List> + makeDeeplyUnmodifiable(Map, List> source) { + Map, List> copy = + new LinkedHashMap, List>(); + for (Map.Entry, List> entry : source.entrySet()) { + copy.put(entry.getKey(), Collections.unmodifiableList(entry.getValue())); + } + return Collections.unmodifiableMap(copy); + } + + /** + * Returns, efficiently, all the non-overridden methods in this class and + * its superclasses that are annotated}. + * + * @since 4.12 + */ + public List getAnnotatedMethods() { + List methods = collectValues(methodsForAnnotations); + Collections.sort(methods, METHOD_COMPARATOR); + return methods; + } + + /** + * Returns, efficiently, all the non-overridden methods in this class and + * its superclasses that are annotated with {@code annotationClass}. + */ + public List getAnnotatedMethods( + Class annotationClass) { + return Collections.unmodifiableList(getAnnotatedMembers(methodsForAnnotations, annotationClass, false)); + } + + /** + * Returns, efficiently, all the non-overridden fields in this class and its + * superclasses that are annotated. + * + * @since 4.12 + */ + public List getAnnotatedFields() { + return collectValues(fieldsForAnnotations); + } + + /** + * Returns, efficiently, all the non-overridden fields in this class and its + * superclasses that are annotated with {@code annotationClass}. + */ + public List getAnnotatedFields( + Class annotationClass) { + return Collections.unmodifiableList(getAnnotatedMembers(fieldsForAnnotations, annotationClass, false)); + } + + private List collectValues(Map> map) { + Set values = new LinkedHashSet(); + for (List additionalValues : map.values()) { + values.addAll(additionalValues); + } + return new ArrayList(values); + } + + private static List getAnnotatedMembers(Map, List> map, + Class type, boolean fillIfAbsent) { + if (!map.containsKey(type) && fillIfAbsent) { + map.put(type, new ArrayList()); + } + List members = map.get(type); + return members == null ? Collections.emptyList() : members; + } + + private static boolean runsTopToBottom(Class annotation) { + return annotation.equals(Before.class) + || annotation.equals(BeforeClass.class); + } + + private static List> getSuperClasses(Class testClass) { + List> results = new ArrayList>(); + Class current = testClass; + while (current != null) { + results.add(current); + current = current.getSuperclass(); + } + return results; + } + + /** + * Returns the underlying Java class. + */ + public Class getJavaClass() { + return clazz; + } + + /** + * Returns the class's name. + */ + public String getName() { + if (clazz == null) { + return "null"; + } + return clazz.getName(); + } + + /** + * Returns the only public constructor in the class, or throws an {@code + * AssertionError} if there are more or less than one. + */ + + public Constructor getOnlyConstructor() { + Constructor[] constructors = clazz.getConstructors(); + Assert.assertEquals(1, constructors.length); + return constructors[0]; + } + + /** + * Returns the annotations on this class + */ + public Annotation[] getAnnotations() { + if (clazz == null) { + return new Annotation[0]; + } + return clazz.getAnnotations(); + } + + public T getAnnotation(Class annotationType) { + if (clazz == null) { + return null; + } + return clazz.getAnnotation(annotationType); + } + + public List getAnnotatedFieldValues(Object test, + Class annotationClass, Class valueClass) { + List results = new ArrayList(); + for (FrameworkField each : getAnnotatedFields(annotationClass)) { + try { + Object fieldValue = each.get(test); + if (valueClass.isInstance(fieldValue)) { + results.add(valueClass.cast(fieldValue)); + } + } catch (IllegalAccessException e) { + throw new RuntimeException( + "How did getFields return a field we couldn't access?", e); + } + } + return results; + } + + public List getAnnotatedMethodValues(Object test, + Class annotationClass, Class valueClass) { + List results = new ArrayList(); + for (FrameworkMethod each : getAnnotatedMethods(annotationClass)) { + try { + /* + * A method annotated with @Rule may return a @TestRule or a @MethodRule, + * we cannot call the method to check whether the return type matches our + * expectation i.e. subclass of valueClass. If we do that then the method + * will be invoked twice and we do not want to do that. So we first check + * whether return type matches our expectation and only then call the method + * to fetch the MethodRule + */ + if (valueClass.isAssignableFrom(each.getReturnType())) { + Object fieldValue = each.invokeExplosively(test); + results.add(valueClass.cast(fieldValue)); + } + } catch (Throwable e) { + throw new RuntimeException( + "Exception in " + each.getName(), e); + } + } + return results; + } + + public boolean isPublic() { + return Modifier.isPublic(clazz.getModifiers()); + } + + public boolean isANonStaticInnerClass() { + return clazz.isMemberClass() && !isStatic(clazz.getModifiers()); + } + + @Override + public int hashCode() { + return (clazz == null) ? 0 : clazz.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TestClass other = (TestClass) obj; + return clazz == other.clazz; + } + + /** + * Compares two fields by its name. + */ + private static class FieldComparator implements Comparator { + public int compare(Field left, Field right) { + return left.getName().compareTo(right.getName()); + } + } + + /** + * Compares two methods by its name. + */ + private static class MethodComparator implements + Comparator { + public int compare(FrameworkMethod left, FrameworkMethod right) { + return NAME_ASCENDING.compare(left.getMethod(), right.getMethod()); + } + } +} diff --git a/src/main/java/org/junit/runners/model/TestTimedOutException.java b/src/main/java/org/junit/runners/model/TestTimedOutException.java new file mode 100644 index 000000000000..60e1a8aa9001 --- /dev/null +++ b/src/main/java/org/junit/runners/model/TestTimedOutException.java @@ -0,0 +1,44 @@ +package org.junit.runners.model; + +import java.util.concurrent.TimeUnit; + +/** + * Exception thrown when a test fails on timeout. + * + * @since 4.12 + * + */ +public class TestTimedOutException extends Exception { + + private static final long serialVersionUID = 31935685163547539L; + + private final TimeUnit timeUnit; + private final long timeout; + + /** + * Creates exception with a standard message "test timed out after [timeout] [timeUnit]" + * + * @param timeout the amount of time passed before the test was interrupted + * @param timeUnit the time unit for the timeout value + */ + public TestTimedOutException(long timeout, TimeUnit timeUnit) { + super(String.format("test timed out after %d %s", + timeout, timeUnit.name().toLowerCase())); + this.timeUnit = timeUnit; + this.timeout = timeout; + } + + /** + * Gets the time passed before the test was interrupted + */ + public long getTimeout() { + return timeout; + } + + /** + * Gets the time unit for the timeout value + */ + public TimeUnit getTimeUnit() { + return timeUnit; + } +} diff --git a/src/main/java/org/junit/runners/package-info.java b/src/main/java/org/junit/runners/package-info.java new file mode 100644 index 000000000000..418acaff0363 --- /dev/null +++ b/src/main/java/org/junit/runners/package-info.java @@ -0,0 +1,8 @@ +/** + * Provides standard {@link org.junit.runner.Runner Runner} implementations. + * + * @since 4.0 + * @see org.junit.runner.Runner + * @see org.junit.runners.BlockJUnit4ClassRunner + */ +package org.junit.runners; \ No newline at end of file diff --git a/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParameters.java b/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParameters.java new file mode 100644 index 000000000000..ffed4beaf6bb --- /dev/null +++ b/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParameters.java @@ -0,0 +1,170 @@ +package org.junit.runners.parameterized; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.List; + +import org.junit.runner.RunWith; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.model.FrameworkField; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.Statement; + +/** + * A {@link BlockJUnit4ClassRunner} with parameters support. Parameters can be + * injected via constructor or into annotated fields. + */ +public class BlockJUnit4ClassRunnerWithParameters extends + BlockJUnit4ClassRunner { + private enum InjectionType { + CONSTRUCTOR, FIELD + } + + private final Object[] parameters; + + private final String name; + + public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test) + throws InitializationError { + super(test.getTestClass().getJavaClass()); + parameters = test.getParameters().toArray( + new Object[test.getParameters().size()]); + name = test.getName(); + } + + @Override + public Object createTest() throws Exception { + InjectionType injectionType = getInjectionType(); + switch (injectionType) { + case CONSTRUCTOR: + return createTestUsingConstructorInjection(); + case FIELD: + return createTestUsingFieldInjection(); + default: + throw new IllegalStateException("The injection type " + + injectionType + " is not supported."); + } + } + + private Object createTestUsingConstructorInjection() throws Exception { + return getTestClass().getOnlyConstructor().newInstance(parameters); + } + + private Object createTestUsingFieldInjection() throws Exception { + List annotatedFieldsByParameter = getAnnotatedFieldsByParameter(); + if (annotatedFieldsByParameter.size() != parameters.length) { + throw new Exception( + "Wrong number of parameters and @Parameter fields." + + " @Parameter fields counted: " + + annotatedFieldsByParameter.size() + + ", available parameters: " + parameters.length + + "."); + } + Object testClassInstance = getTestClass().getJavaClass().newInstance(); + for (FrameworkField each : annotatedFieldsByParameter) { + Field field = each.getField(); + Parameter annotation = field.getAnnotation(Parameter.class); + int index = annotation.value(); + try { + field.set(testClassInstance, parameters[index]); + } catch (IllegalArgumentException iare) { + throw new Exception(getTestClass().getName() + + ": Trying to set " + field.getName() + + " with the value " + parameters[index] + + " that is not the right type (" + + parameters[index].getClass().getSimpleName() + + " instead of " + field.getType().getSimpleName() + + ").", iare); + } + } + return testClassInstance; + } + + @Override + protected String getName() { + return name; + } + + @Override + protected String testName(FrameworkMethod method) { + return method.getName() + getName(); + } + + @Override + protected void validateConstructor(List errors) { + validateOnlyOneConstructor(errors); + if (getInjectionType() != InjectionType.CONSTRUCTOR) { + validateZeroArgConstructor(errors); + } + } + + @Override + protected void validateFields(List errors) { + super.validateFields(errors); + if (getInjectionType() == InjectionType.FIELD) { + List annotatedFieldsByParameter = getAnnotatedFieldsByParameter(); + int[] usedIndices = new int[annotatedFieldsByParameter.size()]; + for (FrameworkField each : annotatedFieldsByParameter) { + int index = each.getField().getAnnotation(Parameter.class) + .value(); + if (index < 0 || index > annotatedFieldsByParameter.size() - 1) { + errors.add(new Exception("Invalid @Parameter value: " + + index + ". @Parameter fields counted: " + + annotatedFieldsByParameter.size() + + ". Please use an index between 0 and " + + (annotatedFieldsByParameter.size() - 1) + ".")); + } else { + usedIndices[index]++; + } + } + for (int index = 0; index < usedIndices.length; index++) { + int numberOfUse = usedIndices[index]; + if (numberOfUse == 0) { + errors.add(new Exception("@Parameter(" + index + + ") is never used.")); + } else if (numberOfUse > 1) { + errors.add(new Exception("@Parameter(" + index + + ") is used more than once (" + numberOfUse + ").")); + } + } + } + } + + @Override + protected Statement classBlock(RunNotifier notifier) { + return childrenInvoker(notifier); + } + + @Override + protected Annotation[] getRunnerAnnotations() { + Annotation[] allAnnotations = super.getRunnerAnnotations(); + Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1]; + int i = 0; + for (Annotation annotation: allAnnotations) { + if (!annotation.annotationType().equals(RunWith.class)) { + annotationsWithoutRunWith[i] = annotation; + ++i; + } + } + return annotationsWithoutRunWith; + } + + private List getAnnotatedFieldsByParameter() { + return getTestClass().getAnnotatedFields(Parameter.class); + } + + private InjectionType getInjectionType() { + if (fieldsAreAnnotated()) { + return InjectionType.FIELD; + } else { + return InjectionType.CONSTRUCTOR; + } + } + + private boolean fieldsAreAnnotated() { + return !getAnnotatedFieldsByParameter().isEmpty(); + } +} diff --git a/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersFactory.java b/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersFactory.java new file mode 100644 index 000000000000..ae49ef4ba73b --- /dev/null +++ b/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersFactory.java @@ -0,0 +1,18 @@ +package org.junit.runners.parameterized; + +import org.junit.runner.Runner; +import org.junit.runners.model.InitializationError; + +/** + * A {@link ParametersRunnerFactory} that creates + * {@link BlockJUnit4ClassRunnerWithParameters}. + * + * @since 4.12 + */ +public class BlockJUnit4ClassRunnerWithParametersFactory implements + ParametersRunnerFactory { + public Runner createRunnerForTestWithParameters(TestWithParameters test) + throws InitializationError { + return new BlockJUnit4ClassRunnerWithParameters(test); + } +} diff --git a/src/main/java/org/junit/runners/parameterized/ParametersRunnerFactory.java b/src/main/java/org/junit/runners/parameterized/ParametersRunnerFactory.java new file mode 100644 index 000000000000..8123e83b1a15 --- /dev/null +++ b/src/main/java/org/junit/runners/parameterized/ParametersRunnerFactory.java @@ -0,0 +1,21 @@ +package org.junit.runners.parameterized; + +import org.junit.runner.Runner; +import org.junit.runners.model.InitializationError; + +/** + * A {@code ParametersRunnerFactory} creates a runner for a single + * {@link TestWithParameters}. + * + * @since 4.12 + */ +public interface ParametersRunnerFactory { + /** + * Returns a runner for the specified {@link TestWithParameters}. + * + * @throws InitializationError + * if the runner could not be created. + */ + Runner createRunnerForTestWithParameters(TestWithParameters test) + throws InitializationError; +} diff --git a/src/main/java/org/junit/runners/parameterized/TestWithParameters.java b/src/main/java/org/junit/runners/parameterized/TestWithParameters.java new file mode 100644 index 000000000000..1b86644a2940 --- /dev/null +++ b/src/main/java/org/junit/runners/parameterized/TestWithParameters.java @@ -0,0 +1,82 @@ +package org.junit.runners.parameterized; + +import static java.util.Collections.unmodifiableList; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.runners.model.TestClass; + +/** + * A {@code TestWithParameters} keeps the data together that are needed for + * creating a runner for a single data set of a parameterized test. It has a + * name, the test class and a list of parameters. + * + * @since 4.12 + */ +public class TestWithParameters { + private final String name; + + private final TestClass testClass; + + private final List parameters; + + public TestWithParameters(String name, TestClass testClass, + List parameters) { + notNull(name, "The name is missing."); + notNull(testClass, "The test class is missing."); + notNull(parameters, "The parameters are missing."); + this.name = name; + this.testClass = testClass; + this.parameters = unmodifiableList(new ArrayList(parameters)); + } + + public String getName() { + return name; + } + + public TestClass getTestClass() { + return testClass; + } + + public List getParameters() { + return parameters; + } + + @Override + public int hashCode() { + int prime = 14747; + int result = prime + name.hashCode(); + result = prime * result + testClass.hashCode(); + return prime * result + parameters.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TestWithParameters other = (TestWithParameters) obj; + return name.equals(other.name) + && parameters.equals(other.parameters) + && testClass.equals(other.testClass); + } + + @Override + public String toString() { + return testClass.getName() + " '" + name + "' with parameters " + + parameters; + } + + private static void notNull(Object value, String message) { + if (value == null) { + throw new NullPointerException(message); + } + } +} diff --git a/src/main/java/org/junit/validator/AnnotationValidator.java b/src/main/java/org/junit/validator/AnnotationValidator.java new file mode 100644 index 000000000000..8a53adfd54e6 --- /dev/null +++ b/src/main/java/org/junit/validator/AnnotationValidator.java @@ -0,0 +1,60 @@ +package org.junit.validator; + +import org.junit.runners.model.FrameworkField; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; + +import static java.util.Collections.emptyList; + +import java.util.List; + +/** + * Validates annotations on classes and methods. To be validated, + * an annotation should be annotated with {@link ValidateWith} + * + * Instances of this class are shared by multiple test runners, so they should + * be immutable and thread-safe. + * + * @since 4.12 + */ +public abstract class AnnotationValidator { + + private static final List NO_VALIDATION_ERRORS = emptyList(); + + /** + * Validates annotation on the given class. + * + * @param testClass that is being validated + * @return A list of exceptions. Default behavior is to return an empty list. + * + * @since 4.12 + */ + public List validateAnnotatedClass(TestClass testClass) { + return NO_VALIDATION_ERRORS; + } + + /** + * Validates annotation on the given field. + * + * @param field that is being validated + * @return A list of exceptions. Default behavior is to return an empty list. + * + * @since 4.12 + */ + public List validateAnnotatedField(FrameworkField field) { + return NO_VALIDATION_ERRORS; + + } + + /** + * Validates annotation on the given method. + * + * @param method that is being validated + * @return A list of exceptions. Default behavior is to return an empty list. + * + * @since 4.12 + */ + public List validateAnnotatedMethod(FrameworkMethod method) { + return NO_VALIDATION_ERRORS; + } +} diff --git a/src/main/java/org/junit/validator/AnnotationValidatorFactory.java b/src/main/java/org/junit/validator/AnnotationValidatorFactory.java new file mode 100644 index 000000000000..fb2460d08fbe --- /dev/null +++ b/src/main/java/org/junit/validator/AnnotationValidatorFactory.java @@ -0,0 +1,39 @@ +package org.junit.validator; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * Creates instances of Annotation Validators. + * + * @since 4.12 + */ +public class AnnotationValidatorFactory { + private static final ConcurrentHashMap VALIDATORS_FOR_ANNOTATION_TYPES = + new ConcurrentHashMap(); + + /** + * Creates the AnnotationValidator specified by the value in + * {@link org.junit.validator.ValidateWith}. Instances are + * cached. + * + * @return An instance of the AnnotationValidator. + * + * @since 4.12 + */ + public AnnotationValidator createAnnotationValidator(ValidateWith validateWithAnnotation) { + AnnotationValidator validator = VALIDATORS_FOR_ANNOTATION_TYPES.get(validateWithAnnotation); + if (validator != null) { + return validator; + } + + Class clazz = validateWithAnnotation.value(); + try { + AnnotationValidator annotationValidator = clazz.newInstance(); + VALIDATORS_FOR_ANNOTATION_TYPES.putIfAbsent(validateWithAnnotation, annotationValidator); + return VALIDATORS_FOR_ANNOTATION_TYPES.get(validateWithAnnotation); + } catch (Exception e) { + throw new RuntimeException("Exception received when creating AnnotationValidator class " + clazz.getName(), e); + } + } + +} diff --git a/src/main/java/org/junit/validator/AnnotationsValidator.java b/src/main/java/org/junit/validator/AnnotationsValidator.java new file mode 100644 index 000000000000..44d99d2a2f8d --- /dev/null +++ b/src/main/java/org/junit/validator/AnnotationsValidator.java @@ -0,0 +1,120 @@ +package org.junit.validator; + +import static java.util.Collections.singletonList; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.runners.model.Annotatable; +import org.junit.runners.model.FrameworkField; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; + +/** + * An {@code AnnotationsValidator} validates all annotations of a test class, + * including its annotated fields and methods. + * + * @since 4.12 + */ +public final class AnnotationsValidator implements TestClassValidator { + private static final List> VALIDATORS = Arrays.>asList( + new ClassValidator(), new MethodValidator(), new FieldValidator()); + + /** + * Validate all annotations of the specified test class that are be + * annotated with {@link ValidateWith}. + * + * @param testClass + * the {@link TestClass} that is validated. + * @return the errors found by the validator. + */ + public List validateTestClass(TestClass testClass) { + List validationErrors= new ArrayList(); + for (AnnotatableValidator validator : VALIDATORS) { + List additionalErrors= validator + .validateTestClass(testClass); + validationErrors.addAll(additionalErrors); + } + return validationErrors; + } + + private static abstract class AnnotatableValidator { + private static final AnnotationValidatorFactory ANNOTATION_VALIDATOR_FACTORY = new AnnotationValidatorFactory(); + + abstract Iterable getAnnotatablesForTestClass(TestClass testClass); + + abstract List validateAnnotatable( + AnnotationValidator validator, T annotatable); + + public List validateTestClass(TestClass testClass) { + List validationErrors= new ArrayList(); + for (T annotatable : getAnnotatablesForTestClass(testClass)) { + List additionalErrors= validateAnnotatable(annotatable); + validationErrors.addAll(additionalErrors); + } + return validationErrors; + } + + private List validateAnnotatable(T annotatable) { + List validationErrors= new ArrayList(); + for (Annotation annotation : annotatable.getAnnotations()) { + Class annotationType = annotation + .annotationType(); + ValidateWith validateWith = annotationType + .getAnnotation(ValidateWith.class); + if (validateWith != null) { + AnnotationValidator annotationValidator = ANNOTATION_VALIDATOR_FACTORY + .createAnnotationValidator(validateWith); + List errors= validateAnnotatable( + annotationValidator, annotatable); + validationErrors.addAll(errors); + } + } + return validationErrors; + } + } + + private static class ClassValidator extends AnnotatableValidator { + @Override + Iterable getAnnotatablesForTestClass(TestClass testClass) { + return singletonList(testClass); + } + + @Override + List validateAnnotatable( + AnnotationValidator validator, TestClass testClass) { + return validator.validateAnnotatedClass(testClass); + } + } + + private static class MethodValidator extends + AnnotatableValidator { + @Override + Iterable getAnnotatablesForTestClass( + TestClass testClass) { + return testClass.getAnnotatedMethods(); + } + + @Override + List validateAnnotatable( + AnnotationValidator validator, FrameworkMethod method) { + return validator.validateAnnotatedMethod(method); + } + } + + private static class FieldValidator extends + AnnotatableValidator { + @Override + Iterable getAnnotatablesForTestClass(TestClass testClass) { + return testClass.getAnnotatedFields(); + } + + @Override + List validateAnnotatable( + AnnotationValidator validator, FrameworkField field) { + return validator.validateAnnotatedField(field); + } + } +} diff --git a/src/main/java/org/junit/validator/PublicClassValidator.java b/src/main/java/org/junit/validator/PublicClassValidator.java new file mode 100644 index 000000000000..fe3f18557f85 --- /dev/null +++ b/src/main/java/org/junit/validator/PublicClassValidator.java @@ -0,0 +1,33 @@ +package org.junit.validator; + +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; + +import java.util.List; + +import org.junit.runners.model.TestClass; + +/** + * Validates that a {@link TestClass} is public. + * + * @since 4.12 + */ +public class PublicClassValidator implements TestClassValidator { + private static final List NO_VALIDATION_ERRORS = emptyList(); + + /** + * Validate that the specified {@link TestClass} is public. + * + * @param testClass the {@link TestClass} that is validated. + * @return an empty list if the class is public or a list with a single + * exception otherwise. + */ + public List validateTestClass(TestClass testClass) { + if (testClass.isPublic()) { + return NO_VALIDATION_ERRORS; + } else { + return singletonList(new Exception("The class " + + testClass.getName() + " is not public.")); + } + } +} diff --git a/src/main/java/org/junit/validator/TestClassValidator.java b/src/main/java/org/junit/validator/TestClassValidator.java new file mode 100644 index 000000000000..ba5e892a156f --- /dev/null +++ b/src/main/java/org/junit/validator/TestClassValidator.java @@ -0,0 +1,21 @@ +package org.junit.validator; + +import java.util.List; + +import org.junit.runners.model.TestClass; + +/** + * Validates a single facet of a test class. + * + * @since 4.12 + */ +public interface TestClassValidator { + /** + * Validate a single facet of a test class. + * + * @param testClass + * the {@link TestClass} that is validated. + * @return the validation errors found by the validator. + */ + List validateTestClass(TestClass testClass); +} diff --git a/src/main/java/org/junit/validator/ValidateWith.java b/src/main/java/org/junit/validator/ValidateWith.java new file mode 100644 index 000000000000..03d790670f75 --- /dev/null +++ b/src/main/java/org/junit/validator/ValidateWith.java @@ -0,0 +1,19 @@ +package org.junit.validator; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Allows for an {@link AnnotationValidator} to be attached to an annotation. + * + *

      When attached to an annotation, the validator will be instantiated and invoked + * by the {@link org.junit.runners.ParentRunner}.

      + * + * @since 4.12 + */ +@Retention(RetentionPolicy.RUNTIME) +@Inherited +public @interface ValidateWith { + Class value(); +} diff --git a/src/main/javadoc/stylesheet.css b/src/main/javadoc/stylesheet.css new file mode 100644 index 000000000000..2419f7b364aa --- /dev/null +++ b/src/main/javadoc/stylesheet.css @@ -0,0 +1 @@ +/* Javadoc style sheet */ /* makes unvisited links red (red bad) */ A {color:red;} /* makes visited links the same green as the toolbar (green good) */ A:visited {color:#03A35D;} /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF } /* Table colors */ .TableHeadingColor { background: #03A35D} /* Green */ .TableSubHeadingColor { background: #03A35D } /* Green */ .TableRowColor { background: #FFFFFF } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: normal; font-family: normal } .FrameHeadingFont { font-size: normal; font-family: normal } .FrameItemFont { font-size: normal; font-family: normal } /* Example of smaller, sans-serif font in frames */ /* .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } */ /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#03A35D;}/* Green */ .NavBarCell1Rev { background-color:#006400;}/* Dark green */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} \ No newline at end of file diff --git a/src/main/resources/junit/runner/logo.gif b/src/main/resources/junit/runner/logo.gif new file mode 100644 index 0000000000000000000000000000000000000000..d0e1547386053e17cbbfab58666613a8119cf21f GIT binary patch literal 964 zcmZ?wbhEHbRAZ20_|C-u1Px%^0Hzv%yao_p`2&P3fByUdN{)ij5E$wqaNxj!|3E+d zXZR1MfHaT=1d2ad7#SG27<51$1my__j)e@O95Nmo794Em5SDT|FkxX6i-59|h=$># z18uzGNirH27r3@6ICtrEY+Q19qK0?TACC!7U8m|BuPeD3xWsdYMsD7jnZc=s8UjN-1P&ZH@E_=h{|x`Z z6p#k8fItW2F;HG`;D}%lylN0H+!}GXMYp literal 0 HcmV?d00001 diff --git a/src/site/fml/faq.fml b/src/site/fml/faq.fml new file mode 100644 index 000000000000..507712f3922a --- /dev/null +++ b/src/site/fml/faq.fml @@ -0,0 +1,1746 @@ + + + About this frequently asked questions list + + Who is responsible for this FAQ? + +

      The current version of this FAQ is maintained + by Mike Clark.

      +

      Most of the wisdom contained in this FAQ comes from the + collective insights and hard-won experiences of the many good + folks who participate on the JUnit mailing list and the JUnit + community at large.

      +

      If you see your genius represented anywhere in this FAQ without + due credit to you, please send me an email and I'll make things + right.

      +
      +
      + + How can I contribute to this FAQ? + +

      Your contributions to this FAQ are greatly appreciated! The + JUnit community thanks you in advance.

      +

      To contribute to this FAQ, simply write a JUnit-related question + and answer, then send the unformatted text + to + + + Mike Clark. + Corrections to this FAQ are always appreciated, as well.

      +

      No reasonable contribution will be denied. Your name will + always appear along with any contribution you make.

      +
      +
      + + Where do I get the latest version of this + FAQ? + +

      The master copy of this FAQ is available + at + + + http://junit.sourceforge.net/doc/faq/faq.htm.

      +

      The JUnit distribution also includes this FAQ in + the + + + docdirectory.

      +
      +
      +
      + + Overview + What is JUnit? +

      + JUnit is a simple, open source framework to write and run + repeatable tests. It is an instance of the xUnit architecture + for unit testing frameworks. JUnit features include: +

      +
        +
      • Assertions for testing expected results
      • +
      • Test fixtures for sharing common test data
      • +
      • Test runners for running tests
      • +
      +

      + JUnit was originally written by Erich Gamma and Kent Beck. +

      +
      +
      + Where is the JUnit home page? + +

      + The official JUnit home page is http://junit.org. +

      +
      +
      +Where are the JUnit mailing lists and + forums? + +

      + There are 3 mailing lists dedicated to everything JUnit: +

      + +
      +
      +Where is the JUnit + documentation? + +

      + The following documents are included in the JUnit distribution + in the doc directory: +

      + +
      +
      +Where can I find articles on + JUnit? +

      + The JUnit home page maintains a list + of JUnit + articles. +

      +
      +
      + How is JUnit licensed? + +

      + JUnit is Open Source + Software, released + under the + Eclipse Public License Version 1.0 and hosted + on SourceForge. +

      +
      +
      + What awards has JUnit won? + + + + +
      + + Getting Started + + Where do I download JUnit? +

      + The latest version of JUnit is available + on SourceForge. +

      +
      + + How do I install JUnit? +
        +
      1. +

        + First, download + the + latest version of JUnit, referred to below + as junit.zip. +

        +
      2. +
      3. +

        + Then install JUnit on your platform of choice: +

        +

        + Windows +

        +

        + To install JUnit on Windows, follow these steps: +

        +
          +
        1. +

          + Unzip the junit.zip distribution file to + a directory referred to as %JUNIT_HOME%. +

          +
        2. +
        3. Add JUnit to the classpath: +

          + set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar +

          +
        4. +
        +

        + Unix (bash) +

        +

        + To install JUnit on Unix, follow these steps: +

        +
          +
        1. +

          + Unzip the junit.zip distribution file to + a directory referred to as $JUNIT_HOME. +

          +
        2. +
        3. +

          + Add JUnit to the classpath: +

          +

          + export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar +

          +
        4. +
        +
      4. +
      5. +

        + (Optional) Unzip + the $JUNIT_HOME/src.jar file. +

        +
      6. +
      7. +

        + Test the installation by running the sample tests + distributed with JUnit. Note that the sample tests are + located in the installation directory directly, not + the junit.jar file. Therefore, make sure that + the JUnit installation directory is on your CLASSPATH. Then + simply type: +

        +
        java org.junit.runner.JUnitCore org.junit.tests.AllTests
        +

        + All the tests should pass with an "OK" message. +

        +

        + + If the tests don't pass, verify + that junit.jar is in the CLASSPATH. + +

        +
      8. +
      9. +

        + Finally, read the documentation. +

        +
      10. +
      +
      + + How do I uninstall JUnit? +
        +
      1. +

        + Delete the directory structure where you unzipped the JUnit + distribution. +

        +
      2. +
      3. +

        + Remove junit.jar from the CLASSPATH. +

        +
      4. +
      +

      + JUnit does not modify the registry so simply removing all the + files will fully uninstall it. +

      +
      + + How do I ask questions? +

      + Questions that are not answered in + the FAQ or + in the documentation should be posted + to + the jGuru + discussion forum or the JUnit user mailing + list. +

      +

      + Please stick to technical issues on the discussion forum and + mailing lists. Keep in mind that these are public, so + do not include any confidental information in your + questions! +

      +

      + You should also + read "How + to ask questions the smart way" by Eric Raymond before + participating in the discussion forum and mailing lists. +

      +

      + + NOTE:
      Please do NOT submit bugs, patches, or feature + requests to the discussion forum or mailing lists.
      + Refer instead to "How do I submit bugs, + patches, or feature requests?". +
      +

      +
      + + How do I submit bugs, patches, or + feature requests? +

      + JUnit celebrates programmers testing their own software. In this + spirit, bugs, patches, and feature requests that include JUnit + tests have a better chance of being addressed than those + without. +

      +

      + JUnit is hosted + on GitHub. + Please use the tools provided by GitHub for your + submissions. +

      +
      +
      +
      + + Writing Tests + How do I write and run a simple test?
        +
      1. +

        + Create a class: +

        +
        package junitfaq;
        +      
        +import org.junit.*;
        +import static org.junit.Assert.*;
        +
        +import java.util.*;
        +
        +public class SimpleTest {
        +
      2. +
      3. +

        + Write a test method (annotated with @Test) that + asserts expected results on the object under test: +

        +
            @Test
        +    public void testEmptyCollection() {
        +        Collection collection = new ArrayList();
        +        assertTrue(collection.isEmpty());
        +    }
        +
      4. +
      5. +

        + If you are running your JUnit 4 tests with a JUnit 3.x runner, + write a suite() method that uses the + JUnit4TestAdapter class to create a suite + containing all of your test methods: +

        +
            public static junit.framework.Test suite() {
        +        return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
        +    }
        +
      6. +
      7. +

        + Although writing a main() method to run the + test is much less important with the advent of IDE runners, + it's still possible: +

        +
            public static void main(String args[]) {
        +      org.junit.runner.JUnitCore.main("junitfaq.SimpleTest");
        +    }
        +}
        +
      8. +
      9. +

        + Run the test: +

        +
          +
        • +

          + To run the test from the console, type: +

          +
          java org.junit.runner.JUnitCore junitfaq.SimpleTest
          +
        • +
        • +

          + To run the test with the test runner used + in main(), type: +

          +
          java junitfaq.SimpleTest
          +
        • +
        +

        + The passing test results in the following textual output: +

        +
        .
        +Time: 0
        +
        +OK (1 tests)
        +
      10. +
      +
      + How do I use a test fixture?

      + (Submitted by: Jeff Nielsen) +

      +

      + A test fixture is useful if you have two or more tests for a + common set of objects. Using a test fixture avoids duplicating + the code necessary to initialize (and cleanup) the common + objects. +

      +

      + Tests can use the objects (variables) in a test fixture, with + each test invoking different methods on objects in the fixture + and asserting different expected results. Each test runs in its + own test fixture to isolate tests from the changes made by other + tests. That is, tests don't share the state of objects in + the test fixture. Because the tests are isolated, they can + be run in any order. +

      +

      + To create a test fixture, declare instance variables for the + common objects. Initialize these objects in a public + void method annotated with @Before. The + JUnit framework automatically invokes any @Before + methods before each test is run. +

      +

      + The following example shows a test fixture with a common + Collection object. +

      +
      package junitfaq;
      +
      +import org.junit.*;
      +import static org.junit.Assert.*;
      +import java.util.*;
      +
      +public class SimpleTest {
      +
      +    private Collection<Object> collection;
      +
      +    @Before
      +    public void setUp() {
      +        collection = new ArrayList<Object>();
      +    }
      +
      +    @Test
      +    public void testEmptyCollection() {
      +        assertTrue(collection.isEmpty());
      +    }
      +
      +
      +    @Test
      +    public void testOneItemCollection() {
      +        collection.add("itemA");
      +        assertEquals(1, collection.size());
      +    }
      +}
      + +

      + Given this test, the methods might execute in the following + order: +

      +
      setUp()
      +testEmptyCollection()
      +setUp()
      +testOneItemCollection()
      +

      + The ordering of test-method invocations is not guaranteed, so + testOneItemCollection() might be executed before + testEmptyCollection(). But it doesn't matter, + because each method gets its own instance of the + collection. +

      + +

      + Although JUnit provides a new instance of the fixture objects + for each test method, if you allocate any external + resources in a @Before method, you should release + them after the test runs by annotating a method with + @After. The JUnit framework automatically invokes + any @After methods after each test is run. For + example: +

      + +
      package junitfaq;
      +
      +import org.junit.*;
      +import static org.junit.Assert.*;
      +import java.io.*;
      +
      +public class OutputTest {
      +
      +    private File output;
      +
      +    @Before
      +    public void createOutputFile() {
      +        output = new File(...);
      +    }
      +
      +    @After
      +    public void deleteOutputFile() {
      +        output.delete();
      +    }
      +
      +    @Test
      +    public void testSomethingWithFile() {
      +        ...
      +    }
      +}
      +

      + With this test, the methods will execute in the following order: +

      +
      +createOutputFile()
      +testSomethingWithFile()
      +deleteOutputFile()
      + How do I test a method that doesn't + return anything?

      + (Submitted by: Dave Astels) +

      +

      + Often if a method doesn't return a value, it will have some side + effect. Actually, if it doesn't return a value AND doesn't have + a side effect, it isn't doing anything. +

      +

      + There may be a way to verify that the side effect actually + occurred as expected. For example, consider + the add() method in the Collection classes. There + are ways of verifying that the side effect happened (i.e. the + object was added). You can check the size and assert that it is + what is expected: +

      +
      +    @Test
      +    public void testCollectionAdd() {
      +        Collection collection = new ArrayList();
      +        assertEquals(0, collection.size());
      +        collection.add("itemA");
      +        assertEquals(1, collection.size());
      +        collection.add("itemB");
      +        assertEquals(2, collection.size());
      +    }
      +

      + Another approach is to make use of MockObjects. +

      +

      + A related issue is to design for testing. For example, if you + have a method that is meant to output to a file, don't pass in a + filename, or even a FileWriter. Instead, pass in + a Writer. That way you can pass in + a StringWriter to capture the output for testing + purposes. Then you can add a method + (e.g. writeToFileNamed(String filename)) to + encapsulate the FileWriter creation. +

      + Under what conditions should I test get() + and set() methods?

      + Unit tests are intended to alleviate fear that something might + break. If you think a get() or set() + method could reasonably break, or has in fact contributed to a + defect, then by all means write a test. +

      +

      + In short, test until you're confident. What you choose to test + is subjective, based on your experiences and confidence level. + Remember to be practical and maximize your testing investment. +

      +

      + Refer also to "How simple is 'too simple to + break'?". +

      + Under what conditions should I not test + get() and set() methods?

      + (Submitted by: J. B. Rainsberger) +

      +

      + Most of the time, get/set methods just can't break, and if they + can't break, then why test them? While it is usually better to + test more, there is a definite curve of diminishing returns on + test effort versus "code coverage". Remember the maxim: "Test + until fear turns to boredom." +

      +

      + Assume that the getX() method only does "return x;" + and that the setX() method only does "this.x = + x;". If you write this test: +

      +
      @Test
      +public void testGetSetX() {
      +    setX(23);
      +    assertEquals(23, getX());
      +}
      +

      + then you are testing the equivalent of the following: +

      +
      +@Test
      +public void testGetSetX() {
      +    x = 23;
      +    assertEquals(23, x);
      +}
      +

      + or, if you prefer, +

      +
      @Test
      +public void testGetSetX() {
      +    assertEquals(23, 23);
      +}
      +

      + At this point, you are testing the Java compiler, or possibly + the interpreter, and not your component or application. There is + generally no need for you to do Java's testing for them. +

      +

      + If you are concerned about whether a property has already been + set at the point you wish to call getX(), then you + want to test the constructor, and not the getX() + method. This kind of test is especially useful if you have + multiple constructors: +

      +
      @Test
      +public void testCreate() {
      +    assertEquals(23, new MyClass(23).getX());
      +}
      +
      + How do I write a test that passes when an + expected exception is thrown?

      + Add the optional expected attribute to + the @Test annotation. The following is an example + test that passes when the + expected IndexOutOfBoundsException is raised: +

      +
      @Test(expected=IndexOutOfBoundsException.class)
      +public void testIndexOutOfBoundsException() {
      +    ArrayList emptyList = new ArrayList();
      +    Object o = emptyList.get(0);
      +}
      +
      + How do I write a test that fails when an + unexpected exception is thrown?

      + Declare the exception in the throws clause of the + test method and don't catch the exception within the test + method. Uncaught exceptions will cause the test to fail with an + error. +

      +

      + The following is an example test that fails when + the IndexOutOfBoundsException is raised: +

      +
      @Test
      +public void testIndexOutOfBoundsExceptionNotRaised() 
      +    throws IndexOutOfBoundsException {
      +
      +    ArrayList emptyList = new ArrayList();
      +    Object o = emptyList.get(0);
      +}
      + How do I test protected methods?

      + Place your tests in the same package as the classes under test. +

      +

      + Refer to "Where should I put my test + files?" for examples of how to organize tests for protected + method access. +

      + How do I test private methods?

      + Testing private methods may be an indication that those methods + should be moved into another class to promote reusability. +

      +

      + But if you must... +

      +

      + If you are using JDK 1.3 or higher, you can use reflection to + subvert the access control mechanism with the aid of + the PrivilegedAccessor. + For details on how to use it, + read this + article. +

      +

      + If you are using JDK 1.6 or higher and you annotate your tests with @Test, + you can use Dp4j to inject reflection in your + test methods. For details on how to use it, see + this test script. +

      + Why does JUnit only report the first + failure in a single test?

      + (Submitted by: J. B. Rainsberger) +

      +

      + Reporting multiple failures in a single test is generally a sign + that the test does too much, compared to what a unit test ought + to do. Usually this means either that the test is really a + functional/acceptance/customer test or, if it is a unit test, + then it is too big a unit test. +

      +

      + JUnit is designed to work best with a number of small tests. It + executes each test within a separate instance of the test + class. It reports failure on each test. Shared setup code is + most natural when sharing between tests. This is a design + decision that permeates JUnit, and when you decide to report + multiple failures per test, you begin to fight against + JUnit. This is not recommended. +

      +

      + Long tests are a design smell and indicate the likelihood of a + design problem. Kent Beck is fond of saying in this case that + "there is an opportunity to learn something about your design." + We would like to see a pattern language develop around these + problems, but it has not yet been written down. +

      +

      + Finally, note that a single test with multiple assertions is + isomorphic to a test case with multiple tests: +

      +

      + One test method, three assertions: +

      +
      public class MyTestCase {
      +    @Test
      +    public void testSomething() {
      +        // Set up for the test, manipulating local variables
      +        assertTrue(condition1);
      +        assertTrue(condition2);
      +        assertTrue(condition3);
      +    }
      +}
      +

      + Three test methods, one assertion each: +

      +
      +public class MyTestCase {
      +    // Local variables become instance variables
      +
      +    @Before
      +    public void setUp() {
      +        // Set up for the test, manipulating instance variables
      +    }
      +    
      +    @Test
      +    public void testCondition1() {
      +        assertTrue(condition1);
      +    }
      +
      +    @Test
      +    public void testCondition2() {
      +        assertTrue(condition2);
      +    }
      +
      +    @Test
      +    public void testCondition3() {
      +        assertTrue(condition3);
      +    }
      +}
      +

      + The resulting tests use JUnit's natural execution and reporting + mechanism and, failure in one test does not affect the execution + of the other tests. You generally want exactly one test to fail + for any given bug, if you can manage it. +

      + In Java 1.4, 'assert' is a + keyword. Won't this conflict with JUnit's assert() + method?

      + JUnit 3.7 deprecated assert() and replaced it + with assertTrue(), which works exactly the same + way. +

      +

      + JUnit 4 is compatible with the assert keyword. If + you run with the -ea JVM switch, assertions that + fail will be reported by JUnit. +

      + How do I test things that must be run in + a J2EE container (e.g. servlets, EJBs)?

      + Refactoring J2EE components to delegate functionality to other + objects that don't have to be run in a J2EE container will + improve the design and testability of the software. +

      +

      + Cactus + is an open source JUnit extension that can be used to test J2EE + components in their natural environment. +

      + Do I need to write a test class for + every class I need to test?

      + (Submitted by: J. B. Rainsberger) +

      +

      + No. It is a convention to start with one test + class per class under test, but it is not necessary. +

      +

      + Test classes only provide a way to organize tests, nothing more. + Generally you will start with one test class per class under + test, but then you may find that a small group of tests belong + together with their own common test fixture.[1] In this case, + you may move those tests to a new test class. This is a simple + object-oriented refactoring: separating responsibilities of an + object that does too much. +

      +

      + Another point to consider is that the TestSuite is + the smallest execution unit in JUnit: you cannot execute + anything smaller than a TestSuite at one time without changing + source code. In this case, you probably do not want to put tests + in the same test class unless they somehow "belong together". + If you have two groups of tests that you think you'd like to + execute separately from one another, it is wise to place them in + separate test classes. +

      +

      + + [1] A test fixture is a common set of test data and + collaborating objects shared by many tests. Generally they are + implemented as instance variables in the test class. + +

      + Is there a basic template I can use to + create a test?

      + (Submitted by: Eric Armstrong) +

      +

      + The following templates are a good starting point. Copy/paste + and edit these templates to suit your coding style. +

      +

      + SampleTest is a basic test template: +

      +
      import org.junit.*;
      +import static org.junit.Assert.*;
      +
      +public class SampleTest {
      +
      +    private java.util.List emptyList;
      +
      +    /**
      +     * Sets up the test fixture. 
      +     * (Called before every test case method.)
      +     */
      +    @Before
      +    public void setUp() {
      +        emptyList = new java.util.ArrayList();
      +    }
      +
      +    /**
      +     * Tears down the test fixture. 
      +     * (Called after every test case method.)
      +     */
      +    @After
      +    public void tearDown() {
      +        emptyList = null;
      +    }
      +    
      +    @Test
      +    public void testSomeBehavior() {
      +        assertEquals("Empty list should have 0 elements", 0, emptyList.size());
      +    }
      +
      +    @Test(expected=IndexOutOfBoundsException.class)
      +    public void testForException() {
      +        Object o = emptyList.get(0);
      +    }
      +}
      + How do I write a test for an abstract + class?

      + Refer to http://c2.com/cgi/wiki?AbstractTestCases. +

      + When are tests garbage collected?

      + (Submitted by: Timothy Wall and Kent Beck) +

      +

      + By design, the tree of Test instances is built in one pass, then + the tests are executed in a second pass. The test runner holds + strong references to all Test instances for the duration of the + test execution. This means that for a very long test run with + many Test instances, none of the tests may be garbage collected + until the end of the entire test run. +

      +

      + Therefore, if you allocate external or limited resources in a + test, you are responsible for freeing those resources. + Explicitly setting an object to null in + the tearDown() method, for example, allows it to be + garbage collected before the end of the entire test run. +

      +
      + + Organizing Tests + + Where should I put my test files? +

      + You can place your tests in the same package and directory as + the classes under test. +

      +

      + For example: +

      +
      src
      +   com
      +      xyz
      +         SomeClass.java
      +         SomeClassTest.java
      +

      + While adequate for small projects, many developers feel that + this approach clutters the source directory, and makes it hard + to package up client deliverables without also including + unwanted test code, or writing unnecessarily complex packaging + tasks. +

      +

      + An arguably better way is to place the tests in a separate + parallel directory structure with package alignment. +

      +

      + For example: +

      +
      src
      +   com
      +      xyz
      +         SomeClass.java
      +test
      +   com
      +      xyz
      +         SomeClassTest.java
      +

      + These approaches allow the tests to access to all the public and + package visible methods of the classes under test. +

      +

      + Some developers have argued in favor of putting the tests in a + sub-package of the classes under test (e.g. com.xyz.test). The + author of this FAQ sees no clear advantage to adopting this + approach and believes that said developers also put their curly + braces on the wrong line. :-) +

      +
      + + How can I run setUp() and tearDown() + code once for all of my tests? +

      + The desire to do this is usually a symptom of excessive coupling + in your design. If two or more tests must share the same test + fixture state, then the tests may be trying to tell you that the + classes under test have some undesirable dependencies. +

      +

      + Refactoring the design to further decouple the classes under + test and eliminate code duplication is usually a better + investment than setting up a shared test fixture. +

      +

      + But if you must... +

      +

      + You can add a @BeforeClass annotation to a method + to be run before all the tests in a class, and + a @AfterClass annotation to a method to be run + after all the tests in a class. Here's an example: +

      +
      package junitfaq;
      +
      +import org.junit.*;
      +import static org.junit.Assert.*;
      +import java.util.*;
      +
      +public class SimpleTest {
      +
      +    private Collection collection;
      +    
      +    @BeforeClass
      +    public static void oneTimeSetUp() {
      +        // one-time initialization code        
      +    }
      +
      +    @AfterClass
      +    public static void oneTimeTearDown() {
      +        // one-time cleanup code
      +    }
      +
      +    @Before
      +    public void setUp() {
      +        collection = new ArrayList();
      +    }
      +    
      +    @After
      +    public void tearDown() {
      +        collection.clear();
      +    }
      +
      +    @Test
      +    public void testEmptyCollection() {
      +        assertTrue(collection.isEmpty());
      +    }
      +    
      +    @Test
      +    public void testOneItemCollection() {
      +        collection.add("itemA");
      +        assertEquals(1, collection.size());
      +    }
      +}
      +

      + Given this test, the methods will execute in the following + order: +

      +
      oneTimeSetUp()
      +setUp()
      +testEmptyCollection()
      +tearDown()
      +setUp()
      +testOneItemCollection()
      +tearDown()
      +oneTimeTearDown()
      +
      +
      +
      + + Running Tests + + What CLASSPATH settings are needed to + run JUnit? +

      + (Submitted by: Eric Armstrong) +

      +

      + To run your JUnit tests, you'll need the following elemements in + your CLASSPATH: +

      +
        +
      • JUnit class files
      • +
      • Your class files, including your JUnit test classes
      • +
      • Libraries your class files depend on
      • +
      +

      + If attempting to run your tests results in + a NoClassDefFoundError, then something is missing + from your CLASSPATH. +

      +

      + Windows Example: +

      +
      set CLASSPATH=%JUNIT_HOME%\junit.jar;c:\myproject\classes;c:\myproject\lib\something.jar
      +

      + Unix (bash) Example: +

      +
      export CLASSPATH=$JUNIT_HOME/junit.jar:/myproject/classes:/myproject/lib/something.jar
      +
      +
      + + Why do I get + a NoClassDefFoundError when trying to test JUnit + or run the samples? +

      + (Submitted by: J.B. Rainsberger and Jason Rogers) +

      +

      + Most likely your CLASSPATH doesn't include the JUnit + installation directory. +

      +

      + Refer to "What CLASSPATH settings are + needed to run JUnit?" for more guidance. +

      +

      + Also consider running WhichJunit + to print the absolute location of the JUnit class files required + to run and test JUnit and its samples. +

      +

      + If the CLASSPATH seems mysterious, read this! +

      +
      + + How do I run JUnit from my command window? +

      + (Submitted by: Eric Armstrong) +

      +
        +
      1. +

        + Set your CLASSPATH +

        +
      2. +
      3. +

        + Invoke the runner: +

        +

        + + java org.junit.runner.JUnitCore <test class name> + +

        +
      4. +
      +
      + + How do I run JUnit using Ant? +

      + (Submitted by: Eric Armstrong) +

      +
        +
      1. +

        + Define any necessary Ant properties: +

        +
        <property name="src" value="./src" />
        +<property name="lib" value="./lib" />
        +<property name="classes" value="./classes" />
        +<property name="test.class.name" value="com.xyz.MyTestSuite" />
        +
      2. +
      3. +

        + Set up the CLASSPATH to be used by JUnit: +

        +
        <path id="test.classpath">
        +  <pathelement location="${classes}" />
        +  <pathelement location="/path/to/junit.jar" />
        +  <fileset dir="${lib}">
        +    <include name="**/*.jar"/>
        +  </fileset>
        +</path>
        +
      4. +
      5. +

        + Define the Ant task for running JUnit: +

        +
        <target name="test">
        +  <junit fork="yes" haltonfailure="yes">
        +    <test name="${test.class.name}" />
        +    <formatter type="plain" usefile="false" />
        +    <classpath refid="test.classpath" />
        +  </junit>
        +</target>
        +
      6. +
      7. +

        + Run the test: +

        +
        ant test
        +
      8. +
      +

      + Refer to the JUnit + Ant Task for more information. +

      +
      + + How do I use Ant to create HTML test + reports? +

      + (Submitted by: Eric Armstrong and Steffen Gemkow) +

      +
        +
      1. +

        + Ensure that Ant's optional.jar file is either + in your CLASSPATH or exists in + your $ANT_HOME/lib directory. +

        +
      2. +
      3. +

        + Add an ANT property for the directory containing the HTML reports: +

        +
        <property name="test.reports" value="./reports" />
        +
      4. +
      5. +

        + Define the Ant task for running JUnit and generating reports: +

        +
        <target name="test-html">
        +  <junit fork="yes" printsummary="no" haltonfailure="no">
        +    <batchtest fork="yes" todir="${test.reports}" >
        +      <fileset dir="${classes}">
        +        <include name="**/*Test.class" />
        +      </fileset>
        +    </batchtest>
        +    <formatter type="xml" />
        +    <classpath refid="test.classpath" />
        +  </junit>
        +
        +  <junitreport todir="${test.reports}">
        +    <fileset dir="${test.reports}">
        +      <include name="TEST-*.xml" />
        +    </fileset>
        +    <report todir="${test.reports}" />
        +  </junitreport>
        +</target>
        +
      6. +
      7. +

        + Run the test: +

        +
        + + ant test-html + +
        +
      8. +
      +

      + Refer to the + JUnit Ant Task + for more information. +

      +
      + + How do I pass command-line arguments + to a test execution? +

      + Use the -D JVM command-line options, as in: +

      +
      -DparameterName=parameterValue
      +

      + If the number of parameters on the command line gets unweildy, + pass in the location of a property file that defines a set of + parameters. Alternatively, the JUnit-addons package + contains the XMLPropertyManager + and PropertyManager classes that allow you to define a + property file (or XML file) containing test parameters. +

      +
      + + Why do I get + a LinkageError when using + XML interfaces in my test? +

      + (Submitted by: Scott Stirling) +

      +

      + The workaround as of JUnit 3.7 is to + add org.w3c.dom.* and org.xml.sax.* to + your excluded.properties. +

      +

      + It's just a matter of time before this fix becomes incorporated + into the released version of + JUnit's excluded.properties, since JAXP is a + standard part of JDK 1.4. It will be just like + excluding org.omg.*. By the way, if you download + the JUnit source from its Sourceforge CVS, you will find that + these patterns have already been added to the default + excluded.properties and so has a pattern for JINI. In fact, here + is the current version in CVS, which demonstrates how to add + exclusions to the list too: +

      +
      #
      +# The list of excluded package paths for the TestCaseClassLoader
      +#
      +excluded.0=sun.*
      +excluded.1=com.sun.*
      +excluded.2=org.omg.*
      +excluded.3=javax.*
      +excluded.4=sunw.*
      +excluded.5=java.*
      +excluded.6=org.w3c.dom.*
      +excluded.7=org.xml.sax.*
      +excluded.8=net.jini.*
      +

      + This is the most common case where the + default excluded.properties list needs + modification. The cause of the LinkageError is + related to using JAXP in your test cases. By JAXP I mean the + whole set of javax.xml.* classes and the + supporting org.w3c.dom.* + and org.xml.sax.* classes. +

      +

      + As stated above, the JUnit GUI TestRunners' classloader relies + on the excluded.properties for classes it should + delegate to the system classloader. JAXP is an unusual case + because it is a standard Java extension library dependent on + classes whose package names (org.w3c.dom.* + and org.xml.sax.*) do not begin with a standard + Java or Sun prefix. This is similar to the relationship + between javax.rmi.* and the org.omg.* + classes, which have been excluded by default in + JUnit'ss excluded.properties for a while. +

      +

      + What can happen, and frequently does when using the JUnit Swing + or AWT UI with test cases that reference, use or depend on JAXP + classes, such as Log4J, Apache SOAP, Axis, Cocoon, etc., is that + the JUnit class loader (properly) + delegates javax.xml.* classes it "sees" + to the system loader. But then the system loader, in the process + of initializing and loading that JAXP class, links and loads up + a bunch of org.w3c.dom/org.xml.sax + classes. When it does so, the JUnit custom classloader is not + involved at all because the system classloader never delegates + "down" or checks with custom classloaders to see if a + class is already loaded. At any point after this, if the JUnit + loader is asked to load + an org.w3c.dom/org.xml.sax class that + it's never seen before, it will try to load it because the + class' name doesn't match any of the patterns in the default + exclude list. That's when a LinkageError + occurs. This is really a flaw in the JUnit classloader design, + but there is the workaround given above. +

      +

      + Java 2 JVMs keep classes (remember, classes and objects, though + related, are different entities to the JVM - I'm talking + about classes here, not object instances) in namespaces, + identifying them by their fully qualified classname plus the + instance of their defining (not initiating) loader. The JVM will + attempt to assign all unloaded classes referenced by an already + defined and loaded class to that class's defining loader. The + JVM's classresolver routine (implemented as a C function in the + JVM source code) keeps track of all these class loading events + and "sees" if another classloader (such as the JUnit + custom loader) attempts to define a class that has already been + defined by the system loader. According to the rules of Java 2 + loader constraints, in case a class has already been defined by + the system loader, any attempts to load a class should first be + delegated to the system loader. A "proper" way for + JUnit to handle this feature would be to load classes from a + repository other than the CLASSPATH that the system classloader + knows nothing about. And then the JUnit custom classloader could + follow the standard Java 2 delegation model, which is to always + delegate class loading to the system loader, and only attempt to + load if that fails. Since they both load from the CLASSPATH in + the current model, if the JUnit loader delegated like it's + supposed to, it would never get to load any classes since the + system loader would always find them. +

      +

      + You could try to hack around this in the JUnit source by + catching the LinkageError in + TestCaseClassLoader's loadClass() method and then + making a recovery call to findSystemClass() -- + thereby delegating to the system loader after the violation has + been caught. But this hack only works some of the time, because + now you can have the reverse problem where the JUnit loader will + load a host of org.w3c.dom/org.xml.sax + classes, and then the system loader violates the loader + contraints at some point when it tries to do exactly what I + described above with JAXP because it doesn't ever delegate to + its logical child (the JUnit loader). Inevitably, if your test + cases use many JAXP and related XML classes, one or the other + classloader will end up violating the constraints whatever you + do. +

      +
      + + Why do I get the warning + "AssertionFailedError: No + tests found in XXX" when I run my test? +

      + Make sure you have more or more method annotated with @Test. +

      +

      + For example: +

      +
      @Test
      +public void testSomething() {
      +}
      +
      + + Why do I see "Unknown Source" in the + stack trace of +a test failure, rather than the source file's line number? +

      + The debug option for the Java compiler must be enabled in order + to see source file and line number information in a stack trace. +

      +

      + When invoking the Java compiler from the command line, use + the -g option to generate all debugging info. +

      +

      + When invoking the Java compiler from an + Ant task, use the + debug="on" attribute. For example: +

      +
      <javac srcdir="${src}" destdir="${build}" debug="on" />
      +

      + When using older JVMs pre-Hotspot (JDK 1.1 and most/all 1.2), + run JUnit with the -DJAVA_COMPILER=none JMV command + line argument to prevent runtime JIT compilation from obscuring + line number info. +

      +

      + Compiling the test source with debug enabled will show the line + where the assertion failed. Compiling the non-test source with + debug enabled will show the line where an exception was raised + in the class under test. +

      +
      + + How do I organize all test classes + in a TestSuite automatically and not use or manage a TestSuite + explicitly? +

      + (Submitted by: Bill de hora) +

      +

      + There are a number of ways to do this: +

      +
        +
      1. +

        + In Ant, use the junit task and + the batchtest element: +

        +
        +
        +<junit printsummary="yes" haltonfailure="yes">
        +  ...
        +  <batchtest fork="yes">
        +    <fileset dir="${src.dir}">
        +       <include name="**/*Test.java" />
        +       <include name="**/Test*.java" />
        +    </fileset>
        +  </batchtest>
        +</junit> 
        +          
        +
        +

        + Idiomatic naming patterns for unit tests + are Test*.java and *Test.java. + Documentation and examples are at http://ant.apache.org/manual/OptionalTasks/junit.html. +

        +
      2. +
      3. +

        + Use the DirectorySuiteBuilder + and ArchiveSuiteBuilder (for jar/zip files) + classes provided by JUnit-addons project: +

        +
        DirectorySuiteBuilder builder = new DirectorySuiteBuilder();
        +builder.setSuffix("Test");
        +Test suite = builer.suite("/home/project/myproject/tests");
        +

        + Documentation and examples are at http://junit-addons.sourceforge.net. +

        +
      4. +
      5. +

        + Write your own custom suite builder. +

        +

        + Have your test classes implement an interface and write a + treewalker to load each class in a directory, inspect the + class, and add any classes that implement the interface to a + TestSuite. +

        +

        + You might only want to do this if you are very + uncomfortable with using a naming convention for test + classes. Aside from being slow for larger suites, ultimately + it's arguable whether it's more effort to follow a naming + convention that have test classes implement an interface! +

        +

        + An example of this approach is at + http://www.javaworld.com/javaworld/jw-12-2000/jw-1221-junit_p.html. +

        +
      6. +
      +
      +
      +
      + + Best Practices + + When should tests be written? +

      + Tests should be written before the code. Test-first programming + is practiced by only writing new code when an automated test is + failing. +

      +

      + Good tests tell you how to best design the system for its + intended use. They effectively communicate in an executable + format how to use the software. They also prevent tendencies to + over-build the system based on speculation. When all the tests + pass, you know you're done! +

      +

      + Whenever a customer test fails or a bug is reported, first write + the necessary unit test(s) to expose the bug(s), then + fix them. This makes it almost impossible for that particular + bug to resurface later. +

      +

      + Test-driven development is a lot more fun than writing tests + after the code seems to be working. Give it a try! +

      +
      + + Do I have to write a test for + everything? +

      + No, just test everything that could reasonably break. +

      +

      + Be practical and maximize your testing investment. Remember + that investments in testing are equal investments in design. If + defects aren't being reported and your design responds well to + change, then you're probably testing enough. If you're spending + a lot of time fixing defects and your design is difficult to + grow, you should write more tests. +

      +

      + If something is difficult to test, it's usually an opportunity + for a design improvement. Look to improve the design so that + it's easier to test, and by doing so a better design will + usually emerge. +

      +
      + + How simple is 'too simple to break'? +

      + (Submitted by: J. B. Rainsberger) +

      +

      + The general philosophy is this: if it can't break on its + own, it's too simple to break. +

      +

      + First example is the getX() method. Suppose + the getX() method only answers the value of an + instance variable. In that case, getX() cannot + break unless either the compiler or the interpreter is also + broken. For that reason, don't test getX(); there + is no benefit. The same is true of the setX() + method, although if your setX() method does any + parameter validation or has any side effects, you likely need to + test it. +

      +

      + Next example: suppose you have written a method that does + nothing but forward parameters into a method called on another + object. That method is too simple to break. +

      +
      public void myMethod(final int a, final String b) {
      +    myCollaborator.anotherMethod(a, b);
      +}
      +

      + myMethod cannot possibly break because it does nothing: it + forwards its input to another object and that's all. +

      +

      + The only precondition for this method is "myCollaborator != + null", but that is generally the responsibility of the + constructor, and not of myMethod. If you are concerned, add a + test to verify that myCollaborator is always set to something + non-null by every constructor. +

      +

      + The only way myMethod could break would be + if myCollaborator.anotherMethod() were broken. In + that case, test myCollaborator, and not the current + class. +

      +

      + It is true that adding tests for even these simple methods + guards against the possibility that someone refactors and makes + the methods "not-so-simple" anymore. In that case, though, the + refactorer needs to be aware that the method is now complex + enough to break, and should write tests for it -- and preferably + before the refactoring. +

      +

      + Another example: suppose you have a JSP and, like a good + programmer, you have removed all business logic from it. All it + does is provide a layout for a number of JavaBeans and never + does anything that could change the value of any object. That + JSP is too simple to break, and since JSPs are notoriously + annoying to test, you should strive to make all your JSPs too + simple to break. +

      +

      + Here's the way testing goes: +

      +
      becomeTimidAndTestEverything
      +while writingTheSameThingOverAndOverAgain
      +    becomeMoreAggressive
      +    writeFewerTests
      +    writeTestsForMoreInterestingCases
      +    if getBurnedByStupidDefect
      +        feelStupid
      +        becomeTimidAndTestEverything
      +    end
      +end
      +

      + The loop, as you can see, never terminates. +

      +
      + + How often should I run my tests? +

      + Run all your unit tests as often as possible, ideally every time + the code is changed. Make sure all your unit tests always run + at 100%. Frequent testing gives you confidence that your + changes didn't break anything and generally lowers the stress of + programming in the dark. +

      +

      + For larger systems, you may just run specific test suites that + are relevant to the code you're working on. +

      +

      + Run all your acceptance, integration, stress, and unit tests at + least once per day (or night). +

      +

      + If you're using Eclipse, be sure to check out David Saff's + continuous + testing plug-in. +

      +
      + + What do I do when a defect is reported? +

      + Test-driven development generally lowers the defect density of + software. But we're all fallible, so sometimes a defect will + slip through. When this happens, write a failing test that + exposes the defect. When the test passes, you know the defect + is fixed! +

      +

      + Don't forget to use this as a learning opportunity. Perhaps the + defect could have been prevented by being more aggressive about + testing everything that could reasonably break. +

      +
      + + Why not just use System.out.println()? +

      + Inserting debug statements into code is a low-tech method for + debugging it. It usually requires that output be scanned + manually every time the program is run to ensure that the code + is doing what's expected. +

      +

      + It generally takes less time in the long run to codify + expectations in the form of an automated JUnit test that retains + its value over time. If it's difficult to write a test to + assert expectations, the tests may be telling you that shorter + and more cohesive methods would improve your design. +

      +
      + + Why not just use a debugger? +

      + Debuggers are commonly used to step through code and inspect + that the variables along the way contain the expected values. + But stepping through a program in a debugger is a manual process + that requires tedious visual inspections. In essence, the + debugging session is nothing more than a manual check of + expected vs. actual results. Moreover, every time the program + changes we must manually step back through the program in the + debugger to ensure that nothing broke. +

      +

      + It generally takes less time to codify expectations in the form + of an automated JUnit test that retains its value over time. If + it's difficult to write a test to assert expected values, the + tests may be telling you that shorter and more cohesive methods + would improve your design. +

      +
      +
      + + Miscellaneous + + How do I integrate JUnit with my IDE? +

      + The JUnit home page maintains a list of IDE integration + instructions. +

      +
      + + How do I launch a debugger when a test fails? +

      + Start the TestRunner under the debugger and + configure the debugger so that it catches + the junit.framework.AssertionFailedError. +

      +

      + How you configure this depends on the debugger you prefer to + use. Most Java debuggers provide support to stop the program + when a specific exception is raised. +

      +

      + Notice that this will only launch the debugger when an expected + failure occurs. +

      +
      + + Where can I find unit testing frameworks + similar to JUnit for other languages? +

      + XProgramming.com maintains a complete list of available xUnit testing + frameworks. +

      +
      +
      +
      diff --git a/src/site/markdown/cookbook.md b/src/site/markdown/cookbook.md new file mode 100644 index 000000000000..3c13c5c965df --- /dev/null +++ b/src/site/markdown/cookbook.md @@ -0,0 +1,127 @@ +Title: JUnit Cookbook +Author: Kent Beck, Erich Gamma + + +Here is a short cookbook showing you the steps you can follow in writing +and organizing your own tests using JUnit. + +## Simple Test Case + +How do you write testing code? + +The simplest way is as an expression in a debugger. You can change debug +expressions without recompiling, and you can wait to decide what to write +until you have seen the running objects. You can also write test expressions +as statements which print to the standard output stream. Both styles of +tests are limited because they require human judgment to analyze their +results. Also, they don't compose nicely- you can only execute one debug +expression at a time and a program with too many print statements causes +the dreaded "Scroll Blindness". + +JUnit tests do not require human judgment to interpret, and it is easy +to run many of them at the same time. When you need to test something, +here is what you do: + +1. Annotate a method with `@org.junit.Test` + +1. When you want to check a value, import `org.junit.Assert.*` statically, call `assertTrue()` and pass a boolean +that is true if the test succeeds + +For example, to test that the sum of two Moneys with the same currency +contains a value which is the sum of the values of the two Moneys, write: + + @Test + public void simpleAdd() { + Money m12CHF= new Money(12, "CHF"); + Money m14CHF= new Money(14, "CHF"); + Money expected= new Money(26, "CHF"); + Money result= m12CHF.add(m14CHF); + assertTrue(expected.equals(result)); + } + +If you want to write a test similar to one you have already written, write +a Fixture instead. + +## Fixture + +What if you have two or more tests that operate on the same or similar +sets of objects? + +Tests need to run against the background of a known set of objects. +This set of objects is called a test fixture. When you are writing tests +you will often find that you spend more time writing the code to set up +the fixture than you do in actually testing values. + +To some extent, you can make writing the fixture code easier by paying +careful attention to the constructors you write. However, a much bigger +savings comes from sharing fixture code. Often, you will be able to use +the same fixture for several different tests. Each case will send slightly +different messages or parameters to the fixture and will check for different +results. + +When you have a common fixture, here is what you do: + +1. Add a field for each part of the fixture +2. Annotate a method with `@org.junit.Before` and initialize the variables in that method +3. Annotate a method with `@org.junit.After` to release any permanent resources you allocated in `setUp` + +For example, to write several test cases that want to work with different +combinations of 12 Swiss Francs, 14 Swiss Francs, and 28 US Dollars, first +create a fixture: + + public class MoneyTest { + private Money f12CHF; + private Money f14CHF; + private Money f28USD; + + @Before public void setUp() { + f12CHF= new Money(12, "CHF"); + f14CHF= new Money(14, "CHF"); + f28USD= new Money(28, "USD"); + } + } + +Once you have the Fixture in place, you can write as many Test Cases as +you'd like. Add as many test methods (annotated with `@Test`) as you'd like. + +## Running Tests + +How do you run your tests and collect their results? + +Once you have tests, you'll want to run them. JUnit provides tools +to define the suite to be run and to display its results. To run tests and see the +results on the console, run this from a Java program: + + org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...); + +or this from the command line, with both your test class and junit on the classpath: + + java org.junit.runner.JUnitCore TestClass1.class [...other test classes...] + +You make your JUnit 4 test classes accessible to a TestRunner designed to work with earlier versions of JUnit, +declare a static method _suite_ +that returns a test. + + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(Example.class); + } + +## Expected Exceptions + +How do you verify that code throws exceptions as expected? + +Verifying that code completes normally is only part of programming. Making sure the code +behaves as expected in exceptional situations is part of the craft of programming too. For example: + + new ArrayList().get(0); + +This code should throw an `IndexOutOfBoundsException`. The `@Test` annotation has an optional parameter `expected` +that takes as values subclasses of `Throwable`. If we wanted to verify that `ArrayList` throws the correct exception, +we would write: + + @Test(expected= IndexOutOfBoundsException.class) + public void empty() { + new ArrayList().get(0); + } + +* * * diff --git a/src/site/resources/css/hopscotch-0.1.2.min.css b/src/site/resources/css/hopscotch-0.1.2.min.css new file mode 100644 index 000000000000..a8ebce9a65d6 --- /dev/null +++ b/src/site/resources/css/hopscotch-0.1.2.min.css @@ -0,0 +1,17 @@ +/**! +* +* Copyright 2013 LinkedIn Corp. All rights reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +.animated{-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-duration:1s;-moz-animation-duration:1s;-ms-animation-duration:1s;-o-animation-duration:1s;animation-duration:1s}@-webkit-keyframes fadeInUp{0%{opacity:0;-webkit-transform:translateY(20px)}100%{opacity:1;-webkit-transform:translateY(0)}}@-moz-keyframes fadeInUp{0%{opacity:0;-moz-transform:translateY(20px)}100%{opacity:1;-moz-transform:translateY(0)}}@-o-keyframes fadeInUp{0%{opacity:0;-o-transform:translateY(20px)}100%{opacity:1;-o-transform:translateY(0)}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.fade-in-up{-webkit-animation-name:fadeInUp;-moz-animation-name:fadeInUp;-o-animation-name:fadeInUp;animation-name:fadeInUp}@-webkit-keyframes fadeInDown{0%{opacity:0;-webkit-transform:translateY(-20px)}100%{opacity:1;-webkit-transform:translateY(0)}}@-moz-keyframes fadeInDown{0%{opacity:0;-moz-transform:translateY(-20px)}100%{opacity:1;-moz-transform:translateY(0)}}@-o-keyframes fadeInDown{0%{opacity:0;-ms-transform:translateY(-20px)}100%{opacity:1;-ms-transform:translateY(0)}}@keyframes fadeInDown{0%{opacity:0;transform:translateY(-20px)}100%{opacity:1;transform:translateY(0)}}.fade-in-down{-webkit-animation-name:fadeInDown;-moz-animation-name:fadeInDown;-o-animation-name:fadeInDown;animation-name:fadeInDown}@-webkit-keyframes fadeInRight{0%{opacity:0;-webkit-transform:translateX(-20px)}100%{opacity:1;-webkit-transform:translateX(0)}}@-moz-keyframes fadeInRight{0%{opacity:0;-moz-transform:translateX(-20px)}100%{opacity:1;-moz-transform:translateX(0)}}@-o-keyframes fadeInRight{0%{opacity:0;-o-transform:translateX(-20px)}100%{opacity:1;-o-transform:translateX(0)}}@keyframes fadeInRight{0%{opacity:0;transform:translateX(-20px)}100%{opacity:1;transform:translateX(0)}}.fade-in-right{-webkit-animation-name:fadeInRight;-moz-animation-name:fadeInRight;-o-animation-name:fadeInRight;animation-name:fadeInRight}@-webkit-keyframes fadeInLeft{0%{opacity:0;-webkit-transform:translateX(20px)}100%{opacity:1;-webkit-transform:translateX(0)}}@-moz-keyframes fadeInLeft{0%{opacity:0;-moz-transform:translateX(20px)}100%{opacity:1;-moz-transform:translateX(0)}}@-o-keyframes fadeInLeft{0%{opacity:0;-o-transform:translateX(20px)}100%{opacity:1;-o-transform:translateX(0)}}@keyframes fadeInLeft{0%{opacity:0;transform:translateX(20px)}100%{opacity:1;transform:translateX(0)}}.fade-in-left{-webkit-animation-name:fadeInLeft;-moz-animation-name:fadeInLeft;-o-animation-name:fadeInLeft;animation-name:fadeInLeft}div.hopscotch-bubble .hopscotch-nav-button{font-weight:bold;border-width:1px;border-style:solid;cursor:pointer;margin:0;overflow:visible;text-decoration:none!important;width:auto;padding:0 10px;height:26px;line-height:24px;font-size:12px;*zoom:1;white-space:nowrap;display:-moz-inline-stack;display:inline-block;*vertical-align:auto;zoom:1;*display:inline;vertical-align:middle;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}div.hopscotch-bubble .hopscotch-nav-button:hover{*zoom:1;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.25);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.25);box-shadow:0 1px 3px rgba(0,0,0,0.25)}div.hopscotch-bubble .hopscotch-nav-button:active{-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.25) inset;-moz-box-shadow:0 1px 2px rgba(0,0,0,0.25) inset;box-shadow:0 1px 2px rgba(0,0,0,0.25) inset}div.hopscotch-bubble .hopscotch-nav-button.next{border-color:#1b5480;color:#fff;margin:0 0 0 10px;text-shadow:0 1px 1px rgba(0,0,0,0.35);background-color:#287bbc;filter:progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr='#287bbc',endColorstr='#23639a');background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(0%,#287bbc),color-stop(100%,#23639a));background-image:-webkit-linear-gradient(top,#287bbc 0,#23639a 100%);background-image:-moz-linear-gradient(top,#287bbc 0,#23639a 100%);background-image:-o-linear-gradient(top,#287bbc 0,#23639a 100%);background-image:linear-gradient(top,#287bbc 0,#23639a 100%)}div.hopscotch-bubble .hopscotch-nav-button.next:hover{background-color:#2672ae;filter:progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr='#2672ae',endColorstr='#1e4f7e');background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(0%,#2672ae),color-stop(100%,#1e4f7e));background-image:-webkit-linear-gradient(top,#2672ae 0,#1e4f7e 100%);background-image:-moz-linear-gradient(top,#2672ae 0,#1e4f7e 100%);background-image:-o-linear-gradient(top,#2672ae 0,#1e4f7e 100%);background-image:linear-gradient(top,#2672ae 0,#1e4f7e 100%)}div.hopscotch-bubble .hopscotch-nav-button.prev{border-color:#a7a7a7;color:#444;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f2f2f2;filter:progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr='#f2f2f2',endColorstr='#e9e9e9');background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(0%,#f2f2f2),color-stop(100%,#e9e9e9));background-image:-webkit-linear-gradient(top,#f2f2f2 0,#e9e9e9 100%);background-image:-moz-linear-gradient(top,#f2f2f2 0,#e9e9e9 100%);background-image:-o-linear-gradient(top,#f2f2f2 0,#e9e9e9 100%);background-image:linear-gradient(top,#f2f2f2 0,#e9e9e9 100%)}div.hopscotch-bubble .hopscotch-nav-button.prev:hover{background-color:#e8e8e8;filter:progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr='#FFE8E8E8',endColorstr='#FFA9A9A9');background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(0%,#e8e8e8),color-stop(13%,#e3e3e3),color-stop(32%,#d7d7d7),color-stop(71%,#b9b9b9),color-stop(100%,#a9a9a9));background-image:-webkit-linear-gradient(top,#e8e8e8 0,#e3e3e3 13%,#d7d7d7 32%,#b9b9b9 71%,#a9a9a9 100%);background-image:-moz-linear-gradient(top,#e8e8e8 0,#e3e3e3 13%,#d7d7d7 32%,#b9b9b9 71%,#a9a9a9 100%);background-image:-o-linear-gradient(top,#e8e8e8 0,#e3e3e3 13%,#d7d7d7 32%,#b9b9b9 71%,#a9a9a9 100%);background-image:linear-gradient(top,#e8e8e8 0,#e3e3e3 13%,#d7d7d7 32%,#b9b9b9 71%,#a9a9a9 100%)}div.hopscotch-bubble{background-color:#fff;border:5px solid #000;border:5px solid rgba(0,0,0,0.5);color:#333;font-family:Helvetica,Arial;font-size:13px;position:absolute;z-index:999999;-moz-background-clip:padding;-webkit-background-clip:padding;background-clip:padding-box}div.hopscotch-bubble.animate{-moz-transition-property:top,left;-moz-transition-duration:1s;-moz-transition-timing-function:ease-in-out;-ms-transition-property:top,left;-ms-transition-duration:1s;-ms-transition-timing-function:ease-in-out;-o-transition-property:top,left;-o-transition-duration:1s;-o-transition-timing-function:ease-in-out;-webkit-transition-property:top,left;-webkit-transition-duration:1s;-webkit-transition-timing-function:ease-in-out;transition-property:top,left;transition-duration:1s;transition-timing-function:ease-in-out}div.hopscotch-bubble.invisible{opacity:0}div.hopscotch-bubble.hide,div.hopscotch-bubble .hide,div.hopscotch-bubble .hide-all{display:none}div.hopscotch-bubble h3{color:#000;font-family:Helvetica,Arial;font-size:16px;font-weight:bold;line-height:19px;margin:-1px 15px 0 0;padding:0}div.hopscotch-bubble .hopscotch-bubble-container{padding:15px;position:relative;text-align:left;-webkit-font-smoothing:antialiased}div.hopscotch-bubble .hopscotch-content{font-family:Helvetica,Arial;font-weight:normal;line-height:17px;margin:-5px 0 11px;padding-top:8px}div.hopscotch-bubble .hopscotch-bubble-content{margin:0 0 0 40px}div.hopscotch-bubble.no-number .hopscotch-bubble-content{margin:0}div.hopscotch-bubble .hopscotch-bubble-close{color:#000;background:transparent url(../img/sprite-green-0.3.png) -192px -92px no-repeat;display:block;padding:8px;position:absolute;text-decoration:none;text-indent:-9999px;width:8px;height:8px;top:0;right:0}div.hopscotch-bubble .hopscotch-bubble-close.hide,div.hopscotch-bubble .hopscotch-bubble-close.hide-all{display:none}div.hopscotch-bubble .hopscotch-bubble-number{background:transparent url(../img/sprite-green-0.3.png) 0 0 no-repeat;color:#fff;display:block;float:left;font-size:17px;font-weight:bold;line-height:31px;padding:0 10px 0 0;text-align:center;width:30px;height:30px}div.hopscotch-bubble .hopscotch-bubble-arrow-container{position:absolute;width:34px;height:34px}div.hopscotch-bubble .hopscotch-bubble-arrow-container .hopscotch-bubble-arrow,div.hopscotch-bubble .hopscotch-bubble-arrow-container .hopscotch-bubble-arrow-border{width:0;height:0}div.hopscotch-bubble .hopscotch-bubble-arrow-container.up{top:-22px;left:10px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.up .hopscotch-bubble-arrow{border-bottom:17px solid #fff;border-left:17px solid transparent;border-right:17px solid transparent;position:relative;top:-10px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.up .hopscotch-bubble-arrow-border{border-bottom:17px solid #000;border-bottom:17px solid rgba(0,0,0,0.5);border-left:17px solid transparent;border-right:17px solid transparent}div.hopscotch-bubble .hopscotch-bubble-arrow-container.down{bottom:-39px;left:10px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.down .hopscotch-bubble-arrow{border-top:17px solid #fff;border-left:17px solid transparent;border-right:17px solid transparent;position:relative;top:-24px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.down .hopscotch-bubble-arrow-border{border-top:17px solid #000;border-top:17px solid rgba(0,0,0,0.5);border-left:17px solid transparent;border-right:17px solid transparent}div.hopscotch-bubble .hopscotch-bubble-arrow-container.left{top:10px;left:-22px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.left .hopscotch-bubble-arrow{border-bottom:17px solid transparent;border-right:17px solid #fff;border-top:17px solid transparent;position:relative;left:7px;top:-34px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.left .hopscotch-bubble-arrow-border{border-right:17px solid #000;border-right:17px solid rgba(0,0,0,0.5);border-bottom:17px solid transparent;border-top:17px solid transparent}div.hopscotch-bubble .hopscotch-bubble-arrow-container.right{top:10px;right:-39px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.right .hopscotch-bubble-arrow{border-bottom:17px solid transparent;border-left:17px solid #fff;border-top:17px solid transparent;position:relative;left:-7px;top:-34px}div.hopscotch-bubble .hopscotch-bubble-arrow-container.right .hopscotch-bubble-arrow-border{border-left:17px solid #000;border-left:17px solid rgba(0,0,0,0.5);border-bottom:17px solid transparent;border-top:17px solid transparent}div.hopscotch-bubble .hopscotch-actions{margin:10px 0 0;text-align:right} \ No newline at end of file diff --git a/src/site/resources/css/plain-links.css b/src/site/resources/css/plain-links.css new file mode 100644 index 000000000000..2e876c410587 --- /dev/null +++ b/src/site/resources/css/plain-links.css @@ -0,0 +1,4 @@ +a.externalLink { + background: none !important; + padding-right: 0 !important; +} \ No newline at end of file diff --git a/src/site/resources/images/junit-logo.png b/src/site/resources/images/junit-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..9b514f3b3cfe9e835f23d8231a7924cbfbdaa274 GIT binary patch literal 3057 zcmV002M;1^@s6or`?000004b3#c}2nYxW zd-dOT z@G+p`;EdXUwPUOGG1@7E>DW$vOx5uXSanparYez^inQXRfJinV2&Lewz6Ps^Rv~1Q zy}$l(H*wi)cF%5hU6b6;%pLZg{hi-e)CPnMY(fVNDJh`? zhLn`h0YgekSuvH5pIK3lX=pLqK=yu9ee91#Z6l;;6x9KdrU11?Z3Ax+5ISHVB^-i7 zN=i|CK=WB85l<;D2ZjMV<*D{d;5}e#&8H!vr96`tdNGs;jZ4cCAg>BY;JG$^kquwfQEeya+KAVou7T!TX1SIY!bYk zO~!}sQGoV+_)Bkf^mW2na7alhX%Cn$?eJ_FM3ahkjKEAIW+u2H-B*G;N0@zG(DwQX{m}tSwn$xV zHXnE+rFd&QJWvXI`U3sY0ZYxAl>2wanEkILmh=Ha2P`mxcT$Q{??aLZ9k9Uo@NP=c zhb1wjj}SUwf$=({bP^cdqJc`z8`99Ibajh#NU3cJ9dLjVl_qoqz4UDct6QXBmC~Nj z0S6cc*Ac{I0?6R%C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0ds`5(YGz)Dr&$}kO*tV3xy*TcGYH)58=B<))UKd;` zZQmk2LHEFmFDim?q<)PugyvfiHM6d#?>ljFzP#u z2A>G#azvM5Hubrmw5D!%mX#ySHYX+ot|4Kk#$au;bloCphit+v(jigl_wBIWg5ZE; zV!$~^m=$y({yReI&R=_`6Iv$iLoiBaT?=-O2YhZy+njMTD=rp#n80y|`eMoW8I`wD z7Q3(Mk{({3Cz#l%NbJkX%aHv6m-nTnYn!IDJ(5+f2Wrh0MWqSAp9ms>v$4D2=0R{% zRC?WDabgW`qhN@^J_OeYdOqFB1ea6?iQhSs%i9beA}QTZE^k8edgQPmt}yvNZN!rY zR|92&r?ctI`K-9JW>s8dru*6UFT6>{eMIzH2lj4zMeN=AlWp_qcd4?hvSNP^)tT&4 zf`G7p$ zODI@eZFa0fy>f#8SY2zd29s*dQlInF)jfb+-C41@ZRS%~S!=I!WnihacUch8dm)fEnI=bG zGPt7_=4PAiL03|ebIy#x6}4t}Lsw7!PuIGF$<=0$HA<0T?$5%VTw7yyTe>e+O54Za zLBV-F)Lkn$ui9*-lbyXiuC<{-UQ1QwnI=0=#tFbsr;5fqz+w|~YCeuV`)!^9oEU~q z5u5}ZmpHN0B{1SEU + + + + + + + + image/svg+xml + + + + + + + JUnit + diff --git a/src/site/resources/scripts/hopscotch-0.1.2.min.js b/src/site/resources/scripts/hopscotch-0.1.2.min.js new file mode 100644 index 000000000000..1d149d837571 --- /dev/null +++ b/src/site/resources/scripts/hopscotch-0.1.2.min.js @@ -0,0 +1,17 @@ +/**! +* +* Copyright 2013 LinkedIn Corp. All rights reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +!function(a,b){var c,d,e,f,g,h,i,j,k,l,m=window.Sizzle||null,n=a[b],o="undefined",p=!1,q=typeof window.jQuery!==o,r=!1,s=window.document;try{r=typeof window.sessionStorage!==o}catch(t){}l={smoothScroll:!0,scrollDuration:1e3,scrollTopMargin:200,showCloseButton:!0,showPrevButton:!1,showNextButton:!0,bubbleWidth:280,bubblePadding:15,arrowWidth:20,skipIfNoElement:!0,cookieName:"hopscotch.tour.state"},n||(Array.isArray||(Array.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)}),k=function(){p&&n.startTour()},h={addClass:function(a,b){var c,d,e,f;if(a.className){for(d=b.split(/\s+/),c=" "+a.className+" ",e=0,f=d.length;f>e;++e)c.indexOf(" "+d[e]+" ")<0&&(c+=d[e]+" ");a.className=c.replace(/^\s+|\s+$/g,"")}else a.className=b},removeClass:function(a,b){var c,d,e,f;for(d=b.split(/\s+/),c=" "+a.className+" ",e=0,f=d.length;f>e;++e)c=c.replace(" "+d[e]+" "," ");a.className=c.replace(/^\s+|\s+$/g,"")},getPixelValue:function(a){var b=typeof a;return"number"===b?a:"string"===b?parseInt(a,10):0},valOrDefault:function(a,b){return typeof a!==o?a:b},invokeCallbackArrayHelper:function(a){var b;return Array.isArray(a)&&(b=j[a[0]],"function"==typeof b)?b.apply(this,a.slice(1)):void 0},invokeCallbackArray:function(a){var b,c;if(Array.isArray(a)){if("string"==typeof a[0])return h.invokeCallbackArrayHelper(a);for(b=0,c=a.length;c>b;++b)h.invokeCallback(a[b])}},invokeCallback:function(a){return"function"==typeof a?a():"string"==typeof a&&j[a]?j[a]():h.invokeCallbackArray(a)},invokeEventCallbacks:function(a,b){var c,d,e=i[a];if(b)return this.invokeCallback(b);for(c=0,d=e.length;d>c;++c)this.invokeCallback(e[c].cb)},getScrollTop:function(){var a;return a=typeof window.pageYOffset!==o?window.pageYOffset:s.documentElement.scrollTop},getScrollLeft:function(){var a;return a=typeof window.pageXOffset!==o?window.pageXOffset:s.documentElement.scrollLeft},getWindowHeight:function(){return window.innerHeight||s.documentElement.clientHeight},getWindowWidth:function(){return window.innerWidth||s.documentElement.clientWidth},addEvtListener:function(a,b,c){return a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent("on"+b,c)},removeEvtListener:function(a,b,c){return a.removeEventListener?a.removeEventListener(b,c,!1):a.detachEvent("on"+b,c)},documentIsReady:function(){return"complete"===s.readyState||"interactive"===s.readyState},evtPreventDefault:function(a){a.preventDefault?a.preventDefault():event&&(event.returnValue=!1)},extend:function(a,b){var c;for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c])},getStepTargetHelper:function(a){var b;return/^[#\.]/.test(a)?s.querySelector?s.querySelector(a):q?(b=jQuery(a),b.length?b[0]:null):m?(b=new m(a),b.length?b[0]:null):/^#[a-zA-Z][\w-_:.]*$/.test(a)?s.getElementById(a.substring(1)):null:s.getElementById(a)},getStepTarget:function(a){var b;if(!a||!a.target)return null;if("string"==typeof a.target)return a.target=h.getStepTargetHelper(a.target),a.target;if(Array.isArray(a.target)){var c,d;for(c=0,d=a.target.length;d>c;c++)if("string"==typeof a.target[c]&&(b=h.getStepTargetHelper(a.target[c])))return a.target=b,b;return null}return a.target},getI18NString:function(a){return g[a]||f[a]},setState:function(a,b,c){var d,e="";r?sessionStorage.setItem(a,b):(c&&(d=new Date,d.setTime(d.getTime()+24*c*60*60*1e3),e="; expires="+d.toGMTString()),s.cookie=a+"="+b+e+"; path=/")},getState:function(a){var b,c,d,e=a+"=",f=s.cookie.split(";");if(r)d=sessionStorage.getItem(a);else for(b=0;b=0?" prev":" next",h.addClass(c,d),c},setPosition:function(a){var b,c,d,e,f,g,i,j=6,k=h.getStepTarget(a),l=this.element,m=this.arrowEl;b=h.getPixelValue(a.width)||this.opt.bubbleWidth,d=h.valOrDefault(a.padding,this.opt.bubblePadding),h.removeClass(l,"fade-in-down fade-in-up fade-in-left fade-in-right"),!a.placement&&a.orientation&&(a.placement=a.orientation),e=k.getBoundingClientRect(),"top"===a.placement?(c=l.offsetHeight,f=e.top-c-this.opt.arrowWidth,g=e.left):"bottom"===a.placement?(f=e.bottom+this.opt.arrowWidth,g=e.left):"left"===a.placement?(f=e.top,g=e.left-b-2*d-2*j-this.opt.arrowWidth):"right"===a.placement&&(f=e.top,g=e.right+this.opt.arrowWidth),i="center"!==a.arrowOffset?h.getPixelValue(a.arrowOffset):a.arrowOffset,i?"top"===a.placement||"bottom"===a.placement?(m.style.top="",m.style.left="center"===i?b/2+d-m.offsetWidth/2+"px":i+"px"):("left"===a.placement||"right"===a.placement)&&(m.style.left="","center"===i?(c=c||l.offsetHeight,m.style.top=c/2+d-m.offsetHeight/2+"px"):m.style.top=i+"px"):(m.style.top="",m.style.left=""),"center"===a.xOffset?g=e.left+k.offsetWidth/2-b/2-d:g+=h.getPixelValue(a.xOffset),"center"===a.yOffset?(c=c||l.offsetHeight,f=e.top+k.offsetHeight/2-c/2-d):f+=h.getPixelValue(a.yOffset),a.fixedElement||(f+=h.getScrollTop(),g+=h.getScrollLeft()),l.style.position=a.fixedElement?"fixed":"absolute",l.style.top=f+"px",l.style.left=g+"px"},_initNavButtons:function(){var a=s.createElement("div");return this.prevBtnEl=this._createButton("hopscotch-prev",h.getI18NString("prevBtn")),this.nextBtnEl=this._createButton("hopscotch-next",h.getI18NString("nextBtn")),this.doneBtnEl=this._createButton("hopscotch-done",h.getI18NString("doneBtn")),this.ctaBtnEl=this._createButton("hopscotch-cta"),h.addClass(this.doneBtnEl,"hide"),a.appendChild(this.prevBtnEl),a.appendChild(this.ctaBtnEl),a.appendChild(this.nextBtnEl),a.appendChild(this.doneBtnEl),h.addEvtListener(this.prevBtnEl,"click",function(){n.prevStep(!0)}),h.addEvtListener(this.nextBtnEl,"click",function(){n.nextStep(!0)}),h.addEvtListener(this.doneBtnEl,"click",function(){n.endTour()}),a.className="hopscotch-actions",this.buttonsEl=a,this.containerEl.appendChild(a),this},_getCloseFn:function(){var a=this;return this.closeFn||(this.closeFn=function(b){a.opt.onClose&&h.invokeCallback(a.opt.onClose),a.opt.id&&!a.opt.isTourBubble?n.getCalloutManager().removeCallout(a.opt.id):a.destroy(),h.evtPreventDefault(b)}),this.closeFn},initCloseButton:function(){var a=s.createElement("a");return a.className="hopscotch-bubble-close",a.href="#",a.title=h.getI18NString("closeTooltip"),a.innerHTML=h.getI18NString("closeTooltip"),this.opt.isTourBubble?h.addEvtListener(a,"click",function(a){var b=n.getCurrStepNum(),c=n.getCurrTour(),d=b===c.steps.length-1;h.invokeEventCallbacks("close"),n.endTour(!0,d),a.preventDefault?a.preventDefault():event&&(event.returnValue=!1)}):h.addEvtListener(a,"click",this._getCloseFn()),h.valOrDefault(this.opt.showCloseButton,!0)||h.addClass(a,"hide"),this.closeBtnEl=a,this.containerEl.appendChild(a),this},_initArrow:function(){var a,b;return this.arrowEl=s.createElement("div"),this.arrowEl.className="hopscotch-bubble-arrow-container",b=s.createElement("div"),b.className="hopscotch-bubble-arrow-border",a=s.createElement("div"),a.className="hopscotch-bubble-arrow",this.arrowEl.appendChild(b),this.arrowEl.appendChild(a),this.element.appendChild(this.arrowEl),this},_setupCTAButton:function(a){var b=this;this._showButton(this.ctaBtnEl,!!a.showCTAButton),a.showCTAButton&&a.ctaLabel&&(this.ctaBtnEl.innerHTML=a.ctaLabel,this._ctaFn=function(){b.opt.isTourBubble||n.getCalloutManager().removeCallout(a.id),a.onCTA&&"function"==typeof a.onCTA&&a.onCTA()},h.addEvtListener(this.ctaBtnEl,"click",this._ctaFn))},_removeCTACallback:function(){this.ctaBtnEl&&this._ctaFn&&(h.removeEvtListener(this.ctaBtnEl,"click",this._ctaFn),this._ctaFn=null)},render:function(a,b,c,d){var e,f,g,i,j=this.element;return a?this.currStep=a:this.currStep&&(a=this.currStep),!a.placement&&a.orientation&&(a.placement=a.orientation),e=h.valOrDefault(a.showNextButton,this.opt.showNextButton),f=h.valOrDefault(a.showPrevButton,this.opt.showPrevButton),this.setTitle(a.title||""),this.setContent(a.content||""),this.opt.isTourBubble&&this.setNum(b),this.placement=a.placement,this.showPrevButton(this.prevBtnEl&&f&&b>0),this.showNextButton(this.nextBtnEl&&e&&!c),this.nextBtnEl.innerHTML=a.showSkip?h.getI18NString("skipBtn"):h.getI18NString("nextBtn"),c?h.removeClass(this.doneBtnEl,"hide"):h.addClass(this.doneBtnEl,"hide"),this._setupCTAButton(a),this._setArrow(a.placement),g=h.getPixelValue(a.width)||this.opt.bubbleWidth,i=h.valOrDefault(a.padding,this.opt.bubblePadding),this.containerEl.style.width=g+"px",this.containerEl.style.padding=i+"px",j.style.zIndex=a.zindex||"","top"===a.placement?(j.style.top="-9999px",j.style.left="-9999px",h.removeClass(j,"hide"),this.setPosition(a),h.addClass(j,"hide")):this.setPosition(a),d&&d(!a.fixedElement),this},setTitle:function(a){return a?(this.titleEl.innerHTML=a,h.removeClass(this.titleEl,"hide")):h.addClass(this.titleEl,"hide"),this},setContent:function(a){return a?(this.contentEl.innerHTML=a,h.removeClass(this.contentEl,"hide")):h.addClass(this.contentEl,"hide"),this},setNum:function(a){var b=h.getI18NString("stepNums");b&&am||m>=k.steps.length?null:k.steps[m]},y=function(){u.nextStep()},z=function(a){var b,c,d,e,f,g,i=v(),j=i.element,k=h.getPixelValue(j.style.top),l=k+h.getPixelValue(j.offsetHeight),m=h.getStepTarget(x()),n=m.getBoundingClientRect(),p=n.top+h.getScrollTop(),r=n.bottom+h.getScrollTop(),t=p>k?k:p,u=l>r?l:r,y=h.getScrollTop(),z=y+h.getWindowHeight(),A=t-w("scrollTopMargin");t>=y&&(t<=y+w("scrollTopMargin")||z>=u)?a&&a():w("smoothScroll")?typeof YAHOO!==o&&typeof YAHOO.env!==o&&typeof YAHOO.env.ua!==o&&typeof YAHOO.util!==o&&typeof YAHOO.util.Scroll!==o?(b=YAHOO.env.ua.webkit?s.body:s.documentElement,d=YAHOO.util.Easing?YAHOO.util.Easing.easeOut:void 0,c=new YAHOO.util.Scroll(b,{scroll:{to:[0,A]}},w("scrollDuration")/1e3,d),c.onComplete.subscribe(a),c.animate()):q?jQuery("body, html").animate({scrollTop:A},w("scrollDuration"),a):(0>A&&(A=0),e=y>t?-1:1,f=Math.abs(y-A)/(w("scrollDuration")/10),g=function(){var b=h.getScrollTop(),c=b+e*f;return e>0&&c>=A||0>e&&A>=c?(c=A,a&&a(),window.scrollTo(0,c),void 0):(window.scrollTo(0,c),h.getScrollTop()===b?(a&&a(),void 0):(setTimeout(g,10),void 0))},g()):(window.scrollTo(0,A),a&&a())},A=function(a,b){var c,d,e;m+a>=0&&m+a0?d.multipage:m>0&&k.steps[m-1].multipage,f=function(c){var f;if(-1===c)return this.endTour(!0);if(a&&(f=b>0?h.invokeEventCallbacks("next",d.onNext):h.invokeEventCallbacks("prev",d.onPrev)),c===m){if(e)return h.setState(w("cookieName"),k.id+":"+m,1),void 0;f=h.valOrDefault(f,!0),f?this.showStep(c):this.endTour(!1)}},!e&&w("skipIfNoElement"))A(b,function(a){f.call(i,a)});else if(m+b>=0&&m+b=k.steps.length)throw"Specified step number out of bounds.";m=b}return h.documentIsReady()?(m||k.id!==n||typeof r===o?m||(m=0):m=r,D(m,function(a){var b=-1!==a&&h.getStepTarget(k.steps[a]);return b?(h.invokeEventCallbacks("start"),c=v(),c.hide(!1),d.isActive=!0,h.getStepTarget(x())?d.showStep(a):(h.invokeEventCallbacks("error"),w("skipIfNoElement")&&d.nextStep(!1)),void 0):(d.endTour(!1,!1),void 0)}),this):(p=!0,this)},this.showStep=function(a){var b=k.steps[a];return b.delay?setTimeout(function(){E(a)},b.delay):E(a),this},this.prevStep=function(a){return B.call(this,a,-1),this},this.nextStep=function(a){var b=x(),c=h.getStepTarget(b);return b.nextOnTargetClick&&h.removeEvtListener(c,"click",y),B.call(this,a,1),this},this.endTour=function(a,b){var c=v();return a=h.valOrDefault(a,!0),b=h.valOrDefault(b,!0),m=0,r=void 0,c.hide(),a&&h.clearState(w("cookieName")),this.isActive&&(this.isActive=!1,k&&b&&h.invokeEventCallbacks("end")),this.removeCallbacks(null,!0),this.resetDefaultOptions(),k=null,this},this.getCurrTour=function(){return k},this.getCurrTarget=function(){return h.getStepTarget(x())},this.getCurrStepNum=function(){return m},this.listen=function(a,b,c){return a&&i[a].push({cb:b,fromTour:c}),this},this.unlisten=function(a,b){var c,d,e=i[a];for(c=0,d=e.length;d>c;++c)e[c]===b&&e.splice(c,1);return this},this.removeCallbacks=function(a,b){var c,d,e,f;for(f in i)if(!a||a===f)if(b)for(c=i[f],d=0,e=c.length;e>d;++d)c[d].fromTour&&(c.splice(d--,1),--e);else i[f]=[];return this},this.registerHelper=function(a,b){"string"==typeof a&&"function"==typeof b&&(j[a]=b)},this.unregisterHelper=function(a){j[a]=null},this.invokeHelper=function(a){var b,c,d=[];for(b=1,c=arguments.length;c>b;++b)d.push(arguments[b]);j[a]&&j[a].call(null,d)},this.setCookieName=function(a){return f.cookieName=a,this},this.resetDefaultOptions=function(){return f={},this},this.resetDefaultI18N=function(){return g={},this},this.getState=function(){return h.getState(w("cookieName"))},t=function(a,b){var c,d,e,i,j=["next","prev","start","end","show","error","close"];for(f||this.resetDefaultOptions(),h.extend(f,a),a&&h.extend(g,a.i18n),e=0,i=j.length;i>e;++e)d="on"+j[e].charAt(0).toUpperCase()+j[e].substring(1),a[d]&&this.listen(j[e],a[d],b);return c=v(!0),this},this.configure=function(a){return t.call(this,a,!1)},F.call(this,a)},n=new c,a[b]=n)}(window,"hopscotch"); diff --git a/src/site/resources/scripts/index.js b/src/site/resources/scripts/index.js new file mode 100644 index 000000000000..9e1486ec601c --- /dev/null +++ b/src/site/resources/scripts/index.js @@ -0,0 +1,13 @@ +$(document).ready(function(){ + $('#main-carousel').carousel({ + interval:5000 + }); + + $('#main-carousel-prev').on("click", function () { + $('#main-carousel').carousel('prev'); + }); + + $('#main-carousel-next').on("click", function () { + $('#main-carousel').carousel('next'); + }); +}); \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml new file mode 100644 index 000000000000..323f6eb065f6 --- /dev/null +++ b/src/site/site.xml @@ -0,0 +1,53 @@ + + + + ${project.name} + http://junit.org/images/junit-logo.png + http://junit.org/ + + + + + + + + + + + + org.apache.maven.skins + maven-fluido-skin + 1.3.0 + + + + + + + + + + + + + + + + + + + + + + + true + false + true + + junit-team/junit + right + + + + diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml new file mode 100644 index 000000000000..d50b470a3360 --- /dev/null +++ b/src/site/xdoc/index.xml @@ -0,0 +1,178 @@ + + + + About + + + + + + +

      + JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. +

      + +

      + Let's take a tour » +

      + +
      +
      + + +
      +

      Third-party extensions

      + +
      +
      +
      + + + +
      diff --git a/src/test/java/junit/samples/AllTests.java b/src/test/java/junit/samples/AllTests.java new file mode 100644 index 000000000000..6307404da39e --- /dev/null +++ b/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/src/test/java/junit/samples/ListTest.java b/src/test/java/junit/samples/ListTest.java new file mode 100644 index 000000000000..182027f56244 --- /dev/null +++ b/src/test/java/junit/samples/ListTest.java @@ -0,0 +1,70 @@ +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.ArrayList}. + */ +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/src/test/java/junit/samples/SimpleTest.java b/src/test/java/junit/samples/SimpleTest.java new file mode 100644 index 000000000000..5177f48a256e --- /dev/null +++ b/src/test/java/junit/samples/SimpleTest.java @@ -0,0 +1,72 @@ +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/src/test/java/junit/samples/money/IMoney.java b/src/test/java/junit/samples/money/IMoney.java new file mode 100644 index 000000000000..d48757a5b81c --- /dev/null +++ b/src/test/java/junit/samples/money/IMoney.java @@ -0,0 +1,51 @@ +package junit.samples.money; + +/** + * The common interface for simple Monies and MoneyBags + */ +public interface IMoney { + /** + * Adds a money to this money. + */ + IMoney add(IMoney m); + + /** + * Adds a simple Money to this money. This is a helper method for + * implementing double dispatch + */ + IMoney addMoney(Money m); + + /** + * Adds a MoneyBag to this money. This is a helper method for + * implementing double dispatch + */ + IMoney addMoneyBag(MoneyBag s); + + /** + * Tests whether this money is zero + */ + boolean isZero(); + + /** + * Multiplies a money by the given factor. + */ + IMoney multiply(int factor); + + /** + * Negates this money. + */ + IMoney negate(); + + /** + * Subtracts a money from this money. + */ + 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. + */ + void appendTo(MoneyBag m); +} diff --git a/src/test/java/junit/samples/money/Money.java b/src/test/java/junit/samples/money/Money.java new file mode 100644 index 000000000000..de6525b7f995 --- /dev/null +++ b/src/test/java/junit/samples/money/Money.java @@ -0,0 +1,92 @@ +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() { + return "[" + amount() + " " + currency() + "]"; + } + + public /*this makes no sense*/ void appendTo(MoneyBag m) { + m.appendMoney(this); + } +} \ No newline at end of file diff --git a/src/test/java/junit/samples/money/MoneyBag.java b/src/test/java/junit/samples/money/MoneyBag.java new file mode 100644 index 000000000000..e02bb51ef848 --- /dev/null +++ b/src/test/java/junit/samples/money/MoneyBag.java @@ -0,0 +1,155 @@ +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() { + StringBuilder sb = new StringBuilder(); + sb.append("{"); + for (Money each : fMonies) { + sb.append(each); + } + sb.append("}"); + return sb.toString(); + } + + public void appendTo(MoneyBag m) { + m.appendBag(this); + } +} \ No newline at end of file diff --git a/src/test/java/junit/samples/money/MoneyTest.java b/src/test/java/junit/samples/money/MoneyTest.java new file mode 100644 index 000000000000..170363aa18d0 --- /dev/null +++ b/src/test/java/junit/samples/money/MoneyTest.java @@ -0,0 +1,166 @@ +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/src/test/java/junit/samples/money/package-info.java b/src/test/java/junit/samples/money/package-info.java new file mode 100644 index 000000000000..eb37dd84a236 --- /dev/null +++ b/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/src/test/java/junit/samples/package-info.java b/src/test/java/junit/samples/package-info.java new file mode 100644 index 000000000000..7b9ea8f9f31b --- /dev/null +++ b/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/src/test/java/junit/tests/AllTests.java b/src/test/java/junit/tests/AllTests.java new file mode 100644 index 000000000000..8be6e26c161a --- /dev/null +++ b/src/test/java/junit/tests/AllTests.java @@ -0,0 +1,22 @@ +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/src/test/java/junit/tests/WasRun.java b/src/test/java/junit/tests/WasRun.java new file mode 100644 index 000000000000..fb294ca6aef1 --- /dev/null +++ b/src/test/java/junit/tests/WasRun.java @@ -0,0 +1,16 @@ +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/src/test/java/junit/tests/extensions/ActiveTestTest.java b/src/test/java/junit/tests/extensions/ActiveTestTest.java new file mode 100644 index 000000000000..5015b76c69bc --- /dev/null +++ b/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/src/test/java/junit/tests/extensions/AllTests.java b/src/test/java/junit/tests/extensions/AllTests.java new file mode 100644 index 000000000000..1cbcfa5a8952 --- /dev/null +++ b/src/test/java/junit/tests/extensions/AllTests.java @@ -0,0 +1,22 @@ +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/src/test/java/junit/tests/extensions/ExtensionTest.java b/src/test/java/junit/tests/extensions/ExtensionTest.java new file mode 100644 index 000000000000..155a478a4f2c --- /dev/null +++ b/src/test/java/junit/tests/extensions/ExtensionTest.java @@ -0,0 +1,104 @@ +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) { + @SuppressWarnings("deprecation") + @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) { + @SuppressWarnings("deprecation") + @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/src/test/java/junit/tests/extensions/RepeatedTestTest.java b/src/test/java/junit/tests/extensions/RepeatedTestTest.java new file mode 100644 index 000000000000..0ba736648bfa --- /dev/null +++ b/src/test/java/junit/tests/extensions/RepeatedTestTest.java @@ -0,0 +1,62 @@ +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/src/test/java/junit/tests/extensions/package-info.java b/src/test/java/junit/tests/extensions/package-info.java new file mode 100644 index 000000000000..acc01946fc22 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/AllTests.java b/src/test/java/junit/tests/framework/AllTests.java new file mode 100644 index 000000000000..860ddca3a572 --- /dev/null +++ b/src/test/java/junit/tests/framework/AllTests.java @@ -0,0 +1,31 @@ +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/src/test/java/junit/tests/framework/AssertTest.java b/src/test/java/junit/tests/framework/AssertTest.java new file mode 100644 index 000000000000..19cca6369be8 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java b/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java new file mode 100644 index 000000000000..16328b47a45f --- /dev/null +++ b/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/src/test/java/junit/tests/framework/ComparisonCompactorTest.java b/src/test/java/junit/tests/framework/ComparisonCompactorTest.java new file mode 100644 index 000000000000..16e0b4edb1c1 --- /dev/null +++ b/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 testComparisonErrorOverlappingMatches() { + String failure = new ComparisonCompactor(0, "abc", "abbc").compact(null); + assertEquals("expected:<...[]...> but was:<...[b]...>", failure); + } + + public void testComparisonErrorOverlappingMatchesContext() { + String failure = new ComparisonCompactor(2, "abc", "abbc").compact(null); + assertEquals("expected: but was:", failure); + } + + public void testComparisonErrorOverlappingMatches2() { + String failure = new ComparisonCompactor(0, "abcdde", "abcde").compact(null); + assertEquals("expected:<...[d]...> but was:<...[]...>", failure); + } + + public void testComparisonErrorOverlappingMatches2Context() { + 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/src/test/java/junit/tests/framework/ComparisonFailureTest.java b/src/test/java/junit/tests/framework/ComparisonFailureTest.java new file mode 100644 index 000000000000..284b7f562102 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java b/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java new file mode 100644 index 000000000000..439cc983dd00 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/Failure.java b/src/test/java/junit/tests/framework/Failure.java new file mode 100644 index 000000000000..00267dfb8056 --- /dev/null +++ b/src/test/java/junit/tests/framework/Failure.java @@ -0,0 +1,13 @@ +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/src/test/java/junit/tests/framework/FloatAssertTest.java b/src/test/java/junit/tests/framework/FloatAssertTest.java new file mode 100644 index 000000000000..d390f0b19cf2 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/InheritedTestCase.java b/src/test/java/junit/tests/framework/InheritedTestCase.java new file mode 100644 index 000000000000..f264e4e17689 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/NoArgTestCaseTest.java b/src/test/java/junit/tests/framework/NoArgTestCaseTest.java new file mode 100644 index 000000000000..65d1bb5830a8 --- /dev/null +++ b/src/test/java/junit/tests/framework/NoArgTestCaseTest.java @@ -0,0 +1,8 @@ +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/src/test/java/junit/tests/framework/NoTestCaseClass.java b/src/test/java/junit/tests/framework/NoTestCaseClass.java new file mode 100644 index 000000000000..f92adef5da57 --- /dev/null +++ b/src/test/java/junit/tests/framework/NoTestCaseClass.java @@ -0,0 +1,9 @@ +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/src/test/java/junit/tests/framework/NoTestCases.java b/src/test/java/junit/tests/framework/NoTestCases.java new file mode 100644 index 000000000000..61abfd3d3cae --- /dev/null +++ b/src/test/java/junit/tests/framework/NoTestCases.java @@ -0,0 +1,11 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * Test class used in SuiteTest + */ +public class NoTestCases extends TestCase { + public void noTestCase() { + } +} \ No newline at end of file diff --git a/src/test/java/junit/tests/framework/NotPublicTestCase.java b/src/test/java/junit/tests/framework/NotPublicTestCase.java new file mode 100644 index 000000000000..d95aa918c051 --- /dev/null +++ b/src/test/java/junit/tests/framework/NotPublicTestCase.java @@ -0,0 +1,14 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * Test class used in SuiteTest + */ +public class NotPublicTestCase extends TestCase { + protected void testNotPublic() { + } + + public void testPublic() { + } +} \ No newline at end of file diff --git a/src/test/java/junit/tests/framework/NotVoidTestCase.java b/src/test/java/junit/tests/framework/NotVoidTestCase.java new file mode 100644 index 000000000000..e087a227b7f7 --- /dev/null +++ b/src/test/java/junit/tests/framework/NotVoidTestCase.java @@ -0,0 +1,15 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * Test class used in SuiteTest + */ +public class NotVoidTestCase extends TestCase { + public int testNotVoid() { + return 1; + } + + public void testVoid() { + } +} \ No newline at end of file diff --git a/src/test/java/junit/tests/framework/OneTestCase.java b/src/test/java/junit/tests/framework/OneTestCase.java new file mode 100644 index 000000000000..b54b7f57fe3b --- /dev/null +++ b/src/test/java/junit/tests/framework/OneTestCase.java @@ -0,0 +1,17 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * Test class used in SuiteTest + */ +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/src/test/java/junit/tests/framework/OverrideTestCase.java b/src/test/java/junit/tests/framework/OverrideTestCase.java new file mode 100644 index 000000000000..a9b665d4b48a --- /dev/null +++ b/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/src/test/java/junit/tests/framework/Success.java b/src/test/java/junit/tests/framework/Success.java new file mode 100644 index 000000000000..510468fce2b1 --- /dev/null +++ b/src/test/java/junit/tests/framework/Success.java @@ -0,0 +1,16 @@ +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/src/test/java/junit/tests/framework/SuiteTest.java b/src/test/java/junit/tests/framework/SuiteTest.java new file mode 100644 index 000000000000..98545480d74a --- /dev/null +++ b/src/test/java/junit/tests/framework/SuiteTest.java @@ -0,0 +1,118 @@ +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/src/test/java/junit/tests/framework/TestCaseTest.java b/src/test/java/junit/tests/framework/TestCaseTest.java new file mode 100644 index 000000000000..5c100528b6b2 --- /dev/null +++ b/src/test/java/junit/tests/framework/TestCaseTest.java @@ -0,0 +1,205 @@ +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/src/test/java/junit/tests/framework/TestImplementorTest.java b/src/test/java/junit/tests/framework/TestImplementorTest.java new file mode 100644 index 000000000000..73ec5f80d965 --- /dev/null +++ b/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/src/test/java/junit/tests/framework/TestListenerTest.java b/src/test/java/junit/tests/framework/TestListenerTest.java new file mode 100644 index 000000000000..d59ba26c503a --- /dev/null +++ b/src/test/java/junit/tests/framework/TestListenerTest.java @@ -0,0 +1,80 @@ +package junit.tests.framework; + +import junit.framework.AssertionFailedError; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestListener; +import junit.framework.TestResult; + +/** + * Test class used in SuiteTest + */ +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 e) { + 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/src/test/java/junit/tests/framework/ThreeTestCases.java b/src/test/java/junit/tests/framework/ThreeTestCases.java new file mode 100644 index 000000000000..c66b0db68fd6 --- /dev/null +++ b/src/test/java/junit/tests/framework/ThreeTestCases.java @@ -0,0 +1,17 @@ +package junit.tests.framework; + +import junit.framework.TestCase; + +/** + * Test class used in SuiteTest + */ +public class ThreeTestCases extends TestCase { + public void testCase() { + } + + public void testCase2() { + } + + public void testCase3thisTimeItsPersonal() { + } +} \ No newline at end of file diff --git a/src/test/java/junit/tests/framework/package-info.java b/src/test/java/junit/tests/framework/package-info.java new file mode 100644 index 000000000000..9cc00246257c --- /dev/null +++ b/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/src/test/java/junit/tests/package-info.java b/src/test/java/junit/tests/package-info.java new file mode 100644 index 000000000000..d23121b8d550 --- /dev/null +++ b/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/src/test/java/junit/tests/runner/AllTests.java b/src/test/java/junit/tests/runner/AllTests.java new file mode 100644 index 000000000000..63f2a6fddc5c --- /dev/null +++ b/src/test/java/junit/tests/runner/AllTests.java @@ -0,0 +1,30 @@ +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/src/test/java/junit/tests/runner/BaseTestRunnerTest.java b/src/test/java/junit/tests/runner/BaseTestRunnerTest.java new file mode 100644 index 000000000000..ea38beab6d3a --- /dev/null +++ b/src/test/java/junit/tests/runner/BaseTestRunnerTest.java @@ -0,0 +1,52 @@ +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 e) { + } + + @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/src/test/java/junit/tests/runner/ResultTest.java b/src/test/java/junit/tests/runner/ResultTest.java new file mode 100644 index 000000000000..9f09fafcb216 --- /dev/null +++ b/src/test/java/junit/tests/runner/ResultTest.java @@ -0,0 +1,112 @@ +package junit.tests.runner; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; + +import junit.framework.TestCase; +import junit.tests.framework.Success; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +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(); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); + objectOutputStream.writeObject(result); + objectOutputStream.flush(); + byte[] bytes = byteArrayOutputStream.toByteArray(); + ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); + Result fromStream = (Result) objectInputStream.readObject(); + assertSerializedCorrectly(result, fromStream); + + InputStream resource = getClass().getResourceAsStream(getName()); + assertNotNull("Could not read resource " + getName(), resource); + objectInputStream = new ObjectInputStream(resource); + fromStream = (Result) objectInputStream.readObject(); + + assertSerializedCorrectly(new ResultWithFixedRunTime(result), fromStream); + } + + /** + * A version of {@code Result} that returns a hard-coded runtime. + * This makes values returned by the methods deterministic. + */ + private static class ResultWithFixedRunTime extends Result { + + private static final long serialVersionUID = 1L; + + private final Result delegate; + + public ResultWithFixedRunTime(Result delegate) { + this.delegate = delegate; + } + + @Override + public int getRunCount() { + return delegate.getRunCount(); + } + + @Override + public int getFailureCount() { + return delegate.getFailureCount(); + } + + @Override + public long getRunTime() { + return 2; + } + + @Override + public List getFailures() { + return delegate.getFailures(); + } + + @Override + public int getIgnoreCount() { + return delegate.getIgnoreCount(); + } + } + + private void assertSerializedCorrectly(Result result, Result fromStream) { + assertNotNull(fromStream); + + // Exceptions don't implement equals() so we need to compare field by field + assertEquals("failureCount", result.getFailureCount(), fromStream.getFailureCount()); + assertEquals("ignoreCount", result.getIgnoreCount(), fromStream.getIgnoreCount()); + assertEquals("runTime", result.getRunTime(), fromStream.getRunTime()); + assertEquals("failures", result.getFailures().size(), fromStream.getFailures().size()); + int index = 0; + for (Failure failure : result.getFailures()) { + Failure failureFromStream = fromStream.getFailures().get(index); + String messagePrefix = String.format("failures[%d]", index++); + assertEquals(messagePrefix + ".description", + failure.getDescription(), failureFromStream.getDescription()); + Throwable exception = failure.getException(); + Throwable exceptionFromStream = failureFromStream.getException(); + assertEquals(messagePrefix + ".exception", + exception.getClass(), exceptionFromStream.getClass()); + assertEquals(messagePrefix + ".exception", + exception.getMessage(), exceptionFromStream.getMessage()); + } + } +} diff --git a/src/test/java/junit/tests/runner/StackFilterTest.java b/src/test/java/junit/tests/runner/StackFilterTest.java new file mode 100644 index 000000000000..741fc3484612 --- /dev/null +++ b/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/src/test/java/junit/tests/runner/TextFeedbackTest.java b/src/test/java/junit/tests/runner/TextFeedbackTest.java new file mode 100644 index 000000000000..146a5acb5218 --- /dev/null +++ b/src/test/java/junit/tests/runner/TextFeedbackTest.java @@ -0,0 +1,126 @@ +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/src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java b/src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java new file mode 100644 index 000000000000..fc3651ad9475 --- /dev/null +++ b/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/src/test/java/junit/tests/runner/TextRunnerTest.java b/src/test/java/junit/tests/runner/TextRunnerTest.java new file mode 100644 index 000000000000..c74acc21335a --- /dev/null +++ b/src/test/java/junit/tests/runner/TextRunnerTest.java @@ -0,0 +1,62 @@ +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/src/test/java/junit/tests/runner/package-info.java b/src/test/java/junit/tests/runner/package-info.java new file mode 100644 index 000000000000..fc44e8a5a2d5 --- /dev/null +++ b/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/src/test/java/org/junit/AssumptionViolatedExceptionTest.java b/src/test/java/org/junit/AssumptionViolatedExceptionTest.java new file mode 100644 index 000000000000..b082933bc9af --- /dev/null +++ b/src/test/java/org/junit/AssumptionViolatedExceptionTest.java @@ -0,0 +1,95 @@ +package org.junit; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assume.assumeThat; +import org.hamcrest.Matcher; +import org.hamcrest.StringDescription; +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 AssumptionViolatedExceptionTest { + @DataPoint + public static Integer TWO = 2; + + @DataPoint + public static Matcher IS_THREE = is(3); + + @DataPoint + public static Matcher NULL = null; + + @Theory + public void toStringReportsMatcher(Integer actual, Matcher matcher) { + assumeThat(matcher, notNullValue()); + assertThat(new AssumptionViolatedException(actual, matcher).toString(), + containsString(matcher.toString())); + } + + @Theory + public void toStringReportsValue(Integer actual, Matcher matcher) { + assertThat(new AssumptionViolatedException(actual, matcher).toString(), + containsString(String.valueOf(actual))); + } + + @Test + public void assumptionViolatedExceptionWithMatcherDescribesItself() { + 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("not enough money")); + } + + @Test + public void canInitCauseWithInstanceCreatedWithString() { + AssumptionViolatedException e = new AssumptionViolatedException("invalid number"); + Throwable cause = new RuntimeException("cause"); + e.initCause(cause); + assertThat(e.getCause(), is(cause)); + } + + @Test + @SuppressWarnings("deprecation") + public void canSetCauseWithInstanceCreatedWithObjectAndMatcher() { + Throwable testObject = new Exception(); + org.junit.internal.AssumptionViolatedException e + = new org.junit.internal.AssumptionViolatedException( + testObject, containsString("test matcher")); + assertThat(e.getCause(), is(testObject)); + } + + @Test + @SuppressWarnings("deprecation") + public void canSetCauseWithInstanceCreatedWithAssumptionObjectAndMatcher() { + Throwable testObject = new Exception(); + org.junit.internal.AssumptionViolatedException e + = new org.junit.internal.AssumptionViolatedException( + "sample assumption", testObject, containsString("test matcher")); + assertThat(e.getCause(), is(testObject)); + } + + @Test + @SuppressWarnings("deprecation") + public void canSetCauseWithInstanceCreatedWithMainConstructor() { + Throwable testObject = new Exception(); + org.junit.internal.AssumptionViolatedException e + = new org.junit.internal.AssumptionViolatedException( + "sample assumption", false, testObject, containsString("test matcher")); + assertThat(e.getCause(), is(testObject)); + } + + @Test + public void canSetCauseWithInstanceCreatedWithExplicitThrowableConstructor() { + Throwable cause = new Exception(); + AssumptionViolatedException e = new AssumptionViolatedException("invalid number", cause); + assertThat(e.getCause(), is(cause)); + } +} diff --git a/src/test/java/org/junit/experimental/categories/AllCategoriesTests.java b/src/test/java/org/junit/experimental/categories/AllCategoriesTests.java new file mode 100644 index 000000000000..6609bb8dcb4e --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/AllCategoriesTests.java @@ -0,0 +1,17 @@ +package org.junit.experimental.categories; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + CategoriesAndParameterizedTest.class, + CategoryFilterFactoryTest.class, + CategoryTest.class, + CategoryValidatorTest.class, + JavadocTest.class, + MultiCategoryTest.class +}) +public class AllCategoriesTests { +} diff --git a/src/test/java/org/junit/experimental/categories/CategoriesAndParameterizedTest.java b/src/test/java/org/junit/experimental/categories/CategoriesAndParameterizedTest.java new file mode 100644 index 000000000000..68e842bb53e9 --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/CategoriesAndParameterizedTest.java @@ -0,0 +1,129 @@ +package org.junit.experimental.categories; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +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.JUnitCore; +import org.junit.runner.Result; +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 ParameterizedTestWithoutCategory { + @Parameters + public static Iterable getParameters() { + return Arrays.asList("first", "second"); + } + + @Parameterized.Parameter + public String value; + + @Test + public void testSomething() { + Assert.assertTrue(true); + } + } + + @Category(Token.class) + public static class TestThatAvoidsNoTestRemainsException { + @Test + public void testSomething() { + Assert.assertTrue(true); + } + } + + @RunWith(Categories.class) + @IncludeCategory(Token.class) + @SuiteClasses({ TestThatAvoidsNoTestRemainsException.class, + ParameterizedTestWithoutCategory.class }) + public static class SuiteWithParameterizedTestWithoutCategory { + } + + @Test + public void doesNotRunTestsWithoutCategory() { + Result result = new JUnitCore() + .run(SuiteWithParameterizedTestWithoutCategory.class); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + } + + @RunWith(Parameterized.class) + @Category(Token.class) + public static class ParameterizedTestWithCategory { + @Parameters + public static Iterable getParameters() { + return Arrays.asList("first", "second"); + } + + @Parameterized.Parameter + public String value; + + @Test + public void testSomething() { + Assert.assertTrue(true); + } + } + + @RunWith(Categories.class) + @IncludeCategory(Token.class) + @SuiteClasses({ ParameterizedTestWithCategory.class }) + public static class SuiteWithParameterizedTestWithCategory { + } + + @Test + public void runsTestsWithoutCategory() { + Result result = new JUnitCore() + .run(SuiteWithParameterizedTestWithCategory.class); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + } + + @RunWith(Parameterized.class) + public static class ParameterizedTestWithMethodWithCategory { + @Parameters + public static Iterable getParameters() { + return Arrays.asList("first", "second"); + } + + @Parameterized.Parameter + public String value; + + @Test + @Category(Token.class) + public void testSomething() { + Assert.assertTrue(true); + } + + @Test + public void testThatIsNotExecuted() { + Assert.assertTrue(true); + } + } + + @RunWith(Categories.class) + @IncludeCategory(Token.class) + @SuiteClasses({ ParameterizedTestWithMethodWithCategory.class }) + public static class SuiteWithParameterizedTestWithMethodWithCategory { + } + + @Test + public void runsTestMethodWithCategory() { + Result result = new JUnitCore() + .run(SuiteWithParameterizedTestWithMethodWithCategory.class); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/experimental/categories/CategoryFilterFactoryTest.java b/src/test/java/org/junit/experimental/categories/CategoryFilterFactoryTest.java new file mode 100644 index 000000000000..7efb6675e896 --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/CategoryFilterFactoryTest.java @@ -0,0 +1,66 @@ +package org.junit.experimental.categories; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.runner.Description.createSuiteDescription; + +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TestName; +import org.junit.runner.Description; +import org.junit.runner.FilterFactory; +import org.junit.runner.FilterFactoryParams; +import org.junit.runner.manipulation.Filter; + +public class CategoryFilterFactoryTest { + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Rule + public TestName testName = new TestName(); + + private final CategoryFilterFactory categoryFilterFactory = new CategoryFilterFactoryStub(); + + @Test + public void shouldCreateFilter() throws Exception { + FilterFactoryParams params = new FilterFactoryParams( + createSuiteDescription(testName.getMethodName()), + CategoryFilterFactoryStub.class.getName()); + Filter filter = categoryFilterFactory.createFilter(params); + + assertThat(filter, instanceOf(DummyFilter.class)); + } + + @Test + public void shouldThrowException() throws Exception { + FilterFactoryParams params = new FilterFactoryParams( + createSuiteDescription(testName.getMethodName()), + "NonExistentFilter"); + + expectedException.expect(FilterFactory.FilterNotCreatedException.class); + + categoryFilterFactory.createFilter(params); + } + + private static class CategoryFilterFactoryStub extends CategoryFilterFactory { + @Override + protected Filter createFilter(List> categories) { + return new DummyFilter(); + } + } + + private static class DummyFilter extends Filter { + @Override + public boolean shouldRun(Description description) { + return false; + } + + @Override + public String describe() { + return null; + } + } +} diff --git a/src/test/java/org/junit/experimental/categories/CategoryTest.java b/src/test/java/org/junit/experimental/categories/CategoryTest.java new file mode 100644 index 000000000000..552f689c93b6 --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/CategoryTest.java @@ -0,0 +1,548 @@ +package org.junit.experimental.categories; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +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 static org.junit.experimental.results.ResultMatchers.failureCountIs; +import static org.hamcrest.core.AnyOf.anyOf; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static java.lang.String.format; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Categories; +import org.junit.experimental.categories.Categories.CategoryFilter; +import org.junit.experimental.categories.Categories.ExcludeCategory; +import org.junit.experimental.categories.Categories.IncludeCategory; +import org.junit.experimental.categories.Category; +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 interface ReallySlowTests { + // category marker + } + + public static class OneOfEach { + + @Category(FastTests.class) + @Test + public void a() { + } + + @Category(SlowTests.class) + @Test + public void b() { + } + + @Category(ReallySlowTests.class) + @Test + public void c() { + } + } + + 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); + 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()); + assertFalse(result.wasSuccessful()); + } + + @Test + public void describeACategoryFilter() { + CategoryFilter filter = CategoryFilter.include(SlowTests.class); + assertEquals("categories [" + SlowTests.class + "]", filter.describe()); + } + + @Test + public void describeMultipleCategoryFilter() { + CategoryFilter filter= CategoryFilter.include(FastTests.class, SlowTests.class); + String d1= format("categories [%s, %s]", FastTests.class, SlowTests.class); + String d2= format("categories [%s, %s]", SlowTests.class, FastTests.class); + assertThat(filter.describe(), is(anyOf(equalTo(d1), equalTo(d2)))); + } + + + 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 interface MultiA { + } + + public interface MultiB { + } + + public interface MultiC { + } + + @RunWith(Categories.class) + @IncludeCategory(value= {MultiA.class, MultiB.class}, matchAny= false) + @SuiteClasses(AllIncludedMustMatched.class) + public static class AllIncludedMustBeMatchedSuite { + } + + public static class AllIncludedMustMatched { + @Test + @Category({MultiA.class, MultiB.class}) + public void a() { + } + + @Test + @Category(MultiB.class) + public void b() { + fail("When multiple categories are included in a Suite, " + + "@Test method must match all include categories"); + } + } + + @Test + public void allIncludedSuiteCategoriesMustBeMatched() { + Result result= JUnitCore.runClasses(AllIncludedMustBeMatchedSuite.class); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + } + + @RunWith(Categories.class) + @IncludeCategory({MultiA.class, MultiB.class}) + @ExcludeCategory(MultiC.class) + @SuiteClasses(MultipleIncludesAndExcludeOnMethod.class) + public static class MultiIncludeWithExcludeCategorySuite { + } + + public static class MultipleIncludesAndExcludeOnMethod { + @Test + @Category({MultiA.class, MultiB.class}) + public void a() { + } + + @Test + @Category({ MultiA.class, MultiB.class, MultiC.class }) + public void b() { + fail("When multiple categories are included and excluded in a Suite, " + + "@Test method must match all include categories and contain non of the excluded"); + } + } + + @Test + public void anyMethodWithExcludedCategoryWillBeExcluded() { + Result result= JUnitCore.runClasses(MultiIncludeWithExcludeCategorySuite.class); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + } + + 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()); + } + + @Category(SlowTests.class) + public static abstract class Ancestor{} + + public static class Inherited extends Ancestor { + @Test + public void a(){ + } + } + + @RunWith(Categories.class) + @IncludeCategory(SlowTests.class) + @SuiteClasses(Inherited.class) + public interface InheritanceSuite {} + + @Test + public void testInheritance() { + Result result = JUnitCore.runClasses(InheritanceSuite.class); + assertEquals(1, result.getRunCount()); + assertTrue(result.wasSuccessful()); + } + + @RunWith(Categories.class) + @IncludeCategory(Runnable.class) + @ExcludeCategory(Runnable.class) + @SuiteClasses({}) + public static class EmptyCategoriesSuite { + } + + @Test public void emptyCategoriesSuite() { + assertThat(testResult(EmptyCategoriesSuite.class), failureCountIs(1)); + } + + @Category(Runnable.class) + public static class NoTest { + } + + @Category(Runnable.class) + public static class IgnoredTest { + + @Ignore + @Test + public void test() { + fail(); + } + } + + @RunWith(Categories.class) + @IncludeCategory(Runnable.class) + @SuiteClasses({NoTest.class, IgnoredTest.class}) + public static class IgnoredTestCategoriesSuite { + } + + @Test + public void ignoredTest() {// behaves same as Suite + Result result= JUnitCore.runClasses(IgnoredTestCategoriesSuite.class); + assertFalse(result.wasSuccessful()); + assertThat(result.getRunCount(), is(1)); + assertThat(result.getFailureCount(), is(1)); + assertThat(result.getIgnoreCount(), is(1)); + } + + @Category(Runnable.class) + public static class ExcludedTest1 { + + @Test + public void test() { + fail(); + } + } + + @Category(Runnable.class) + public static class ExcludedTest2 { + + @Test + @Category(Runnable.class) + public void test() { + fail(); + } + } + + public static class IncludedTest { + + @Test + @Category(Object.class) + public void test() { + } + } + + @RunWith(Categories.class) + @IncludeCategory({Runnable.class, Object.class}) + @ExcludeCategory(Runnable.class) + @SuiteClasses({ExcludedTest1.class, ExcludedTest2.class, IncludedTest.class}) + public static class IncludedExcludedSameSuite { + } + + @Test + public void oneRunnableOthersAvoided() { + Result result= JUnitCore.runClasses(IncludedExcludedSameSuite.class); + assertEquals(1, result.getRunCount()); + assertTrue(result.wasSuccessful()); + } + + @Test + @SuppressWarnings("unchecked") + public void testCountWithMultipleExcludeFilter() throws Throwable { + Set> exclusions= new HashSet>(2); + Collections.addAll(exclusions, SlowTests.class, FastTests.class); + CategoryFilter exclude = CategoryFilter.categoryFilter(true, null, true, exclusions); + Request baseRequest= Request.aClass(OneOfEach.class); + Result result= new JUnitCore().run(baseRequest.filterWith(exclude)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + } + + @Test + public void testCountWithMultipleIncludeFilter() throws Throwable { + CategoryFilter exclude = CategoryFilter.include(true, SlowTests.class, FastTests.class); + Request baseRequest= Request.aClass(OneOfEach.class); + Result result= new JUnitCore().run(baseRequest.filterWith(exclude)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + } + + @RunWith(Categories.class) + @Categories.ExcludeCategory(String.class) + @Suite.SuiteClasses(NoIncludeCategoryAnnotationTest.class) + public static class NoIncludeCategoryAnnotationSuite { + } + + @Category(CharSequence.class) + public static class NoIncludeCategoryAnnotationTest { + + @Test + public void test2() { + } + + @Test + @Category(String.class) public void test1() { + } + } + + @Test + public void noIncludeCategoryAnnotation() { + Result testResult= JUnitCore.runClasses(NoIncludeCategoryAnnotationSuite.class); + assertTrue(testResult.wasSuccessful()); + assertEquals(1, testResult.getRunCount()); + } + + @RunWith(Categories.class) + @Categories.IncludeCategory(CharSequence.class) + @Categories.ExcludeCategory(String.class) + @Suite.SuiteClasses(NoIncludeCategoryAnnotationTest.class) + public static class SameAsNoIncludeCategoryAnnotationSuite { + } + + @Test + public void sameAsNoIncludeCategoryAnnotation() { + Result testResult= JUnitCore.runClasses(SameAsNoIncludeCategoryAnnotationSuite.class); + assertTrue(testResult.wasSuccessful()); + assertEquals(1, testResult.getRunCount()); + } +} diff --git a/src/test/java/org/junit/experimental/categories/CategoryValidatorTest.java b/src/test/java/org/junit/experimental/categories/CategoryValidatorTest.java new file mode 100644 index 000000000000..84042e9a0513 --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/CategoryValidatorTest.java @@ -0,0 +1,88 @@ +package org.junit.experimental.categories; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.experimental.categories.CategoryValidator; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; + +public class CategoryValidatorTest { + + public static class SampleCategory { + } + + public static class CategoryTest { + @BeforeClass + @Category(value = SampleCategory.class) + public static void methodWithCategoryAndBeforeClass() { + } + + @AfterClass + @Category(value = SampleCategory.class) + public static void methodWithCategoryAndAfterClass() { + } + + @Before + @Category(value = SampleCategory.class) + public static void methodWithCategoryAndBefore() { + } + + @After + @Category(value = SampleCategory.class) + public static void methodWithCategoryAndAfter() { + } + + @Category(value = SampleCategory.class) + public static void methodWithCategory() { + } + } + + @Test + public void errorIsAddedWhenCategoryIsUsedWithBeforeClass() { + FrameworkMethod method = new TestClass(CategoryTest.class).getAnnotatedMethods(BeforeClass.class).get(0); + testAndAssertErrorMessage(method, "@BeforeClass can not be combined with @Category"); + } + + @Test + public void errorIsAddedWhenCategoryIsUsedWithAfterClass() { + FrameworkMethod method = new TestClass(CategoryTest.class).getAnnotatedMethods(AfterClass.class).get(0); + testAndAssertErrorMessage(method, "@AfterClass can not be combined with @Category"); + } + + @Test + public void errorIsAddedWhenCategoryIsUsedWithBefore() { + FrameworkMethod method = new TestClass(CategoryTest.class).getAnnotatedMethods(Before.class).get(0); + testAndAssertErrorMessage(method, "@Before can not be combined with @Category"); + } + + @Test + public void errorIsAddedWhenCategoryIsUsedWithAfter() { + FrameworkMethod method = new TestClass(CategoryTest.class).getAnnotatedMethods(After.class).get(0); + testAndAssertErrorMessage(method, "@After can not be combined with @Category"); + } + + private void testAndAssertErrorMessage(FrameworkMethod method, String expectedErrorMessage) { + List errors = new CategoryValidator().validateAnnotatedMethod(method); + + assertThat(errors.size(), is(1)); + Exception exception = errors.get(0); + assertThat(exception.getMessage(), is(expectedErrorMessage)); + } + + @Test + public void errorIsNotAddedWhenCategoryIsNotCombinedWithIllegalCombination() throws NoSuchMethodException { + FrameworkMethod method = new FrameworkMethod(CategoryTest.class.getMethod("methodWithCategory")); + List errors = new CategoryValidator().validateAnnotatedMethod(method); + + assertThat(errors.size(), is(0)); + } +} diff --git a/src/test/java/org/junit/experimental/categories/JavadocTest.java b/src/test/java/org/junit/experimental/categories/JavadocTest.java new file mode 100644 index 000000000000..65fa430f9dbb --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/JavadocTest.java @@ -0,0 +1,78 @@ +package org.junit.experimental.categories; + +import org.junit.Test; +import org.junit.experimental.categories.Categories; +import org.junit.experimental.categories.Category; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * @author tibor17 + * @version 4.12 + * @since 4.12 + */ +public class JavadocTest { + public static interface FastTests {} + public static interface SlowTests {} + public static interface SmokeTests {} + + public static class A { + public void a() { + fail(); + } + + @Category(SlowTests.class) + @Test + public void b() { + } + + @Category({FastTests.class, SmokeTests.class}) + @Test + public void c() { + } + } + + @Category({SlowTests.class, FastTests.class}) + public static class B { + @Test + public void d() { + } + } + + @RunWith(Categories.class) + @Categories.IncludeCategory(SlowTests.class) + @Suite.SuiteClasses({A.class, B.class}) + public static class SlowTestSuite { + // Will run A.b and B.d, but not A.a and A.c + } + + @RunWith(Categories.class) + @Categories.IncludeCategory({FastTests.class, SmokeTests.class}) + @Suite.SuiteClasses({A.class, B.class}) + public static class FastOrSmokeTestSuite { + // Will run A.c and B.d, but not A.b because it is not any of FastTests or SmokeTests + } + + @Test + public void slowTests() { + Result testResult= JUnitCore.runClasses(SlowTestSuite.class); + assertTrue(testResult.wasSuccessful()); + assertThat("unexpected run count", testResult.getRunCount(), is(2)); + assertThat("unexpected failure count", testResult.getFailureCount(), is(0)); + } + + @Test + public void fastSmokeTests() { + Result testResult= JUnitCore.runClasses(FastOrSmokeTestSuite.class); + assertTrue(testResult.wasSuccessful()); + assertThat("unexpected run count", testResult.getRunCount(), is(2)); + assertThat("unexpected failure count", testResult.getFailureCount(), is(0)); + } +} diff --git a/src/test/java/org/junit/experimental/categories/MultiCategoryTest.java b/src/test/java/org/junit/experimental/categories/MultiCategoryTest.java new file mode 100644 index 000000000000..c7169aca120a --- /dev/null +++ b/src/test/java/org/junit/experimental/categories/MultiCategoryTest.java @@ -0,0 +1,171 @@ +package org.junit.experimental.categories; + +import org.junit.Test; +import org.junit.experimental.categories.Categories; +import org.junit.experimental.categories.Category; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +/** + * @author tibor17 + * @version 4.12 + * @since 4.12 + */ +public final class MultiCategoryTest { + public interface A {} + public interface B {} + public interface C {} + + /** + * This test is mentioned in {@code Categories} and any changes + * must be reflected. + */ + @Test + public void runSuite() { + // Targeting Test: + Result testResult= JUnitCore.runClasses(MultiCategorySuite.class); + + assertThat("unexpected run count", testResult.getRunCount(), is(equalTo(2))); + assertThat("unexpected failure count", testResult.getFailureCount(), is(equalTo(0))); + assertThat("unexpected failure count", testResult.getIgnoreCount(), is(equalTo(0))); + } + + @RunWith(Categories.class) + @Categories.IncludeCategory({A.class, B.class}) + @Categories.ExcludeCategory(C.class) + @Suite.SuiteClasses({CategoriesTest.class}) + public static final class MultiCategorySuite {} + + public static final class CategoriesTest { + + @Test + @Category(A.class) + public void a() {} + + @Test + @Category(B.class) + public void b() {} + + @Test + @Category(C.class) + public void c() { + fail(); + } + + @Test + public void anything() { + fail(); + } + } + + @Test + public void inheritanceAnyIncluded() { + Result testResult= JUnitCore.runClasses(InheritanceAny.class); + assertThat("unexpected run count", testResult.getRunCount(), is(equalTo(3))); + assertThat("unexpected failure count", testResult.getFailureCount(), is(equalTo(0))); + assertThat("unexpected failure count", testResult.getIgnoreCount(), is(equalTo(0))); + } + + @Test + public void inheritanceAllIncluded() { + Result testResult= JUnitCore.runClasses(InheritanceAll.class); + assertThat("unexpected run count", testResult.getRunCount(), is(equalTo(1))); + assertThat("unexpected failure count", testResult.getFailureCount(), is(equalTo(0))); + assertThat("unexpected failure count", testResult.getIgnoreCount(), is(equalTo(0))); + } + + @Test + public void inheritanceAnyAll() {//any included, all excluded + Result testResult= JUnitCore.runClasses(InheritanceAnyAll.class); + assertThat("unexpected run count", testResult.getRunCount(), is(equalTo(3))); + assertThat("unexpected failure count", testResult.getFailureCount(), is(equalTo(0))); + assertThat("unexpected failure count", testResult.getIgnoreCount(), is(equalTo(0))); + } + + @Test + public void inheritanceAllAny() {//all included, any excluded + Result testResult= JUnitCore.runClasses(InheritanceAllAny.class); + assertThat("unexpected run count", testResult.getRunCount(), is(equalTo(1))); + assertThat("unexpected failure count", testResult.getFailureCount(), is(equalTo(1))); + assertThat("unexpected failure count", testResult.getIgnoreCount(), is(equalTo(0))); + assertFalse(testResult.wasSuccessful()); + } + + public static class X implements A {} + public static class Y implements B {} + public static class Z implements A, B {} + public static class W implements A, B, C {} + public static class Q implements A, C {} + + @RunWith(Categories.class) + @Categories.IncludeCategory({A.class, B.class}) + @Categories.ExcludeCategory(C.class) + @Suite.SuiteClasses({InheritanceAnyTest.class}) + public static final class InheritanceAny {} + + @RunWith(Categories.class) + @Categories.IncludeCategory(value= {A.class, B.class}, matchAny= false) + @Categories.ExcludeCategory(C.class) + @Suite.SuiteClasses({InheritanceAllTest.class}) + public static final class InheritanceAll {} + + @RunWith(Categories.class) + @Categories.IncludeCategory({A.class, B.class}) + @Categories.ExcludeCategory(value= {A.class, C.class}, matchAny= false) + @Suite.SuiteClasses({InheritanceAnyAllTest.class}) + public static final class InheritanceAnyAll {} + + @RunWith(Categories.class) + @Categories.IncludeCategory(value= {A.class, B.class}, matchAny= false) + @Categories.ExcludeCategory({A.class, C.class}) + @Suite.SuiteClasses({InheritanceAllAnyTest.class}) + public static final class InheritanceAllAny {} + + public static final class InheritanceAnyTest { + @Test @Category(X.class) public void x() {} + @Test @Category(Y.class) public void y() {} + @Test @Category(Z.class) public void z() {} + @Test @Category(W.class) public void w() { fail(); } + @Test @Category(Q.class) public void q() { fail(); } + @Test @Category(Runnable.class) public void runnable() { fail(); } + @Test public void t() { fail(); } + } + + public static final class InheritanceAllTest { + @Test @Category(X.class) public void x() { fail(); } + @Test @Category(Y.class) public void y() { fail(); } + @Test @Category(Z.class) public void z() {} + @Test @Category(W.class) public void w() { fail(); } + @Test @Category(Q.class) public void q() { fail(); } + @Test @Category(Runnable.class) public void runnable() { fail(); } + @Test public void t() { fail(); } + } + + public static final class InheritanceAnyAllTest { + @Test @Category(X.class) public void x() {} + @Test @Category(Y.class) public void y() {} + @Test @Category(Z.class) public void z() {} + @Test @Category(W.class) public void w() { fail(); } + @Test @Category(Q.class) public void q() { fail(); } + @Test @Category(Runnable.class) public void runnable() { fail(); } + @Test public void t() { fail(); } + } + + public static final class InheritanceAllAnyTest { + @Test @Category(X.class) public void x() { fail(); } + @Test @Category(Y.class) public void y() { fail(); } + @Test @Category(Z.class) public void z() { fail(); } + @Test @Category(W.class) public void w() { fail(); } + @Test @Category(Q.class) public void q() { fail(); } + @Test @Category(Runnable.class) public void runnable() { fail(); } + @Test public void t() { fail(); } + } +} diff --git a/src/test/java/org/junit/internal/AllInternalTests.java b/src/test/java/org/junit/internal/AllInternalTests.java new file mode 100644 index 000000000000..04cef67c73ab --- /dev/null +++ b/src/test/java/org/junit/internal/AllInternalTests.java @@ -0,0 +1,23 @@ +package org.junit.internal; + +import org.junit.internal.builders.AnnotatedBuilderTest; +import org.junit.internal.matchers.StacktracePrintingMatcherTest; +import org.junit.internal.matchers.ThrowableCauseMatcherTest; +import org.junit.internal.runners.ErrorReportingRunnerTest; +import org.junit.internal.runners.statements.FailOnTimeoutTest; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AnnotatedBuilderTest.class, + ErrorReportingRunnerTest.class, + FailOnTimeoutTest.class, + MethodSorterTest.class, + StacktracePrintingMatcherTest.class, + ThrowableCauseMatcherTest.class, + ArrayComparisonFailureTest.class +}) +public class AllInternalTests { +} diff --git a/src/test/java/org/junit/internal/ArrayComparisonFailureTest.java b/src/test/java/org/junit/internal/ArrayComparisonFailureTest.java new file mode 100644 index 000000000000..93db64992fa3 --- /dev/null +++ b/src/test/java/org/junit/internal/ArrayComparisonFailureTest.java @@ -0,0 +1,68 @@ +package org.junit.internal; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +public class ArrayComparisonFailureTest { + + private static final String ARRAY_COMPARISON_FAILURE_411 = "arrayComparisonFailure_411"; + private static final String ARRAY_COMPARISON_FAILURE_412 = "arrayComparisonFailure_412"; + + /* + Test compatibility of older versions of ArrayComparisonFailure + Setup: + - checkout prior versions of the codebase (r4.11, r4.12 in this case) + - catch the exception resulting from: + assertArrayEquals(new int[]{0, 1}, new int[]{0, 5}); + - serialize the resulting exception to a file, moving into the test/resources path + Ex., for v4.11's resulting exception {@link org/junit/internal/arrayComparisonFailure_411} + Current unit test: + - deserialize the above files casting it to the current version of the class + (catches any forward incompatibility with missing fields) + - assert the results from existing methods: getCause(), toString() -> getMessage() + (catches incompatible usages of fields) + + This does not test if an instance of the current version of the class is able to deserialize to a previous ver. + */ + + @Test + public void classShouldAccept411Version() throws Exception { + assertFailureSerializableFromOthers(ARRAY_COMPARISON_FAILURE_411); + } + + @Test + public void classShouldAccept412Version() throws Exception { + assertFailureSerializableFromOthers(ARRAY_COMPARISON_FAILURE_412); + } + + private void assertFailureSerializableFromOthers(String failureFileName) throws IOException, + ClassNotFoundException { + try { + assertArrayEquals(new int[]{0, 1}, new int[]{0, 5}); + fail(); + } catch (ArrayComparisonFailure e) { + ArrayComparisonFailure arrayComparisonFailureFromFile = deserializeFailureFromFile(failureFileName); + assertNotNull("ArrayComparisonFailure.getCause() should fallback to the deprecated fCause field" + + " for compatibility with older versions of junit4 that didn't use Throwable.initCause().", + arrayComparisonFailureFromFile.getCause()); + assertEquals(e.getCause().toString(), arrayComparisonFailureFromFile.getCause().toString()); + assertEquals(e.toString(), arrayComparisonFailureFromFile.toString()); + } + } + + private ArrayComparisonFailure deserializeFailureFromFile(String fileName) throws IOException, + ClassNotFoundException { + InputStream resource = getClass().getResourceAsStream(fileName); + ObjectInputStream objectInputStream = new ObjectInputStream(resource); + return (ArrayComparisonFailure) objectInputStream.readObject(); + } + +} \ No newline at end of file diff --git a/src/test/java/org/junit/internal/MethodSorterTest.java b/src/test/java/org/junit/internal/MethodSorterTest.java new file mode 100644 index 000000000000..1934fa2d7e27 --- /dev/null +++ b/src/test/java/org/junit/internal/MethodSorterTest.java @@ -0,0 +1,182 @@ +package org.junit.internal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertArrayEquals; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +public class MethodSorterTest { + private static final String ALPHA = "java.lang.Object alpha(int,double,java.lang.Thread)"; + private static final String BETA = "void beta(int[][])"; + private static final String GAMMA_VOID = "int gamma()"; + private static final String GAMMA_BOOLEAN = "void gamma(boolean)"; + private static final String DELTA = "void delta()"; + private static final String EPSILON = "void epsilon()"; + private static final String SUPER_METHOD = "void superMario()"; + private static final String SUB_METHOD = "void subBowser()"; + + static class DummySortWithoutAnnotation { + Object alpha(int i, double d, Thread t) { + return null; + } + + void beta(int[][] x) { + } + + int gamma() { + return 0; + } + + void gamma(boolean b) { + } + + void delta() { + } + + void epsilon() { + } + } + + static class Super { + void superMario() { + } + } + + static class Sub extends Super { + void subBowser() { + } + } + + private List getDeclaredMethodNames(Class clazz) { + Method[] actualMethods = MethodSorter.getDeclaredMethods(clazz); + + // Obtain just the names instead of the full methods. + List names = new ArrayList(); + for (Method m : actualMethods) { + // Filter out synthetic methods from, e.g., coverage tools. + if (!m.isSynthetic()) { + names.add(m.toString().replace(clazz.getName() + '.', "")); + } + } + + return names; + } + + @Test + public void testMethodsNullSorterSelf() { + List expected = Arrays.asList(EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN); + List actual = getDeclaredMethodNames(DummySortWithoutAnnotation.class); + assertEquals(expected, actual); + } + + @Test + public void testMethodsNullSorterSuper() { + List expected = Arrays.asList(SUPER_METHOD); + List actual = getDeclaredMethodNames(Super.class); + assertEquals(expected, actual); + } + + @Test + public void testMethodsNullSorterSub() { + List expected = Arrays.asList(SUB_METHOD); + List actual = getDeclaredMethodNames(Sub.class); + assertEquals(expected, actual); + } + + @FixMethodOrder(MethodSorters.DEFAULT) + static class DummySortWithDefault { + Object alpha(int i, double d, Thread t) { + return null; + } + + void beta(int[][] x) { + } + + int gamma() { + return 0; + } + + void gamma(boolean b) { + } + + void delta() { + } + + void epsilon() { + } + } + + @Test + public void testDefaultMethodSorter() { + List expected = Arrays.asList(EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN); + List actual = getDeclaredMethodNames(DummySortWithDefault.class); + assertEquals(expected, actual); + } + + @FixMethodOrder(MethodSorters.JVM) + static class DummySortJvm { + Object alpha(int i, double d, Thread t) { + return null; + } + + void beta(int[][] x) { + } + + int gamma() { + return 0; + } + + void gamma(boolean b) { + } + + void delta() { + } + + void epsilon() { + } + } + + @Test + public void testJvmMethodSorter() { + Method[] fromJvmWithSynthetics = DummySortJvm.class.getDeclaredMethods(); + Method[] sorted = MethodSorter.getDeclaredMethods(DummySortJvm.class); + assertArrayEquals(fromJvmWithSynthetics, sorted); + } + + @FixMethodOrder(MethodSorters.NAME_ASCENDING) + static class DummySortWithNameAsc { + Object alpha(int i, double d, Thread t) { + return null; + } + + void beta(int[][] x) { + } + + int gamma() { + return 0; + } + + void gamma(boolean b) { + } + + void delta() { + } + + void epsilon() { + } + } + + @Test + public void testAscendingMethodSorter() { + List expected = Arrays.asList(ALPHA, BETA, DELTA, EPSILON, GAMMA_VOID, GAMMA_BOOLEAN); + List actual = getDeclaredMethodNames(DummySortWithNameAsc.class); + assertEquals(expected, actual); + } +} diff --git a/src/test/java/org/junit/internal/builders/AnnotatedBuilderTest.java b/src/test/java/org/junit/internal/builders/AnnotatedBuilderTest.java new file mode 100644 index 000000000000..9879d3a5228d --- /dev/null +++ b/src/test/java/org/junit/internal/builders/AnnotatedBuilderTest.java @@ -0,0 +1,105 @@ +package org.junit.internal.builders; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.assertThat; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runner.Runner; +import org.junit.runner.RunnerSpy; +import org.junit.runners.model.RunnerBuilder; +import org.junit.runners.model.RunnerBuilderStub; + +public class AnnotatedBuilderTest { + private AnnotatedBuilder builder = new AnnotatedBuilder(new RunnerBuilderStub()); + + @Test + public void topLevelTestClassWithoutAnnotation_isRunWithDefaultRunner() throws Exception { + Runner runner = builder.runnerForClass(Object.class); + assertThat(runner, is(nullValue())); + } + + @Test + public void topLevelTestClassWithAnnotation_isRunWithAnnotatedRunner() throws Exception { + Runner runner = builder.runnerForClass(OuterClass.class); + assertThat(runner, is(instanceOf(RunnerSpy.class))); + + RunnerSpy runnerSpy = (RunnerSpy) runner; + assertThat(runnerSpy.getInvokedTestClass(), is((Object) OuterClass.class)); + } + + @Test + public void memberClassInsideAnnotatedTopLevelClass_isRunWithTopLevelRunner() throws Exception { + Runner runner = builder.runnerForClass(OuterClass.InnerClassWithoutOwnRunWith.class); + assertThat(runner, is(instanceOf(RunnerSpy.class))); + + RunnerSpy runnerSpy = (RunnerSpy) runner; + assertThat(runnerSpy.getInvokedTestClass(), is((Object) OuterClass.InnerClassWithoutOwnRunWith.class)); + } + + @Test + public void memberClassDeepInsideAnnotatedTopLevelClass_isRunWithTopLevelRunner() throws Exception { + Runner runner = builder.runnerForClass(OuterClass.InnerClassWithoutOwnRunWith.MostInnerClass.class); + assertThat(runner, is(instanceOf(RunnerSpy.class))); + + RunnerSpy runnerSpy = (RunnerSpy) runner; + assertThat(runnerSpy.getInvokedTestClass(), is((Object) OuterClass.InnerClassWithoutOwnRunWith.MostInnerClass.class)); + } + + @Test + public void annotatedMemberClassInsideAnnotatedTopLevelClass_isRunWithOwnRunner() throws Exception { + Runner runner = builder.runnerForClass(OuterClass.InnerClassWithOwnRunWith.class); + assertThat(runner, is(instanceOf(InnerRunner.class))); + + RunnerSpy runnerSpy = (RunnerSpy) runner; + assertThat(runnerSpy.getInvokedTestClass(), is((Object) OuterClass.InnerClassWithOwnRunWith.class)); + } + + @Test + public void memberClassDeepInsideAnnotatedMemberClass_isRunWithParentMemberClassRunner() throws Exception { + Runner runner = builder.runnerForClass(OuterClass.InnerClassWithOwnRunWith.MostInnerClass.class); + assertThat(runner, is(instanceOf(InnerRunner.class))); + + RunnerSpy runnerSpy = (RunnerSpy) runner; + assertThat(runnerSpy.getInvokedTestClass(), is((Object) OuterClass.InnerClassWithOwnRunWith.MostInnerClass.class)); + } + + @RunWith(RunnerSpy.class) + public static class OuterClass { + public class InnerClassWithoutOwnRunWith { + @Test + public void test() { + } + + public class MostInnerClass { + @Test + public void test() { + } + } + } + + @RunWith(InnerRunner.class) + public class InnerClassWithOwnRunWith { + @Test + public void test() { + } + + public class MostInnerClass { + @Test + public void test() { + } + } + } + } + + public static class InnerRunner extends RunnerSpy { + public InnerRunner(Class testClass) { + super(testClass); + } + + public InnerRunner(Class testClass, RunnerBuilder runnerBuilder) { + super(testClass, runnerBuilder); + } + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java b/src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java new file mode 100644 index 000000000000..3bd2c54b4d04 --- /dev/null +++ b/src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java @@ -0,0 +1,38 @@ +package org.junit.internal.matchers; + +import static org.hamcrest.CoreMatchers.any; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.internal.matchers.StacktracePrintingMatcher.isException; +import static org.junit.internal.matchers.StacktracePrintingMatcher.isThrowable; + +import org.junit.Test; + +public class StacktracePrintingMatcherTest { + + @Test + public void succeedsWhenInnerMatcherSucceeds() throws Exception { + assertTrue(isThrowable(any(Throwable.class)).matches(new Exception())); + } + + @Test + public void failsWhenInnerMatcherFails() throws Exception { + assertFalse(isException(notNullValue(Exception.class)).matches(null)); + } + + @Test + public void assertThatIncludesStacktrace() { + Exception actual = new IllegalArgumentException("my message"); + Exception expected = new NullPointerException(); + + try { + assertThat(actual, isThrowable(equalTo(expected))); + } catch (AssertionError e) { + assertThat(e.getMessage(), containsString("Stacktrace was: java.lang.IllegalArgumentException: my message")); + } + } +} diff --git a/src/test/java/org/junit/internal/matchers/ThrowableCauseMatcherTest.java b/src/test/java/org/junit/internal/matchers/ThrowableCauseMatcherTest.java new file mode 100644 index 000000000000..dba1f7b2ce03 --- /dev/null +++ b/src/test/java/org/junit/internal/matchers/ThrowableCauseMatcherTest.java @@ -0,0 +1,18 @@ +package org.junit.internal.matchers; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause; + +public class ThrowableCauseMatcherTest { + + @Test + public void shouldAllowCauseOfDifferentClassFromRoot() throws Exception { + NullPointerException expectedCause = new NullPointerException("expected"); + Exception actual = new Exception(expectedCause); + + assertThat(actual, hasCause(is(expectedCause))); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/internal/runners/ErrorReportingRunnerTest.java b/src/test/java/org/junit/internal/runners/ErrorReportingRunnerTest.java new file mode 100644 index 000000000000..e8263e544bc5 --- /dev/null +++ b/src/test/java/org/junit/internal/runners/ErrorReportingRunnerTest.java @@ -0,0 +1,88 @@ +package org.junit.internal.runners; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.InvalidTestClassError; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.MatcherAssert.assertThat; + +public class ErrorReportingRunnerTest { + + @Test(expected = NullPointerException.class) + public void cannotCreateWithNullClass() { + new ErrorReportingRunner(null, new RuntimeException()); + } + + @Test(expected = NullPointerException.class) + public void cannotCreateWithNullClass2() { + new ErrorReportingRunner(new RuntimeException(), (Class) null); + } + + @Test(expected = NullPointerException.class) + public void cannotCreateWithNullClasses() { + new ErrorReportingRunner(new RuntimeException(), (Class[]) null); + } + + @Test(expected = NullPointerException.class) + public void cannotCreateWithoutClass() { + new ErrorReportingRunner(new RuntimeException()); + } + + @Test + public void givenInvalidTestClassErrorAsCause() { + final List firedFailures = new ArrayList(); + InvalidTestClassError testClassError = new InvalidTestClassError(TestClassWithErrors.class, + Arrays.asList(new Throwable("validation error 1"), new Throwable("validation error 2"))); + ErrorReportingRunner sut = new ErrorReportingRunner(TestClassWithErrors.class, testClassError); + + sut.run(new RunNotifier() { + @Override + public void fireTestFailure(Failure failure) { + super.fireTestFailure(failure); + firedFailures.add(failure); + } + }); + + assertThat(firedFailures.size(), is(1)); + Throwable exception = firedFailures.get(0).getException(); + assertThat(exception, instanceOf(InvalidTestClassError.class)); + assertThat(((InvalidTestClassError) exception), is(testClassError)); + } + + @Test + public void givenInvalidTestClass_integrationTest() { + Result result = JUnitCore.runClasses(TestClassWithErrors.class); + + assertThat(result.getFailureCount(), is(1)); + Throwable failure = result.getFailures().get(0).getException(); + assertThat(failure, instanceOf(InvalidTestClassError.class)); + assertThat(failure.getMessage(), allOf( + startsWith("Invalid test class '" + TestClassWithErrors.class.getName() + "'"), + containsString("\n 1. "), + containsString("\n 2. ") + )); + } + + private static class TestClassWithErrors { + @Before public static void staticBeforeMethod() {} + @After public static void staticAfterMethod() {} + + @Test public String testMethodReturningString() { + return "this should not be allowed"; + } + } +} diff --git a/src/test/java/org/junit/internal/runners/statements/FailOnTimeoutTest.java b/src/test/java/org/junit/internal/runners/statements/FailOnTimeoutTest.java new file mode 100644 index 000000000000..ad70b162cbdc --- /dev/null +++ b/src/test/java/org/junit/internal/runners/statements/FailOnTimeoutTest.java @@ -0,0 +1,195 @@ +package org.junit.internal.runners.statements; + +import static java.lang.Long.MAX_VALUE; +import static java.lang.Math.atan; +import static java.lang.System.currentTimeMillis; +import static java.lang.Thread.sleep; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.hamcrest.core.Is.is; +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 static org.junit.internal.runners.statements.FailOnTimeout.builder; + +import java.util.concurrent.TimeUnit; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runners.model.Statement; +import org.junit.runners.model.TestTimedOutException; + +/** + * @author Asaf Ary, Stefan Birkner + */ +public class FailOnTimeoutTest { + private static final long TIMEOUT = 100; + private static final long DURATION_THAT_EXCEEDS_TIMEOUT = 60 * 60 * 1000; //1 hour + + @Rule + public final ExpectedException thrown = ExpectedException.none(); + + private final TestStatement statement = new TestStatement(); + + private final FailOnTimeout failOnTimeout = builder().withTimeout(TIMEOUT, MILLISECONDS).build(statement); + + @Test + public void throwsTestTimedOutException() throws Throwable { + thrown.expect(TestTimedOutException.class); + evaluateWithWaitDuration(DURATION_THAT_EXCEEDS_TIMEOUT); + } + + @Test + public void throwExceptionWithNiceMessageOnTimeout() throws Throwable { + thrown.expectMessage("test timed out after 100 milliseconds"); + evaluateWithWaitDuration(DURATION_THAT_EXCEEDS_TIMEOUT); + } + + @Test + public void sendUpExceptionThrownByStatement() throws Throwable { + RuntimeException exception = new RuntimeException(); + thrown.expect(is(exception)); + evaluateWithException(exception); + } + + @Test + public void throwExceptionIfTheSecondCallToEvaluateNeedsTooMuchTime() + throws Throwable { + thrown.expect(TestTimedOutException.class); + evaluateWithWaitDuration(0); + evaluateWithWaitDuration(DURATION_THAT_EXCEEDS_TIMEOUT); + } + + @Test + public void throwTimeoutExceptionOnSecondCallAlthoughFirstCallThrowsException() + throws Throwable { + thrown.expectMessage("test timed out after 100 milliseconds"); + try { + evaluateWithException(new RuntimeException()); + } catch (Throwable expected) { + } + evaluateWithWaitDuration(DURATION_THAT_EXCEEDS_TIMEOUT); + } + + @Test + public void throwsExceptionWithTimeoutValueAndTimeUnitSet() + throws Throwable { + try { + evaluateWithWaitDuration(DURATION_THAT_EXCEEDS_TIMEOUT); + fail("No exception was thrown when test timed out"); + } catch (TestTimedOutException e) { + assertEquals(TIMEOUT, e.getTimeout()); + assertEquals(TimeUnit.MILLISECONDS, e.getTimeUnit()); + } + } + + private void evaluateWithException(Exception exception) throws Throwable { + statement.nextException = exception; + statement.waitDuration = 0; + failOnTimeout.evaluate(); + } + + private void evaluateWithWaitDuration(long waitDuration) throws Throwable { + statement.nextException = null; + statement.waitDuration = waitDuration; + failOnTimeout.evaluate(); + } + + private static final class TestStatement extends Statement { + long 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 = builder().withTimeout(TIMEOUT, MILLISECONDS).build(infiniteLoop); + 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; + } + } + } + + @Test + public void stackTraceContainsRealCauseOfTimeout() throws Throwable { + StuckStatement stuck = new StuckStatement(); + FailOnTimeout stuckTimeout = builder().withTimeout(TIMEOUT, MILLISECONDS).build(stuck); + try { + stuckTimeout.evaluate(); + // We must not get here, we expect a timeout exception + fail("Expected timeout exception"); + } catch (Exception timeoutException) { + StackTraceElement[] stackTrace = timeoutException.getStackTrace(); + boolean stackTraceContainsTheRealCauseOfTheTimeout = false; + boolean stackTraceContainsOtherThanTheRealCauseOfTheTimeout = false; + for (StackTraceElement element : stackTrace) { + String methodName = element.getMethodName(); + if ("theRealCauseOfTheTimeout".equals(methodName)) { + stackTraceContainsTheRealCauseOfTheTimeout = true; + } + if ("notTheRealCauseOfTheTimeout".equals(methodName)) { + stackTraceContainsOtherThanTheRealCauseOfTheTimeout = true; + } + } + assertTrue( + "Stack trace does not contain the real cause of the timeout", + stackTraceContainsTheRealCauseOfTheTimeout); + assertFalse( + "Stack trace contains other than the real cause of the timeout, which can be very misleading", + stackTraceContainsOtherThanTheRealCauseOfTheTimeout); + } + } + + private static final class StuckStatement extends Statement { + + @Override + public void evaluate() throws Throwable { + try { + // Must show up in stack trace + theRealCauseOfTheTimeout(); + } catch (InterruptedException e) { + } finally { + // Must _not_ show up in stack trace + notTheRealCauseOfTheTimeout(); + } + } + + private void theRealCauseOfTheTimeout() throws InterruptedException { + sleep(MAX_VALUE); + } + + private void notTheRealCauseOfTheTimeout() { + for (long now = currentTimeMillis(), eta = now + 1000L; now < eta; now = currentTimeMillis()) { + // Doesn't matter, just pretend to be busy + atan(now); + } + } + } +} diff --git a/src/test/java/org/junit/rules/AllRulesTests.java b/src/test/java/org/junit/rules/AllRulesTests.java new file mode 100644 index 000000000000..af48f5792655 --- /dev/null +++ b/src/test/java/org/junit/rules/AllRulesTests.java @@ -0,0 +1,30 @@ +package org.junit.rules; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + BlockJUnit4ClassRunnerOverrideTest.class, + ClassRulesTest.class, + DisableOnDebugTest.class, + ExpectedExceptionTest.class, + ExternalResourceRuleTest.class, + MethodRulesTest.class, + NameRulesTest.class, + RuleChainTest.class, + RuleMemberValidatorTest.class, + StopwatchTest.class, + TempFolderRuleTest.class, + TemporaryFolderRuleAssuredDeletionTest.class, + TemporaryFolderUsageTest.class, + TestRuleTest.class, + TestWatcherTest.class, + TestWatchmanTest.class, + // todo TestWatchmanTest.class, - doesn't work and wasn't being run before. + TimeoutRuleTest.class, + VerifierRuleTest.class +}) +public class AllRulesTests { +} diff --git a/src/test/java/org/junit/rules/BlockJUnit4ClassRunnerOverrideTest.java b/src/test/java/org/junit/rules/BlockJUnit4ClassRunnerOverrideTest.java new file mode 100644 index 000000000000..c7047a827d84 --- /dev/null +++ b/src/test/java/org/junit/rules/BlockJUnit4ClassRunnerOverrideTest.java @@ -0,0 +1,175 @@ +package org.junit.rules; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +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.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; + +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()); + } + + + /** + * Runner for testing override of {@link org.junit.runners.BlockJUnit4ClassRunner#createTest(org.junit.runners.model.FrameworkMethod)} + * by setting the {@link org.junit.runners.model.FrameworkMethod} in a field + * of the test class so it can be compared with the test method that is being + * executed. + */ + public static class OverrideCreateTestRunner extends BlockJUnit4ClassRunner { + public OverrideCreateTestRunner(final Class klass) throws InitializationError { + super(klass); + + assert(klass.equals(OverrideCreateTest.class)); + } + + @Override + protected Object createTest(FrameworkMethod method) { + final OverrideCreateTest obj = new OverrideCreateTest(); + + obj.method = method; + + return obj; + } + } + + @RunWith(OverrideCreateTestRunner.class) + public static class OverrideCreateTest { + public FrameworkMethod method; + + @Test + public void testMethodA() { + assertEquals("testMethodA", method.getMethod().getName()); + } + + @Test + public void testMethodB() { + assertEquals("testMethodB", method.getMethod().getName()); + } + } + + @Test + public void overrideCreateTestMethod() { + assertThat(testResult(OverrideCreateTest.class), isSuccessful()); + } + + + /** + * Runner for testing override of {@link org.junit.runners.BlockJUnit4ClassRunner#createTest()} + * is still called by default if no other {@code createTest} method override + * is in place. This is tested by setting a boolean flag in a field of the + * test class so it can be checked to confirm that the createTest method was + * called. + */ + public static class CreateTestDefersToNoArgCreateTestRunner extends BlockJUnit4ClassRunner { + public CreateTestDefersToNoArgCreateTestRunner(final Class klass) throws InitializationError { + super(klass); + + assert(klass.equals(CreateTestDefersToNoArgCreateTestTest.class)); + } + + @Override + protected Object createTest() { + final CreateTestDefersToNoArgCreateTestTest obj = new CreateTestDefersToNoArgCreateTestTest(); + + obj.createTestCalled = true; + + return obj; + } + } + + @RunWith(CreateTestDefersToNoArgCreateTestRunner.class) + public static class CreateTestDefersToNoArgCreateTestTest { + public boolean createTestCalled = false; + + @Test + public void testCreateTestCalled() { + assertEquals(true, createTestCalled); + } + } + + @Test + public void createTestDefersToNoArgCreateTest() { + assertThat(testResult(CreateTestDefersToNoArgCreateTestTest.class), isSuccessful()); + } +} diff --git a/src/test/java/org/junit/rules/ClassRulesTest.java b/src/test/java/org/junit/rules/ClassRulesTest.java new file mode 100644 index 000000000000..04d1134f7946 --- /dev/null +++ b/src/test/java/org/junit/rules/ClassRulesTest.java @@ -0,0 +1,251 @@ +/** + * Created Oct 19, 2009 + */ +package org.junit.rules; + +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.isSuccessful; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.ClassRule; +import org.junit.Test; +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); + } + + private static final List orderList = new LinkedList(); + + private static class OrderTestRule implements TestRule { + private String name; + + public OrderTestRule(String name) { + this.name = name; + } + + public Statement apply(final Statement base, final Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + orderList.add(name); + base.evaluate(); + } + }; + } + } + + ; + + public static class UsesFieldAndMethodRule { + @ClassRule + public static OrderTestRule orderMethod() { + return new OrderTestRule("orderMethod"); + } + + @ClassRule + public static OrderTestRule orderField = new OrderTestRule("orderField"); + + @Test + public void foo() { + assertEquals("orderField", orderList.get(0)); + assertEquals("orderMethod", orderList.get(1)); + } + } + + @Test + public void usesFieldAndMethodRule() { + orderList.clear(); + assertThat(testResult(UsesFieldAndMethodRule.class), isSuccessful()); + } + + + public static class MethodExampleTestWithClassRule { + private static Counter counter = new Counter(); + + @ClassRule + public static Counter getCounter() { + return counter; + } + + @Test + public void firstTest() { + assertEquals(1, counter.count); + } + + @Test + public void secondTest() { + assertEquals(1, counter.count); + } + } + + @Test + public void methodRuleIsAppliedOnce() { + MethodExampleTestWithClassRule.counter.count = 0; + JUnitCore.runClasses(MethodExampleTestWithClassRule.class); + assertEquals(1, MethodExampleTestWithClassRule.counter.count); + } + + public static class MethodSubclassOfTestWithClassRule extends + MethodExampleTestWithClassRule { + + } + + @Test + public void methodRuleIsIntroducedAndEvaluatedOnSubclass() { + MethodExampleTestWithClassRule.counter.count = 0; + JUnitCore.runClasses(MethodSubclassOfTestWithClassRule.class); + assertEquals(1, MethodExampleTestWithClassRule.counter.count); + } + + public static class MethodExampleTestWithCustomClassRule { + private static CustomCounter counter = new CustomCounter(); + + @ClassRule + public static CustomCounter getCounter() { + return counter; + } + + @Test + public void firstTest() { + assertEquals(1, counter.count); + } + + @Test + public void secondTest() { + assertEquals(1, counter.count); + } + } + + + @Test + public void methodCustomRuleIsAppliedOnce() { + MethodExampleTestWithCustomClassRule.counter.count = 0; + Result result = JUnitCore.runClasses(MethodExampleTestWithCustomClassRule.class); + assertTrue(result.wasSuccessful()); + assertEquals(1, MethodExampleTestWithCustomClassRule.counter.count); + } + + public static class CallMethodOnlyOnceRule { + static int countOfMethodCalls = 0; + + private static class Dummy implements TestRule { + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + base.evaluate(); + } + + ; + }; + } + } + + @ClassRule + public static Dummy both() { + countOfMethodCalls++; + return new Dummy(); + } + + @Test + public void onlyOnce() { + assertEquals(1, countOfMethodCalls); + } + } + + @Test + public void testCallMethodOnlyOnceRule() { + CallMethodOnlyOnceRule.countOfMethodCalls = 0; + assertTrue(JUnitCore.runClasses(CallMethodOnlyOnceRule.class).wasSuccessful()); + } +} diff --git a/src/test/java/org/junit/rules/DisableOnDebugTest.java b/src/test/java/org/junit/rules/DisableOnDebugTest.java new file mode 100644 index 000000000000..d61db9e528db --- /dev/null +++ b/src/test/java/org/junit/rules/DisableOnDebugTest.java @@ -0,0 +1,164 @@ +package org.junit.rules; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runners.model.Statement; + +public class DisableOnDebugTest { + private static final List WITHOUT_DEBUG_ARGUMENTS = Collections + .emptyList(); + + private static final List PRE_JAVA5_DEBUG_ARGUMENTS = Arrays + .asList("-Xdebug", + "-Xrunjdwp:transport=dt_socket,server=y,address=8000"); + + private static final List PRE_JAVA5_DEBUG_ARGUMENTS_IN_REVERSE_ORDER = Arrays + .asList("-Xrunjdwp:transport=dt_socket,server=y,address=8000", + "-Xdebug"); + + private static final List POST_JAVA5_DEBUG_ARGUMENTS = Arrays + .asList("-agentlib:jdwp=transport=dt_socket,server=y,address=8000"); + + /** + * Nasty rule that always fails + */ + private static class FailOnExecution implements TestRule { + + public Statement apply(Statement base, + Description description) { + return new Statement() { + + @Override + public void evaluate() throws Throwable { + throw new AssertionError(); + } + }; + } + + } + + public static abstract class AbstractDisableOnDebugTest { + + @Rule + public TestRule failOnExecution; + + public AbstractDisableOnDebugTest(List arguments) { + this.failOnExecution = new DisableOnDebug(new FailOnExecution(), + arguments); + } + + @Test + public void test() { + } + } + + public static class PreJava5DebugArgumentsTest extends + AbstractDisableOnDebugTest { + + public PreJava5DebugArgumentsTest() { + super(PRE_JAVA5_DEBUG_ARGUMENTS); + } + + } + + public static class PreJava5DebugArgumentsReversedTest extends + AbstractDisableOnDebugTest { + + public PreJava5DebugArgumentsReversedTest() { + super(PRE_JAVA5_DEBUG_ARGUMENTS_IN_REVERSE_ORDER); + } + + } + + public static class PostJava5DebugArgumentsTest extends + AbstractDisableOnDebugTest { + + public PostJava5DebugArgumentsTest() { + super(POST_JAVA5_DEBUG_ARGUMENTS); + } + + } + + public static class WithoutDebugArgumentsTest extends + AbstractDisableOnDebugTest { + + public WithoutDebugArgumentsTest() { + super(WITHOUT_DEBUG_ARGUMENTS); + } + + } + + @Test + public void givenPreJava5DebugArgumentsIsDebuggingShouldReturnTrue() { + DisableOnDebug subject = new DisableOnDebug( + new FailOnExecution(), PRE_JAVA5_DEBUG_ARGUMENTS); + assertTrue("Should be debugging", subject.isDebugging()); + } + + @Test + public void givenPreJava5DebugArgumentsInReverseIsDebuggingShouldReturnTrue() { + DisableOnDebug subject = new DisableOnDebug( + new FailOnExecution(), + PRE_JAVA5_DEBUG_ARGUMENTS_IN_REVERSE_ORDER); + assertTrue("Should be debugging", subject.isDebugging()); + } + + @Test + public void givenPostJava5DebugArgumentsIsDebuggingShouldReturnTrue() { + DisableOnDebug subject = new DisableOnDebug( + new FailOnExecution(), POST_JAVA5_DEBUG_ARGUMENTS); + assertTrue("Should be debugging", subject.isDebugging()); + } + + @Test + public void givenArgumentsWithoutDebugFlagsIsDebuggingShouldReturnFalse() { + DisableOnDebug subject = new DisableOnDebug( + new FailOnExecution(), WITHOUT_DEBUG_ARGUMENTS); + Assert.assertFalse("Should not be debugging", subject.isDebugging()); + } + + @Test + public void whenRunWithPreJava5DebugArgumentsTestShouldFail() { + JUnitCore core = new JUnitCore(); + Result result = core.run(PreJava5DebugArgumentsTest.class); + assertEquals("Should run the test", 1, result.getRunCount()); + assertEquals("Test should not have failed", 0, result.getFailureCount()); + } + + @Test + public void whenRunWithPreJava5DebugArgumentsInReverseOrderTestShouldFail() { + JUnitCore core = new JUnitCore(); + Result result = core + .run(PreJava5DebugArgumentsReversedTest.class); + assertEquals("Should run the test", 1, result.getRunCount()); + assertEquals("Test should not have failed", 0, result.getFailureCount()); + } + + @Test + public void whenRunWithPostJava5DebugArgumentsTestShouldFail() { + JUnitCore core = new JUnitCore(); + Result result = core.run(PostJava5DebugArgumentsTest.class); + assertEquals("Should run the test", 1, result.getRunCount()); + assertEquals("Test should not have failed", 0, result.getFailureCount()); + } + + @Test + public void whenRunWithoutDebugFlagsTestShouldPass() { + JUnitCore core = new JUnitCore(); + Result result = core.run(WithoutDebugArgumentsTest.class); + assertEquals("Should run the test", 1, result.getRunCount()); + assertEquals("Test should have failed", 1, result.getFailureCount()); + } + +} diff --git a/src/test/java/org/junit/rules/EventCollector.java b/src/test/java/org/junit/rules/EventCollector.java new file mode 100644 index 000000000000..3e024e8f9494 --- /dev/null +++ b/src/test/java/org/junit/rules/EventCollector.java @@ -0,0 +1,191 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.core.IsEqual.equalTo; + +import java.util.ArrayList; +import java.util.List; + +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.runner.Description; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + +class EventCollector extends RunListener { + static Matcher everyTestRunSuccessful() { + return allOf(hasNoFailure(), hasNoAssumptionFailure()); + } + + private static Matcher hasNumberOfFailures( + final int numberOfFailures) { + return new TypeSafeMatcher() { + @Override + public boolean matchesSafely(EventCollector item) { + return item.fFailures.size() == numberOfFailures; + } + + public void describeTo(org.hamcrest.Description description) { + description.appendText("has "); + description.appendValue(numberOfFailures); + description.appendText(" failures"); + } + + @Override + protected void describeMismatchSafely(EventCollector item, + org.hamcrest.Description description) { + description.appendValue(item.fFailures.size()); + description.appendText(" failures"); + } + }; + } + + static Matcher hasSingleFailure() { + return hasNumberOfFailures(1); + } + + static Matcher hasNoFailure() { + return hasNumberOfFailures(0); + } + + private static Matcher hasNumberOfAssumptionFailures( + final int numberOfFailures) { + return new TypeSafeMatcher() { + @Override + public boolean matchesSafely(EventCollector item) { + return item.fAssumptionFailures.size() == numberOfFailures; + } + + public void describeTo(org.hamcrest.Description description) { + description.appendText("has "); + description.appendValue(numberOfFailures); + description.appendText(" assumption failures"); + } + }; + } + + static Matcher hasSingleAssumptionFailure() { + return hasNumberOfAssumptionFailures(1); + } + + static Matcher hasNoAssumptionFailure() { + return hasNumberOfAssumptionFailures(0); + } + + static Matcher hasSingleFailureWithMessage(String message) { + return hasSingleFailureWithMessage(equalTo(message)); + } + + static Matcher hasSingleFailureWithMessage( + final Matcher messageMatcher) { + return new TypeSafeMatcher() { + @Override + public boolean matchesSafely(EventCollector item) { + return hasSingleFailure().matches(item) + && messageMatcher.matches(item.fFailures.get(0) + .getMessage()); + } + + public void describeTo(org.hamcrest.Description description) { + description.appendText("has single failure with message "); + messageMatcher.describeTo(description); + } + + @Override + protected void describeMismatchSafely(EventCollector item, + org.hamcrest.Description description) { + description.appendText("was "); + hasSingleFailure().describeMismatch(item, description); + description.appendText(": "); + boolean first= true; + for (Failure f : item.fFailures) { + if (!first) { + description.appendText(" ,"); + } + description.appendText("'"); + description.appendText(f.getMessage()); + description.appendText("'"); + first= false; + } + } + }; + } + + static Matcher failureIs(final Matcher exceptionMatcher) { + return new TypeSafeMatcher() { + @Override + public boolean matchesSafely(EventCollector item) { + for (Failure f : item.fFailures) { + return exceptionMatcher.matches(f.getException()); + } + return false; + } + + public void describeTo(org.hamcrest.Description description) { + description.appendText("failure is "); + exceptionMatcher.describeTo(description); + } + }; + } + + private final List fTestRunsStarted = new ArrayList(); + + private final List fTestRunsFinished = new ArrayList(); + + private final List fTestsStarted = new ArrayList(); + + private final List fTestsFinished = new ArrayList(); + + private final List fFailures = new ArrayList(); + + private final List fAssumptionFailures = new ArrayList(); + + private final List fTestsIgnored = new ArrayList(); + + @Override + public void testRunStarted(Description description) throws Exception { + fTestRunsStarted.add(description); + } + + @Override + public void testRunFinished(Result result) throws Exception { + fTestRunsFinished.add(result); + } + + @Override + public void testStarted(Description description) throws Exception { + fTestsStarted.add(description); + } + + @Override + public void testFinished(Description description) throws Exception { + fTestsFinished.add(description); + } + + @Override + public void testFailure(Failure failure) throws Exception { + fFailures.add(failure); + } + + @Override + public void testAssumptionFailure(Failure failure) { + fAssumptionFailures.add(failure); + } + + @Override + public void testIgnored(Description description) throws Exception { + fTestsIgnored.add(description); + } + + @Override + public String toString() { + return fTestRunsStarted.size() + " test runs started, " + + fTestRunsFinished.size() + " test runs finished, " + + fTestsStarted.size() + " tests started, " + + fTestsFinished.size() + " tests finished, " + + fFailures.size() + " failures, " + + fAssumptionFailures.size() + " assumption failures, " + + fTestsIgnored.size() + " tests ignored"; + } +} diff --git a/src/test/java/org/junit/rules/ExpectedExceptionTest.java b/src/test/java/org/junit/rules/ExpectedExceptionTest.java new file mode 100644 index 000000000000..fc548a81a155 --- /dev/null +++ b/src/test/java/org/junit/rules/ExpectedExceptionTest.java @@ -0,0 +1,367 @@ +package org.junit.rules; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.any; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; +import static org.junit.rules.ExpectedException.none; +import static org.junit.rules.EventCollector.everyTestRunSuccessful; +import static org.junit.rules.EventCollector.hasSingleAssumptionFailure; +import static org.junit.rules.EventCollector.hasSingleFailure; +import static org.junit.rules.EventCollector.hasSingleFailureWithMessage; + +import java.util.Collection; + +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matcher; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public class ExpectedExceptionTest { + private static final String ARBITRARY_MESSAGE = "arbitrary message"; + + @Parameters(name= "{0}") + public static Collection testsWithEventMatcher() { + return asList(new Object[][]{ + {EmptyTestExpectingNoException.class, everyTestRunSuccessful()}, + {ThrowExceptionWithExpectedType.class, + everyTestRunSuccessful()}, + {ThrowExceptionWithExpectedPartOfMessage.class, + everyTestRunSuccessful()}, + { + ThrowExceptionWithWrongType.class, + hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException"))}, + { + HasWrongMessage.class, + hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n" + + " but: message was \"actualMessage\""))}, + { + ThrowNoExceptionButExpectExceptionWithType.class, + hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException")}, + {WronglyExpectsExceptionMessage.class, hasSingleFailure()}, + {ExpectsSubstring.class, everyTestRunSuccessful()}, + { + ExpectsSubstringNullMessage.class, + hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\""))}, + {ExpectsMessageMatcher.class, everyTestRunSuccessful()}, + { + ExpectedMessageMatcherFails.class, + hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\""))}, + {ExpectsMatcher.class, everyTestRunSuccessful()}, + {ExpectAssertionErrorWhichIsNotThrown.class, hasSingleFailure()}, + {FailedAssumptionAndExpectException.class, + hasSingleAssumptionFailure()}, + {FailBeforeExpectingException.class, + hasSingleFailureWithMessage(ARBITRARY_MESSAGE)}, + { + ExpectsMultipleMatchers.class, + hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")"))}, + {ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful()}, + {ThrowExpectedNullCause.class, everyTestRunSuccessful()}, + { + ThrowUnexpectedCause.class, + hasSingleFailureWithMessage(CoreMatchers.allOf( + startsWith("\nExpected: ("), + containsString("exception with cause is "), + containsString("cause was "), + containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"), + containsString("Caused by: java.lang.NullPointerException: an unexpected cause")))}, + { + UseNoCustomMessage.class, + hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.IllegalArgumentException") }, + { + UseCustomMessageWithoutPlaceHolder.class, + hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, + { + UseCustomMessageWithPlaceHolder.class, + hasSingleFailureWithMessage(ARBITRARY_MESSAGE + + " - an instance of java.lang.IllegalArgumentException") } + }); + } + + private final Class classUnderTest; + + private final Matcher matcher; + + public ExpectedExceptionTest(Class classUnderTest, + Matcher matcher) { + this.classUnderTest = classUnderTest; + this.matcher = matcher; + } + + @Test + public void runTestAndVerifyResult() { + EventCollector collector = new EventCollector(); + JUnitCore core = new JUnitCore(); + core.addListener(collector); + core.run(classUnderTest); + assertThat(collector, matcher); + } + + public static class EmptyTestExpectingNoException { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsNothing() { + } + } + + public static class ThrowExceptionWithExpectedType { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsNullPointerException() { + thrown.expect(NullPointerException.class); + throw new NullPointerException(); + } + } + + public static class ThrowExceptionWithExpectedPartOfMessage { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsNullPointerExceptionWithMessage() { + thrown.expect(NullPointerException.class); + thrown.expectMessage(ARBITRARY_MESSAGE); + throw new NullPointerException(ARBITRARY_MESSAGE + "something else"); + } + } + + public static class ThrowExceptionWithWrongType { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsNullPointerException() { + thrown.expect(NullPointerException.class); + throw new IllegalArgumentException(); + } + } + + public static class HasWrongMessage { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsNullPointerException() { + thrown.expectMessage("expectedMessage"); + throw new IllegalArgumentException("actualMessage"); + } + } + + public static class ThrowNoExceptionButExpectExceptionWithType { + @Rule + public ExpectedException thrown = none(); + + @Test + public void doesntThrowNullPointerException() { + thrown.expect(NullPointerException.class); + } + } + + public static class WronglyExpectsExceptionMessage { + @Rule + public ExpectedException thrown = none(); + + @Test + public void doesntThrowAnything() { + thrown.expectMessage("anything!"); + } + } + + public static class ExpectsSubstring { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsMore() { + thrown.expectMessage("anything!"); + throw new NullPointerException( + "This could throw anything! (as long as it has the right substring)"); + } + } + + public static class ExpectsSubstringNullMessage { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsMore() { + thrown.expectMessage("anything!"); + throw new NullPointerException(); + } + } + + public static class ExpectsMessageMatcher { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsMore() { + thrown.expectMessage(startsWith(ARBITRARY_MESSAGE)); + throw new NullPointerException(ARBITRARY_MESSAGE + "!"); + } + } + + public static class ExpectedMessageMatcherFails { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsMore() { + thrown.expectMessage(equalTo("Wrong start")); + throw new NullPointerException("Back!"); + } + } + + public static class ExpectsMatcher { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsMore() { + thrown.expect(any(Exception.class)); + throw new NullPointerException("Ack!"); + } + } + + public static class ExpectsMultipleMatchers { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwsMore() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Ack!"); + throw new NullPointerException("Ack!"); + } + } + + //https://github.com/junit-team/junit4/pull/583 + public static class ExpectAssertionErrorWhichIsNotThrown { + @Rule + public ExpectedException thrown = none(); + + @Test + public void fails() { + thrown.expect(AssertionError.class); + } + } + + public static class FailBeforeExpectingException { + @Rule + public ExpectedException thrown = none(); + + @Test + public void fails() { + fail(ARBITRARY_MESSAGE); + thrown.expect(IllegalArgumentException.class); + } + } + + public static class FailedAssumptionAndExpectException { + @Rule + public ExpectedException thrown = none(); + + @Test + public void failedAssumption() { + assumeTrue(false); + thrown.expect(NullPointerException.class); + } + } + + public static class ThrowExceptionWithMatchingCause { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwExceptionWithMatchingCause() { + NullPointerException expectedCause = new NullPointerException("expected cause"); + + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Ack!"); + thrown.expectCause(is(expectedCause)); + + throw new IllegalArgumentException("Ack!", expectedCause); + } + } + + public static class ThrowExpectedNullCause { + @Rule + public ExpectedException thrown = none(); + + @Test + public void throwExpectedNullCause() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Ack!"); + thrown.expectCause(nullValue(Throwable.class)); + + throw new IllegalArgumentException("Ack!"); + } + } + + public static class ThrowUnexpectedCause { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void throwWithCause() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Ack!"); + thrown.expectCause(is(new NullPointerException("expected cause"))); + + throw new IllegalArgumentException("Ack!", new NullPointerException("an unexpected cause")); + } + } + + public static class UseNoCustomMessage { + + @Rule + public ExpectedException thrown= ExpectedException.none(); + + @Test + public void noThrow() { + thrown.expect(IllegalArgumentException.class); + } + } + + public static class UseCustomMessageWithPlaceHolder { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void noThrow() { + thrown.expect(IllegalArgumentException.class); + thrown.reportMissingExceptionWithMessage(ARBITRARY_MESSAGE + + " - %s"); + } + } + + public static class UseCustomMessageWithoutPlaceHolder { + + @Rule + public ExpectedException thrown= ExpectedException.none(); + + @Test + public void noThrow() { + thrown.expect(IllegalArgumentException.class); + thrown.reportMissingExceptionWithMessage(ARBITRARY_MESSAGE); + } + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/rules/ExternalResourceRuleTest.java b/src/test/java/org/junit/rules/ExternalResourceRuleTest.java new file mode 100644 index 000000000000..97b7193500e1 --- /dev/null +++ b/src/test/java/org/junit/rules/ExternalResourceRuleTest.java @@ -0,0 +1,75 @@ +package org.junit.rules; + +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +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.isSuccessful; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.internal.runners.statements.Fail; +import org.junit.runner.Description; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +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); + } + + @Test + public void shouldThrowMultipleFailureExceptionWhenTestFailsAndClosingResourceFails() throws Throwable { + // given + ExternalResource resourceRule = new ExternalResource() { + @Override + protected void after() { + throw new RuntimeException("simulating resource tear down failure"); + } + }; + Statement failingTest = new Fail(new RuntimeException("simulated test failure")); + Description dummyDescription = Description.createTestDescription( + "dummy test class name", "dummy test name"); + + try { + resourceRule.apply(failingTest, dummyDescription).evaluate(); + fail("ExternalResource should throw"); + } catch (MultipleFailureException e) { + assertThat(e.getMessage(), allOf( + containsString("simulated test failure"), + containsString("simulating resource tear down failure") + )); + } + } +} diff --git a/src/test/java/org/junit/rules/LoggingTestWatcher.java b/src/test/java/org/junit/rules/LoggingTestWatcher.java new file mode 100644 index 000000000000..f1c0ddafba9b --- /dev/null +++ b/src/test/java/org/junit/rules/LoggingTestWatcher.java @@ -0,0 +1,37 @@ +package org.junit.rules; + +import org.junit.AssumptionViolatedException; +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 skipped(AssumptionViolatedException e, Description description) { + log.append("skipped "); + } + + @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/src/test/java/org/junit/rules/MethodRulesTest.java b/src/test/java/org/junit/rules/MethodRulesTest.java new file mode 100644 index 000000000000..e2fb66545e26 --- /dev/null +++ b/src/test/java/org/junit/rules/MethodRulesTest.java @@ -0,0 +1,404 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +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 org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +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; + + 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(); + } + }; + } + } + + public static class MultipleRuleTest { + + @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 { + @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()); + } + + public static class HasMethodReturningMethodRule { + private MethodRule methodRule = 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(); + } + }; + } + }; + + @Rule + public MethodRule methodRule() { + return methodRule; + } + + @Test + public void doNothing() { + + } + } + + /** + * If there are any public methods annotated with @Rule returning a {@link MethodRule} + * then it should also be run. + * + *

      This case has been added with + * Issue #589 - + * Support @Rule for methods works only for TestRule but not for MethodRule + */ + @Test + public void runsMethodRuleThatIsReturnedByMethod() { + wasRun = false; + JUnitCore.runClasses(HasMethodReturningMethodRule.class); + assertTrue(wasRun); + } + + public static class HasMultipleMethodsReturningMethodRule { + @Rule + public Increment methodRule1() { + return new Increment(); + } + + @Rule + public Increment methodRule2() { + return new Increment(); + } + + @Test + public void doNothing() { + + } + } + + /** + * If there are multiple public methods annotated with @Rule returning a {@link MethodRule} + * then all the rules returned should be run. + * + *

      This case has been added with + * Issue #589 - + * Support @Rule for methods works only for TestRule but not for MethodRule + */ + @Test + public void runsAllMethodRulesThatAreReturnedByMethods() { + runCount = 0; + JUnitCore.runClasses(HasMultipleMethodsReturningMethodRule.class); + assertEquals(2, runCount); + } + + + public static class CallsMethodReturningRuleOnlyOnce { + int callCount = 0; + + private static class Dummy implements MethodRule { + public Statement apply(final Statement base, FrameworkMethod method, Object target) { + return new Statement() { + + @Override + public void evaluate() throws Throwable { + base.evaluate(); + } + }; + } + }; + + + @Rule + public MethodRule methodRule() { + callCount++; + return new Dummy(); + } + + @Test + public void doNothing() { + assertEquals(1, callCount); + } + } + + /** + * If there are any public methods annotated with @Rule returning a {@link MethodRule} + * then method should be called only once. + * + *

      This case has been added with + * Issue #589 - + * Support @Rule for methods works only for TestRule but not for MethodRule + */ + @Test + public void callsMethodReturningRuleOnlyOnce() { + assertTrue(JUnitCore.runClasses(CallsMethodReturningRuleOnlyOnce.class).wasSuccessful()); + } +} diff --git a/src/test/java/org/junit/rules/NameRulesTest.java b/src/test/java/org/junit/rules/NameRulesTest.java new file mode 100644 index 000000000000..9ae45ff217a8 --- /dev/null +++ b/src/test/java/org/junit/rules/NameRulesTest.java @@ -0,0 +1,50 @@ +package org.junit.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.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/src/test/java/org/junit/rules/RuleChainTest.java b/src/test/java/org/junit/rules/RuleChainTest.java new file mode 100644 index 000000000000..914b6a9088c5 --- /dev/null +++ b/src/test/java/org/junit/rules/RuleChainTest.java @@ -0,0 +1,96 @@ +package org.junit.rules; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.experimental.results.PrintableResult.testResult; +import static org.junit.rules.RuleChain.outerRule; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.internal.Throwables; +import org.junit.runner.Description; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; + +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); + } + + @Test + public void aroundShouldNotAllowNullRules() { + RuleChain chain = RuleChain.emptyRuleChain(); + try { + chain.around(null); + fail("around() should not allow null rules"); + } catch (NullPointerException e) { + assertThat(e.getMessage(), equalTo("The enclosed rule must not be null")); + } + } + + public static class RuleChainWithNullRules { + @Rule + public final RuleChain chain = outerRule(new LoggingRule("outer rule")) + .around(null); + + @Test + public void example() {} + } + + @Test + public void whenRuleChainHasNullRuleTheStacktraceShouldPointToIt() { + Result result = JUnitCore.runClasses(RuleChainWithNullRules.class); + + assertThat(result.getFailures().size(), equalTo(1)); + String stacktrace = Throwables.getStacktrace(result.getFailures().get(0).getException()); + assertThat(stacktrace, containsString("\tat org.junit.rules.RuleChainTest$RuleChainWithNullRules.(RuleChainTest.java:")); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/rules/RuleMemberValidatorTest.java b/src/test/java/org/junit/rules/RuleMemberValidatorTest.java new file mode 100644 index 000000000000..5fc964d725cb --- /dev/null +++ b/src/test/java/org/junit/rules/RuleMemberValidatorTest.java @@ -0,0 +1,356 @@ +package org.junit.rules; + +import static org.junit.Assert.assertEquals; +import static org.junit.internal.runners.rules.RuleMemberValidator.CLASS_RULE_METHOD_VALIDATOR; +import static org.junit.internal.runners.rules.RuleMemberValidator.CLASS_RULE_VALIDATOR; +import static org.junit.internal.runners.rules.RuleMemberValidator.RULE_METHOD_VALIDATOR; +import static org.junit.internal.runners.rules.RuleMemberValidator.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.runners.model.FrameworkMethod; +import org.junit.runners.model.Statement; +import org.junit.runners.model.TestClass; + +public class RuleMemberValidatorTest { + 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 acceptStaticTestRuleThatIsAlsoClassRule() { + TestClass target = new TestClass(TestWithStaticClassAndTestRule.class); + CLASS_RULE_VALIDATOR.validate(target, errors); + assertNumberOfErrors(0); + } + + public static class TestWithStaticClassAndTestRule { + @ClassRule + @Rule + public static TestRule temporaryFolder = new TemporaryFolder(); + } + + @Test + public void rejectClassRuleInNonPublicClass() { + TestClass target = new TestClass(NonPublicTestWithClassRule.class); + CLASS_RULE_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'temporaryFolder' must be declared in a public class."); + } + + static class NonPublicTestWithClassRule { + @ClassRule + public static TestRule temporaryFolder = new TemporaryFolder(); + } + + /** + * If there is any property annotated with @ClassRule then it must implement + * {@link TestRule} + * + *

      This case has been added with + * Issue #1019 + */ + @Test + public void rejectClassRuleThatIsImplemetationOfMethodRule() { + TestClass target = new TestClass(TestWithClassRuleIsImplementationOfMethodRule.class); + CLASS_RULE_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'classRule' must implement TestRule."); + } + + public static class TestWithClassRuleIsImplementationOfMethodRule { + @ClassRule + public static MethodRule classRule = new MethodRule() { + + public Statement apply(Statement base, FrameworkMethod method, Object target) { + return base; + } + }; + } + + /** + * If there is any method annotated with @ClassRule then it must return an + * implementation of {@link TestRule} + * + *

      This case has been added with + * Issue #1019 + */ + @Test + public void rejectClassRuleThatReturnsImplementationOfMethodRule() { + TestClass target = new TestClass(TestWithClassRuleMethodThatReturnsMethodRule.class); + CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'methodRule' must return an implementation of TestRule."); + } + + public static class TestWithClassRuleMethodThatReturnsMethodRule { + @ClassRule + public static MethodRule methodRule() { + return new MethodRule() { + + public Statement apply(Statement base, FrameworkMethod method, Object target) { + return base; + } + }; + } + } + + /** + * If there is any property annotated with @ClassRule then it must implement + * {@link TestRule} + * + *

      This case has been added with + * Issue #1019 + */ + @Test + public void rejectClassRuleIsAnArbitraryObject() throws Exception { + TestClass target = new TestClass(TestWithClassRuleIsAnArbitraryObject.class); + CLASS_RULE_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'arbitraryObject' must implement TestRule."); + } + + public static class TestWithClassRuleIsAnArbitraryObject { + @ClassRule + public static Object arbitraryObject = 1; + } + + /** + * If there is any method annotated with @ClassRule then it must return an + * implementation of {@link TestRule} + * + *

      This case has been added with + * Issue #1019 + */ + @Test + public void rejectClassRuleMethodReturnsAnArbitraryObject() throws Exception { + TestClass target = new TestClass(TestWithClassRuleMethodReturnsAnArbitraryObject.class); + CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'arbitraryObject' must return an implementation of TestRule."); + } + + public static class TestWithClassRuleMethodReturnsAnArbitraryObject { + @ClassRule + public static Object arbitraryObject() { + return 1; + } + } + + @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 rejectStaticTestRule() { + TestClass target = new TestClass(TestWithStaticTestRule.class); + RULE_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @Rule 'temporaryFolder' must not be static or it must be annotated with @ClassRule."); + } + + public static class TestWithStaticTestRule { + @Rule + public static TestRule temporaryFolder = new TemporaryFolder(); + } + + @Test + public void rejectStaticMethodRule() { + TestClass target = new TestClass(TestWithStaticMethodRule.class); + RULE_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @Rule 'someMethodRule' must not be static."); + } + + public static class TestWithStaticMethodRule { + @Rule + public static MethodRule someMethodRule = new SomeMethodRule(); + } + + @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; + } + + @Test + public void methodRejectProtectedClassRule() { + TestClass target = new TestClass(MethodTestWithProtectedClassRule.class); + CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'getTemporaryFolder' must be public."); + } + + public static class MethodTestWithProtectedClassRule { + @ClassRule + protected static TestRule getTemporaryFolder() { + return new TemporaryFolder(); + } + } + + @Test + public void methodRejectNonStaticClassRule() { + TestClass target = new TestClass(MethodTestWithNonStaticClassRule.class); + CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @ClassRule 'getTemporaryFolder' must be static."); + } + + public static class MethodTestWithNonStaticClassRule { + @ClassRule + public TestRule getTemporaryFolder() { + return new TemporaryFolder(); + } + } + + @Test + public void acceptMethodStaticTestRuleThatIsAlsoClassRule() { + TestClass target = new TestClass(MethodTestWithStaticClassAndTestRule.class); + CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); + assertNumberOfErrors(0); + } + + public static class MethodTestWithStaticClassAndTestRule { + @ClassRule + @Rule + public static TestRule getTemporaryFolder() { + return new TemporaryFolder(); + } + } + + @Test + public void acceptMethodNonStaticTestRule() { + TestClass target = new TestClass(TestMethodWithNonStaticTestRule.class); + RULE_METHOD_VALIDATOR.validate(target, errors); + assertNumberOfErrors(0); + } + + public static class TestMethodWithNonStaticTestRule { + @Rule + public TestRule getTemporaryFolder() { + return new TemporaryFolder(); + } + } + + @Test + public void rejectMethodStaticTestRule() { + TestClass target = new TestClass(TestMethodWithStaticTestRule.class); + RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @Rule 'getTemporaryFolder' must not be static or it must be annotated with @ClassRule."); + } + + public static class TestMethodWithStaticTestRule { + @Rule + public static TestRule getTemporaryFolder() { + return new TemporaryFolder(); + } + } + + @Test + public void rejectMethodStaticMethodRule() { + TestClass target = new TestClass(TestMethodWithStaticMethodRule.class); + RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @Rule 'getSomeMethodRule' must not be static."); + } + + public static class TestMethodWithStaticMethodRule { + @Rule + public static MethodRule getSomeMethodRule() { return new SomeMethodRule(); } + } + + @Test + public void methodAcceptMethodRuleMethod() throws Exception { + TestClass target = new TestClass(MethodTestWithMethodRule.class); + RULE_METHOD_VALIDATOR.validate(target, errors); + assertNumberOfErrors(0); + } + + public static class MethodTestWithMethodRule { + @Rule + public MethodRule getTemporaryFolder() { + return new MethodRule() { + public Statement apply(Statement base, FrameworkMethod method, + Object target) { + return null; + } + }; + } + } + + @Test + public void methodRejectArbitraryObjectWithRuleAnnotation() throws Exception { + TestClass target = new TestClass(MethodTestWithArbitraryObjectWithRuleAnnotation.class); + RULE_METHOD_VALIDATOR.validate(target, errors); + assertOneErrorWithMessage("The @Rule 'getArbitraryObject' must return an implementation of MethodRule or TestRule."); + } + + public static class MethodTestWithArbitraryObjectWithRuleAnnotation { + @Rule + public Object getArbitraryObject() { + return 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()); + } + + private static final class SomeMethodRule implements MethodRule { + public Statement apply(Statement base, FrameworkMethod method, Object target) { + return base; + } + } +} diff --git a/src/test/java/org/junit/rules/StopwatchTest.java b/src/test/java/org/junit/rules/StopwatchTest.java new file mode 100644 index 000000000000..18893dd99acd --- /dev/null +++ b/src/test/java/org/junit/rules/StopwatchTest.java @@ -0,0 +1,212 @@ +package org.junit.rules; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.hamcrest.core.Is.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.Assume.assumeTrue; + +import java.util.concurrent.TimeUnit; + +import org.junit.AssumptionViolatedException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.JUnitCore; +import org.junit.runner.Request; +import org.junit.runner.Result; + +/** + * @author tibor17 + * @since 4.12 + */ +public class StopwatchTest { + private static enum TestStatus { SUCCEEDED, FAILED, SKIPPED } + private static Record record; + private static Record finishedRecord; + private static long fakeTimeNanos = 1234; + + private static class Record { + final long duration; + final String name; + final TestStatus status; + + Record() { + this(0, null, null); + } + + Record(long duration, Description description) { + this(duration, null, description); + } + + Record(long duration, TestStatus status, Description description) { + this.duration = duration; + this.status = status; + this.name = description == null ? null : description.getMethodName(); + } + } + + public static abstract class AbstractStopwatchTest { + + /** + * Fake implementation of {@link Stopwatch.Clock} that increments the time + * every time it is asked. + */ + private final Stopwatch.Clock fakeClock = new Stopwatch.Clock() { + @Override + public long nanoTime() { + return fakeTimeNanos++; + } + }; + + protected final Stopwatch stopwatch = new Stopwatch(fakeClock) { + @Override + protected void succeeded(long nanos, Description description) { + StopwatchTest.record = new Record(nanos, TestStatus.SUCCEEDED, description); + simulateTimePassing(1); + } + + @Override + protected void failed(long nanos, Throwable e, Description description) { + StopwatchTest.record = new Record(nanos, TestStatus.FAILED, description); + simulateTimePassing(1); + } + + @Override + protected void skipped(long nanos, AssumptionViolatedException e, Description description) { + StopwatchTest.record = new Record(nanos, TestStatus.SKIPPED, description); + simulateTimePassing(1); + } + + @Override + protected void finished(long nanos, Description description) { + StopwatchTest.finishedRecord = new Record(nanos, description); + } + }; + + private final TestWatcher watcher = new TestWatcher() { + @Override + protected void finished(Description description) { + afterStopwatchRule(); + } + }; + + @Rule + public final RuleChain chain = RuleChain + .outerRule(watcher) + .around(stopwatch); + + protected void afterStopwatchRule() { + } + } + + public static class SuccessfulTest extends AbstractStopwatchTest { + @Test + public void successfulTest() { + } + } + + public static class FailedTest extends AbstractStopwatchTest { + @Test + public void failedTest() { + fail(); + } + } + + public static class SkippedTest extends AbstractStopwatchTest { + @Test + public void skippedTest() { + assumeTrue(false); + } + } + + public static class DurationDuringTestTest extends AbstractStopwatchTest { + @Test + public void duration() { + simulateTimePassing(300L); + assertEquals(300L, stopwatch.runtime(MILLISECONDS)); + simulateTimePassing(500L); + assertEquals(800L, stopwatch.runtime(MILLISECONDS)); + } + } + + public static class DurationAfterTestTest extends AbstractStopwatchTest { + @Test + public void duration() { + simulateTimePassing(300L); + assertEquals(300L, stopwatch.runtime(MILLISECONDS)); + } + + @Override + protected void afterStopwatchRule() { + assertEquals(300L, stopwatch.runtime(MILLISECONDS)); + simulateTimePassing(500L); + assertEquals(300L, stopwatch.runtime(MILLISECONDS)); + } + } + + @Before + public void init() { + record = new Record(); + finishedRecord = new Record(); + simulateTimePassing(1L); + } + + private static Result runTest(Class test) { + simulateTimePassing(1L); + JUnitCore junitCore = new JUnitCore(); + return junitCore.run(Request.aClass(test).getRunner()); + } + + private static void simulateTimePassing(long millis) { + fakeTimeNanos += TimeUnit.MILLISECONDS.toNanos(millis); + } + + @Test + public void succeeded() { + Result result = runTest(SuccessfulTest.class); + assertEquals(0, result.getFailureCount()); + assertThat(record.name, is("successfulTest")); + assertThat(record.name, is(finishedRecord.name)); + assertThat(record.status, is(TestStatus.SUCCEEDED)); + assertTrue("timeSpent > 0", record.duration > 0); + assertThat(record.duration, is(finishedRecord.duration)); + } + + @Test + public void failed() { + Result result = runTest(FailedTest.class); + assertEquals(1, result.getFailureCount()); + assertThat(record.name, is("failedTest")); + assertThat(record.name, is(finishedRecord.name)); + assertThat(record.status, is(TestStatus.FAILED)); + assertTrue("timeSpent > 0", record.duration > 0); + assertThat(record.duration, is(finishedRecord.duration)); + } + + @Test + public void skipped() { + Result result = runTest(SkippedTest.class); + assertEquals(0, result.getFailureCount()); + assertThat(record.name, is("skippedTest")); + assertThat(record.name, is(finishedRecord.name)); + assertThat(record.status, is(TestStatus.SKIPPED)); + assertTrue("timeSpent > 0", record.duration > 0); + assertThat(record.duration, is(finishedRecord.duration)); + } + + @Test + public void runtimeDuringTestShouldReturnTimeSinceStart() { + Result result = runTest(DurationDuringTestTest.class); + assertTrue(result.wasSuccessful()); + } + + @Test + public void runtimeAfterTestShouldReturnRunDuration() { + Result result = runTest(DurationAfterTestTest.class); + assertTrue(result.wasSuccessful()); + } +} diff --git a/src/test/java/org/junit/rules/TempFolderRuleTest.java b/src/test/java/org/junit/rules/TempFolderRuleTest.java new file mode 100644 index 000000000000..f7cb5f50150d --- /dev/null +++ b/src/test/java/org/junit/rules/TempFolderRuleTest.java @@ -0,0 +1,246 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.hasItem; +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 java.io.File; +import java.io.IOException; +import java.lang.reflect.Method; +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 testTempFolderLocation() throws IOException { + File folderRoot = folder.getRoot(); + String tmpRoot = System.getProperty("java.io.tmpdir"); + assertTrue(folderRoot.toString().startsWith(tmpRoot)); + } + } + + @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 testUsingTempFolderStringReflection() throws Exception { + String subfolder = "subfolder"; + String filename = "a.txt"; + // force usage of folder.newFolder(String), + // check is available and works, to avoid a potential NoSuchMethodError with non-recompiled code. + Method method = folder.getClass().getMethod("newFolder", new Class[]{String.class}); + createdFiles[0] = (File) method.invoke(folder, subfolder); + new File(createdFiles[0], filename).createNewFile(); + + File expectedFile = new File(folder.getRoot(), join(subfolder, filename)); + + assertTrue(expectedFile.exists()); + } + + @Test + public void testUsingTempFolderString() throws IOException { + String subfolder = "subfolder"; + String filename = "a.txt"; + // this uses newFolder(String), ensure that a single String works + 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()); + } + + public static class NameClashes { + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + @Test + public void fileWithFileClash() throws IOException { + folder.newFile("something.txt"); + folder.newFile("something.txt"); + } + + @Test + public void fileWithFolderTest() throws IOException { + folder.newFolder("dummy"); + folder.newFile("dummy"); + } + } + + @Test + public void nameClashesResultInTestFailures() { + assertThat(testResult(NameClashes.class), failureCountIs(2)); + } + + 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() throws IOException { + 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/src/test/java/org/junit/rules/TemporaryFolderRuleAssuredDeletionTest.java b/src/test/java/org/junit/rules/TemporaryFolderRuleAssuredDeletionTest.java new file mode 100644 index 000000000000..e6184673fd3e --- /dev/null +++ b/src/test/java/org/junit/rules/TemporaryFolderRuleAssuredDeletionTest.java @@ -0,0 +1,77 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.containsString; +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 java.io.IOException; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.results.PrintableResult; + +public class TemporaryFolderRuleAssuredDeletionTest { + + private static class StubTemporaryFolder extends TemporaryFolder { + private StubTemporaryFolder(Builder builder) { + super(builder); + } + + /** + * Don't need to create as we are overriding deletion. + */ + @Override + public void create() throws IOException { + } + + /** + * Simulates failure to clean-up temporary folder. + */ + @Override + protected boolean tryDelete() { + return false; + } + + public static Builder builder() { + return new TemporaryFolder.Builder() { + @Override + public TemporaryFolder build() { + return new StubTemporaryFolder(this); + } + }; + } + } + + public static class HasTempFolderWithAssuredDeletion { + @Rule public TemporaryFolder folder = StubTemporaryFolder.builder() + .assureDeletion() + .build(); + + @Test + public void alwaysPasses() { + } + } + + @Test + public void testStrictVerificationFailure() { + PrintableResult result = testResult(HasTempFolderWithAssuredDeletion.class); + assertThat(result, failureCountIs(1)); + assertThat(result.toString(), containsString("Unable to clean up temporary folder")); + } + + public static class HasTempFolderWithoutAssuredDeletion { + @Rule public TemporaryFolder folder = StubTemporaryFolder.builder().build(); + + @Test + public void alwaysPasses() { + } + } + + @Test + public void testStrictVerificationSuccess() { + PrintableResult result = testResult(HasTempFolderWithoutAssuredDeletion.class); + assertThat(result, isSuccessful()); + } +} diff --git a/src/test/java/org/junit/rules/TemporaryFolderUsageTest.java b/src/test/java/org/junit/rules/TemporaryFolderUsageTest.java new file mode 100644 index 000000000000..7b7e525c10a0 --- /dev/null +++ b/src/test/java/org/junit/rules/TemporaryFolderUsageTest.java @@ -0,0 +1,215 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +/** + * TemporaryFolderUsageTest provides tests for API usage correctness + * and ensure implementation symmetry of public methods against a root folder. + */ +public class TemporaryFolderUsageTest { + + private TemporaryFolder tempFolder; + + @Rule + public final ExpectedException thrown = ExpectedException.none(); + + @Before + public void setUp() { + tempFolder = new TemporaryFolder(); + } + + @After + public void tearDown() { + tempFolder.delete(); + } + + @Test(expected = IllegalStateException.class) + public void getRootShouldThrowIllegalStateExceptionIfCreateWasNotInvoked() { + new TemporaryFolder().getRoot(); + } + + @Test(expected = IllegalStateException.class) + public void newFileThrowsIllegalStateExceptionIfCreateWasNotInvoked() + throws IOException { + new TemporaryFolder().newFile(); + } + + @Test(expected = IllegalStateException.class) + public void newFileWithGivenNameThrowsIllegalStateExceptionIfCreateWasNotInvoked() + throws IOException { + new TemporaryFolder().newFile("MyFile.txt"); + } + + @Test + public void newFileWithGivenFilenameThrowsIllegalArgumentExceptionIfFileExists() throws IOException { + tempFolder.create(); + tempFolder.newFile("MyFile.txt"); + + thrown.expect(IOException.class); + thrown.expectMessage("a file with the name 'MyFile.txt' already exists in the test folder"); + tempFolder.newFile("MyFile.txt"); + } + + @Test(expected = IllegalStateException.class) + public void newFolderThrowsIllegalStateExceptionIfCreateWasNotInvoked() + throws IOException { + new TemporaryFolder().newFolder(); + } + + @Test(expected = IllegalStateException.class) + public void newFolderWithGivenPathThrowsIllegalStateExceptionIfCreateWasNotInvoked() throws IOException { + new TemporaryFolder().newFolder("level1", "level2", "level3"); + } + + @Test + public void newFolderWithGivenFolderThrowsIllegalArgumentExceptionIfFolderExists() throws IOException { + tempFolder.create(); + tempFolder.newFolder("level1"); + + thrown.expect(IOException.class); + thrown.expectMessage("a folder with the name 'level1' already exists"); + tempFolder.newFolder("level1"); + } + + @Test + public void newFolderWithGivenFolderThrowsIOExceptionIfFolderNameConsistsOfMultiplePathComponents() + throws IOException { + tempFolder.create(); + thrown.expect(IOException.class); + thrown.expectMessage("name cannot consist of multiple path components"); + tempFolder.newFolder("temp1/temp2"); + } + + @Test + public void newFolderWithGivenPathThrowsIllegalArgumentExceptionIfPathExists() throws IOException { + tempFolder.create(); + tempFolder.newFolder("level1", "level2", "level3"); + + thrown.expect(IOException.class); + thrown.expectMessage("a folder with the name 'level3' already exists"); + tempFolder.newFolder("level1", "level2", "level3"); + } + + @Test + public void newFolderWithGivenPathThrowsIOExceptionIfFolderNamesConsistOfMultiplePathComponents() + throws IOException { + tempFolder.create(); + thrown.expect(IOException.class); + thrown.expectMessage("name cannot consist of multiple path components"); + tempFolder.newFolder("temp1", "temp2", "temp3/temp4"); + } + + @Test + public void createInitializesRootFolder() throws IOException { + tempFolder.create(); + assertFileExists(tempFolder.getRoot()); + } + + @Test + public void deleteShouldDoNothingIfRootFolderWasNotInitialized() { + tempFolder.delete(); + } + + @Test + public void deleteRemovesRootFolder() throws IOException { + tempFolder.create(); + tempFolder.delete(); + assertFileDoesNotExist(tempFolder.getRoot()); + } + + @Test + public void newRandomFileIsCreatedUnderRootFolder() throws IOException { + tempFolder.create(); + + File f = tempFolder.newFile(); + assertFileExists(f); + assertFileCreatedUnderRootFolder("Random file", f); + } + + @Test + public void newNamedFileIsCreatedUnderRootFolder() throws IOException { + final String fileName = "SampleFile.txt"; + tempFolder.create(); + + File f = tempFolder.newFile(fileName); + + assertFileExists(f); + assertFileCreatedUnderRootFolder("Named file", f); + assertThat("file name", f.getName(), equalTo(fileName)); + } + + @Test + public void newRandomFolderIsCreatedUnderRootFolder() throws IOException { + tempFolder.create(); + + File f = tempFolder.newFolder(); + assertFileExists(f); + assertFileCreatedUnderRootFolder("Random folder", f); + } + + @Test + public void newNestedFoldersCreatedUnderRootFolder() throws IOException { + tempFolder.create(); + + File f = tempFolder.newFolder("top", "middle", "bottom"); + assertFileExists(f); + assertParentFolderForFileIs(f, new File(tempFolder.getRoot(), + "top/middle")); + assertParentFolderForFileIs(f.getParentFile(), + new File(tempFolder.getRoot(), "top")); + assertFileCreatedUnderRootFolder("top", f.getParentFile() + .getParentFile()); + } + + @Test + public void canSetTheBaseFileForATemporaryFolder() throws IOException { + File tempDir = createTemporaryFolder(); + + TemporaryFolder folder = new TemporaryFolder(tempDir); + folder.create(); + + assertThat(tempDir, is(folder.getRoot().getParentFile())); + } + + private File createTemporaryFolder() throws IOException { + File tempDir = File.createTempFile("junit", "tempFolder"); + assertTrue("Unable to delete temporary file", tempDir.delete()); + assertTrue("Unable to create temp directory", tempDir.mkdir()); + return tempDir; + } + + private void assertFileDoesNotExist(File file) { + checkFileExists("exists", file, false); + } + + private void checkFileExists(String msg, File file, boolean exists) { + assertThat("File is null", file, is(notNullValue())); + assertThat("File '" + file.getAbsolutePath() + "' " + msg, + file.exists(), is(exists)); + } + + private void assertFileExists(File file) { + checkFileExists("does not exist", file, true); + } + + private void assertFileCreatedUnderRootFolder(String msg, File f) { + assertParentFolderForFileIs(f, tempFolder.getRoot()); + } + + private void assertParentFolderForFileIs(File f, File parentFolder) { + assertThat("'" + f.getAbsolutePath() + "': not under root", + f.getParentFile(), is(parentFolder)); + } +} diff --git a/src/test/java/org/junit/rules/TestRuleTest.java b/src/test/java/org/junit/rules/TestRuleTest.java new file mode 100644 index 000000000000..0562fa610219 --- /dev/null +++ b/src/test/java/org/junit/rules/TestRuleTest.java @@ -0,0 +1,728 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +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 java.util.LinkedList; +import java.util.List; + +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.internal.AssumptionViolatedException; +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); + } + + 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 { + @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()); + } + + public static class MethodExampleTest { + private 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(); + } + + ; + }; + } + }; + + @Rule + public TestRule getExample() { + return example; + } + + @Test + public void nothing() { + + } + } + + @Test + public void methodRuleIsIntroducedAndEvaluated() { + wasRun = false; + JUnitCore.runClasses(MethodExampleTest.class); + assertTrue(wasRun); + } + + public static class MethodBothKindsOfRule 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 MethodOneFieldTwoKindsOfRule { + private MethodBothKindsOfRule both = new MethodBothKindsOfRule(); + + @Rule + public MethodBothKindsOfRule getBoth() { + return both; + } + + @Test + public void onlyOnce() { + assertEquals(1, both.applications); + } + } + + + @Test + public void methodOnlyApplyOnceEvenIfImplementsBothInterfaces() { + assertTrue(JUnitCore.runClasses(MethodOneFieldTwoKindsOfRule.class).wasSuccessful()); + } + + public static class MethodSonOfExampleTest extends MethodExampleTest { + + } + + @Test + public void methodRuleIsIntroducedAndEvaluatedOnSubclass() { + wasRun = false; + JUnitCore.runClasses(MethodSonOfExampleTest.class); + assertTrue(wasRun); + } + + public static class MethodMultipleRuleTest { + 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(); + } + + ; + }; + } + } + + private TestRule incrementor1 = new Increment(); + + @Rule + public TestRule getIncrementor1() { + return incrementor1; + } + + private TestRule incrementor2 = new Increment(); + + @Rule + public TestRule getIncrementor2() { + return incrementor2; + } + + @Test + public void nothing() { + + } + } + + @Test + public void methodMultipleRulesAreRun() { + runCount = 0; + JUnitCore.runClasses(MethodMultipleRuleTest.class); + assertEquals(2, runCount); + } + + public static class MethodNoRulesTest { + public int x; + + @Test + public void nothing() { + + } + } + + @Test + public void methodIgnoreNonRules() { + Result result = JUnitCore.runClasses(MethodNoRulesTest.class); + assertEquals(0, result.getFailureCount()); + } + + public static class MethodOnFailureTest { + private TestRule watchman = new TestWatcher() { + @Override + protected void failed(Throwable e, Description description) { + log += description + " " + e.getClass().getSimpleName(); + } + }; + + @Rule + public TestRule getWatchman() { + return watchman; + } + + @Test + public void nothing() { + fail(); + } + } + + @Test + public void methodOnFailure() { + log = ""; + Result result = JUnitCore.runClasses(MethodOnFailureTest.class); + assertEquals(String.format("nothing(%s) AssertionError", MethodOnFailureTest.class.getName()), log); + assertEquals(1, result.getFailureCount()); + } + + public static class MethodOnSkippedTest { + private TestRule watchman = new TestWatcher() { + @Override + protected void skipped(AssumptionViolatedException e, Description description) { + log += description + " " + e.getClass().getSimpleName(); + } + }; + + @Rule + public TestRule getWatchman() { + return watchman; + } + + @Test + public void nothing() { + Assume.assumeTrue(false); + } + } + + @Test + public void methodOnSkipped() { + log = ""; + Result result = JUnitCore.runClasses(MethodOnSkippedTest.class); + assertEquals(String.format("nothing(%s) AssumptionViolatedException", MethodOnSkippedTest.class.getName()), log); + assertEquals(0, result.getFailureCount()); + assertEquals(1, result.getRunCount()); + } + + public static class MethodWatchmanTest { + @SuppressWarnings("unused") + private static String watchedLog; + + private TestRule watchman = 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"; + } + }; + + @Rule + public TestRule getWatchman() { + return watchman; + } + + @Test + public void fails() { + fail(); + } + + @Test + public void succeeds() { + } + } + + @Test + public void methodSucceeded() { + 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 MethodBeforesAndAfters { + private static String watchedLog; + + @Before + public void before() { + watchedLog += "before "; + } + + private TestRule watchman = new TestWatcher() { + @Override + protected void starting(Description d) { + watchedLog += "starting "; + } + + @Override + protected void finished(Description d) { + watchedLog += "finished "; + } + + @Override + protected void succeeded(Description d) { + watchedLog += "succeeded "; + } + }; + + @Rule + public TestRule getWatchman() { + return watchman; + } + + @After + public void after() { + watchedLog += "after "; + } + + @Test + public void succeeds() { + watchedLog += "test "; + } + } + + @Test + public void methodBeforesAndAfters() { + MethodBeforesAndAfters.watchedLog = ""; + JUnitCore.runClasses(MethodBeforesAndAfters.class); + assertThat(MethodBeforesAndAfters.watchedLog, is("starting before test after succeeded finished ")); + } + + public static class MethodWrongTypedField { + @Rule + public int getX() { + return 5; + } + + @Test + public void foo() { + } + } + + @Test + public void methodValidateWrongTypedField() { + assertThat(testResult(MethodWrongTypedField.class), + hasSingleFailureContaining("must return an implementation of MethodRule")); + } + + public static class MethodSonOfWrongTypedField extends MethodWrongTypedField { + + } + + @Test + public void methodValidateWrongTypedFieldInSuperclass() { + assertThat(testResult(MethodSonOfWrongTypedField.class), + hasSingleFailureContaining("must return an implementation of MethodRule")); + } + + public static class MethodPrivateRule { + @Rule + private TestRule getRule() { + return new TestName(); + } + + @Test + public void foo() { + } + } + + @Test + public void methodValidatePrivateRule() { + assertThat(testResult(MethodPrivateRule.class), + hasSingleFailureContaining("must be public")); + } + + public static class MethodUsesCustomMethodRule { + private CustomTestName counter = new CustomTestName(); + + @Rule + public CustomTestName getCounter() { + return counter; + } + + @Test + public void foo() { + assertEquals("foo", counter.name); + } + } + + @Test + public void methodUseCustomMethodRule() { + assertThat(testResult(MethodUsesCustomMethodRule.class), isSuccessful()); + } + + private static final List orderList = new LinkedList(); + + private static class OrderTestRule implements TestRule { + private String name; + + public OrderTestRule(String name) { + this.name = name; + } + + public Statement apply(final Statement base, final Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + orderList.add(name); + base.evaluate(); + } + }; + } + } + + public static class UsesFieldAndMethodRule { + @Rule + public OrderTestRule orderMethod() { + return new OrderTestRule("orderMethod"); + } + + @Rule + public OrderTestRule orderField = new OrderTestRule("orderField"); + + @Test + public void foo() { + assertEquals("orderField", orderList.get(0)); + assertEquals("orderMethod", orderList.get(1)); + } + } + + @Test + public void usesFieldAndMethodRule() { + orderList.clear(); + assertThat(testResult(UsesFieldAndMethodRule.class), isSuccessful()); + } + + public static class CallMethodOnlyOnceRule { + int countOfMethodCalls = 0; + + private static class Dummy implements TestRule { + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + base.evaluate(); + } + + ; + }; + } + } + + @Rule + public Dummy both() { + countOfMethodCalls++; + return new Dummy(); + } + + @Test + public void onlyOnce() { + assertEquals(1, countOfMethodCalls); + } + } + + @Test + public void testCallMethodOnlyOnceRule() { + assertTrue(JUnitCore.runClasses(CallMethodOnlyOnceRule.class).wasSuccessful()); + } +} diff --git a/src/test/java/org/junit/rules/TestWatcherTest.java b/src/test/java/org/junit/rules/TestWatcherTest.java new file mode 100644 index 000000000000..100a13f540c8 --- /dev/null +++ b/src/test/java/org/junit/rules/TestWatcherTest.java @@ -0,0 +1,192 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; +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.runner.JUnitCore.runClasses; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.results.PrintableResult; +import org.junit.internal.AssumptionViolatedException; +import org.junit.runner.Description; + +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 skipped finished ")); + } + + public static class InternalViolatedAssumptionTest { + private static StringBuilder watchedLog = new StringBuilder(); + + @Rule + public TestRule watcher = new TestWatcher() { + @Override + protected void starting(Description description) { + watchedLog.append("starting "); + } + + @Override + protected void finished(Description description) { + watchedLog.append("finished "); + } + + @Override + protected void skipped(AssumptionViolatedException e, Description description) { + watchedLog.append("skipped "); + } + }; + + @SuppressWarnings("deprecation") + @Test + public void succeeds() { + throw new AssumptionViolatedException("don't run"); + } + } + + @Test + public void internalViolatedAssumption() { + InternalViolatedAssumptionTest.watchedLog = new StringBuilder(); + runClasses(InternalViolatedAssumptionTest.class); + assertThat(InternalViolatedAssumptionTest.watchedLog.toString(), + is("starting skipped finished ")); + } + + public static class TestWatcherSkippedThrowsExceptionTest { + @Rule + public TestRule watcher = new TestWatcher() { + @Override + protected void skipped(AssumptionViolatedException e, Description description) { + throw new RuntimeException("watcher failure"); + } + }; + + @SuppressWarnings("deprecation") + @Test + public void fails() { + throw new AssumptionViolatedException("test failure"); + } + } + + @Test + public void testWatcherSkippedThrowsException() { + PrintableResult result = testResult(TestWatcherSkippedThrowsExceptionTest.class); + assertThat(result, failureCountIs(2)); + assertThat(result, hasFailureContaining("test failure")); + assertThat(result, hasFailureContaining("watcher failure")); + } + + 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 ")); + } + + public static class TestWatcherFailedThrowsExceptionTest { + @Rule + public TestRule watcher = new TestWatcher() { + @Override + protected void failed(Throwable e, Description description) { + throw new RuntimeException("watcher failure"); + } + }; + + @Test + public void fails() { + throw new IllegalArgumentException("test failure"); + } + } + + @Test + public void testWatcherFailedThrowsException() { + PrintableResult result = testResult(TestWatcherFailedThrowsExceptionTest.class); + assertThat(result, failureCountIs(2)); + assertThat(result, hasFailureContaining("test failure")); + assertThat(result, hasFailureContaining("watcher failure")); + } + + public static class TestWatcherStartingThrowsExceptionTest { + @Rule + public TestRule watcher = new TestWatcher() { + @Override + protected void starting(Description description) { + throw new RuntimeException("watcher failure"); + } + }; + + @Test + public void fails() { + throw new IllegalArgumentException("test failure"); + } + } + + @Test + public void testWatcherStartingThrowsException() { + PrintableResult result = testResult(TestWatcherStartingThrowsExceptionTest.class); + assertThat(result, failureCountIs(2)); + assertThat(result, hasFailureContaining("test failure")); + assertThat(result, hasFailureContaining("watcher failure")); + } + + public static class TestWatcherFailedAndFinishedThrowsExceptionTest { + @Rule + public TestRule watcher = new TestWatcher() { + @Override + protected void failed(Throwable e, Description description) { + throw new RuntimeException("watcher failed failure"); + } + + @Override + protected void finished(Description description) { + throw new RuntimeException("watcher finished failure"); + } + }; + + @Test + public void fails() { + throw new IllegalArgumentException("test failure"); + } + } + + @Test + public void testWatcherFailedAndFinishedThrowsException() { + PrintableResult result = testResult(TestWatcherFailedAndFinishedThrowsExceptionTest.class); + assertThat(result, failureCountIs(3)); + assertThat(result, hasFailureContaining("test failure")); + assertThat(result, hasFailureContaining("watcher failed failure")); + assertThat(result, hasFailureContaining("watcher finished failure")); + } +} diff --git a/src/test/java/org/junit/rules/TestWatchmanTest.java b/src/test/java/org/junit/rules/TestWatchmanTest.java new file mode 100644 index 000000000000..58644486453a --- /dev/null +++ b/src/test/java/org/junit/rules/TestWatchmanTest.java @@ -0,0 +1,78 @@ +package org.junit.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.runners.model.FrameworkMethod; + +@SuppressWarnings("deprecation") +public class TestWatchmanTest { + public static class ViolatedAssumptionTest { + static StringBuilder log = new StringBuilder(); + @Rule + public LoggingTestWatchman watchman = new LoggingTestWatchman(log); + + @Test + public void succeeds() { + assumeTrue(false); + } + } + + @Test + public void neitherLogSuccessNorFailedForViolatedAssumption() { + runClasses(ViolatedAssumptionTest.class); + assertThat(ViolatedAssumptionTest.log.toString(), + is("starting finished ")); + } + + public static class FailingTest { + static StringBuilder log = new StringBuilder(); + @Rule + public LoggingTestWatchman watchman = new LoggingTestWatchman(log); + + @Test + public void succeeds() { + fail(); + } + } + + @Test + public void logFailingTest() { + runClasses(FailingTest.class); + assertThat(FailingTest.log.toString(), + is("starting failed finished ")); + } + + private static class LoggingTestWatchman extends TestWatchman { + private final StringBuilder log; + + private LoggingTestWatchman(StringBuilder log) { + this.log = log; + } + + @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/src/test/java/org/junit/rules/TimeoutRuleTest.java b/src/test/java/org/junit/rules/TimeoutRuleTest.java new file mode 100644 index 000000000000..e3b2041af526 --- /dev/null +++ b/src/test/java/org/junit/rules/TimeoutRuleTest.java @@ -0,0 +1,162 @@ +package org.junit.rules; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class TimeoutRuleTest { + private static final ReentrantLock run1Lock = new ReentrantLock(); + + private static volatile boolean run4done = false; + + public abstract static class AbstractTimeoutTest { + public static final StringBuffer logger = new StringBuffer(); + + @Rule + public final TemporaryFolder tmpFile = new TemporaryFolder(); + + @Test + public void run1() throws InterruptedException { + logger.append("run1"); + TimeoutRuleTest.run1Lock.lockInterruptibly(); + TimeoutRuleTest.run1Lock.unlock(); + } + + @Test + public void run2() throws InterruptedException { + logger.append("run2"); + Thread.currentThread().join(); + } + + @Test + public synchronized void run3() throws InterruptedException { + logger.append("run3"); + wait(); + } + + @Test + public void run4() { + logger.append("run4"); + while (!run4done) { + } + } + + @Test + public void run5() throws IOException { + logger.append("run5"); + Random rnd = new Random(); + byte[] data = new byte[1024]; + File tmp = tmpFile.newFile(); + while (true) { + RandomAccessFile randomAccessFile = new RandomAccessFile(tmp, "rw"); + try { + FileChannel channel = randomAccessFile.getChannel(); + rnd.nextBytes(data); + ByteBuffer buffer = ByteBuffer.wrap(data); + // Interrupted thread closes channel and throws ClosedByInterruptException. + channel.write(buffer); + } finally { + randomAccessFile.close(); + } + tmp.delete(); + } + } + + @Test + public void run6() throws InterruptedIOException { + logger.append("run6"); + // Java IO throws InterruptedIOException only on SUN machines. + throw new InterruptedIOException(); + } + } + + public static class HasGlobalLongTimeout extends AbstractTimeoutTest { + + @Rule + public final TestRule globalTimeout = Timeout.millis(200); + } + + public static class HasGlobalTimeUnitTimeout extends AbstractTimeoutTest { + + @Rule + public final TestRule globalTimeout = new Timeout(200, TimeUnit.MILLISECONDS); + } + + public static class HasNullTimeUnit { + + @Rule + public final TestRule globalTimeout = new Timeout(200, null); + + @Test + public void wouldPass() { + } + } + + @Before + public void before() { + run4done = false; + run1Lock.lock(); + } + + @After + public void after() { + // set run4done to make sure that the thread won't continue at run4() + run4done = true; + run1Lock.unlock(); + } + + @Test + public void timeUnitTimeout() { + HasGlobalTimeUnitTimeout.logger.setLength(0); + Result result = JUnitCore.runClasses(HasGlobalTimeUnitTimeout.class); + assertEquals(6, result.getFailureCount()); + assertThat(HasGlobalTimeUnitTimeout.logger.toString(), containsString("run1")); + assertThat(HasGlobalTimeUnitTimeout.logger.toString(), containsString("run2")); + assertThat(HasGlobalTimeUnitTimeout.logger.toString(), containsString("run3")); + assertThat(HasGlobalTimeUnitTimeout.logger.toString(), containsString("run4")); + assertThat(HasGlobalTimeUnitTimeout.logger.toString(), containsString("run5")); + assertThat(HasGlobalTimeUnitTimeout.logger.toString(), containsString("run6")); + } + + @Test + public void longTimeout() { + HasGlobalLongTimeout.logger.setLength(0); + Result result = JUnitCore.runClasses(HasGlobalLongTimeout.class); + assertEquals(6, result.getFailureCount()); + assertThat(HasGlobalLongTimeout.logger.toString(), containsString("run1")); + assertThat(HasGlobalLongTimeout.logger.toString(), containsString("run2")); + assertThat(HasGlobalLongTimeout.logger.toString(), containsString("run3")); + assertThat(HasGlobalLongTimeout.logger.toString(), containsString("run4")); + assertThat(HasGlobalLongTimeout.logger.toString(), containsString("run5")); + assertThat(HasGlobalLongTimeout.logger.toString(), containsString("run6")); + } + + @Test + public void nullTimeUnit() { + Result result = JUnitCore.runClasses(HasNullTimeUnit.class); + assertEquals(1, result.getFailureCount()); + Failure failure = result.getFailures().get(0); + assertThat(failure.getException().getMessage(), + containsString("Invalid parameters for Timeout")); + Throwable cause = failure.getException().getCause(); + assertThat(cause.getMessage(), containsString("TimeUnit cannot be null")); + } +} diff --git a/src/test/java/org/junit/rules/VerifierRuleTest.java b/src/test/java/org/junit/rules/VerifierRuleTest.java new file mode 100644 index 000000000000..1344fe9c0a1f --- /dev/null +++ b/src/test/java/org/junit/rules/VerifierRuleTest.java @@ -0,0 +1,210 @@ +package org.junit.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.function.ThrowingRunnable; + +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("was <3>")); + assertThat(testResult, hasFailureContaining("was <5>")); + assertThat(testResult, hasFailureContaining("reason 1")); + assertThat(testResult, hasFailureContaining("was <7>")); + assertThat(testResult, hasFailureContaining("reason 2")); + assertThat(testResult, hasFailureContaining("was <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 Integer call() throws Exception { + throw new RuntimeException("second!"); + } + }); + Integer result = collector.checkSucceeds(new Callable() { + public Integer call() throws Exception { + return 1; + } + }); + assertEquals(Integer.valueOf(1), result); + } + } + + @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()); + } + + public static class UsesErrorCollectorCheckThrowsMatchingClass { + @Rule + public ErrorCollector collector = new ErrorCollector(); + + @Test + public void example() { + collector.checkThrows(IllegalArgumentException.class, new ThrowingRunnable() { + public void run() throws Throwable { + throw new IllegalArgumentException(); + } + }); + } + } + + @Test + public void usedErrorCollectorCheckThrowsMatchingClassShouldPass() { + PrintableResult testResult = testResult(UsesErrorCollectorCheckThrowsMatchingClass.class); + assertThat(testResult, isSuccessful()); + } + + public static class UsesErrorCollectorCheckThrowsClassMismatch { + @Rule + public ErrorCollector collector = new ErrorCollector(); + + @Test + public void example() { + collector.checkThrows(IllegalArgumentException.class, new ThrowingRunnable() { + public void run() throws Throwable { + throw new NullPointerException(); + } + }); + } + } + + @Test + public void usedErrorCollectorCheckThrowsClassMismatchShouldFail() { + PrintableResult testResult = testResult(UsesErrorCollectorCheckThrowsClassMismatch.class); + assertThat(testResult, hasFailureContaining( + "expected: but was:")); + } + + public static class UsesErrorCollectorCheckThrowsNothingThrown { + @Rule + public ErrorCollector collector = new ErrorCollector(); + + @Test + public void example() { + collector.checkThrows(IllegalArgumentException.class, new ThrowingRunnable() { + public void run() throws Throwable { + } + }); + } + } + + @Test + public void usedErrorCollectorCheckThrowsNothingThrownShouldFail() { + PrintableResult testResult = testResult(UsesErrorCollectorCheckThrowsNothingThrown.class); + assertThat(testResult, hasFailureContaining("but nothing was thrown")); + } + + 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); + } +} diff --git a/src/test/java/org/junit/runner/AllRunnerTests.java b/src/test/java/org/junit/runner/AllRunnerTests.java new file mode 100644 index 000000000000..159f9133f7f7 --- /dev/null +++ b/src/test/java/org/junit/runner/AllRunnerTests.java @@ -0,0 +1,17 @@ +package org.junit.runner; + + +import org.junit.runner.notification.AllNotificationTests; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AllNotificationTests.class, + FilterFactoriesTest.class, + FilterOptionIntegrationTest.class, + JUnitCommandLineParseResultTest.class, + JUnitCoreTest.class +}) +public class AllRunnerTests { +} diff --git a/src/test/java/org/junit/runner/FilterFactoriesTest.java b/src/test/java/org/junit/runner/FilterFactoriesTest.java new file mode 100644 index 000000000000..0293cf8e464b --- /dev/null +++ b/src/test/java/org/junit/runner/FilterFactoriesTest.java @@ -0,0 +1,137 @@ +package org.junit.runner; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assume.assumeThat; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.ExcludeCategories; +import org.junit.rules.ExpectedException; +import org.junit.rules.TestName; +import org.junit.runner.manipulation.Filter; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +public class FilterFactoriesTest { + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Rule + public TestName testName = new TestName(); + + private Request createSuiteRequest() { + return Request.aClass(DummySuite.class); + } + + @Test + public void shouldCreateFilterWithArguments() throws Exception { + Filter filter = FilterFactories.createFilterFromFilterSpec( + createSuiteRequest(), + ExcludeCategories.class.getName() + "=" + DummyCategory.class.getName()); + + assertThat(filter.describe(), startsWith("excludes ")); + } + + @Test + public void shouldCreateFilterWithNoArguments() throws Exception { + Filter filter = FilterFactories.createFilterFromFilterSpec( + createSuiteRequest(), FilterFactoryStub.class.getName()); + + assertThat(filter, instanceOf(DummyFilter.class)); + } + + @Test + public void shouldPassOnDescriptionToFilterFactory() throws Exception { + Request request = createSuiteRequest(); + Description description = request.getRunner().getDescription(); + Filter filter = FilterFactories.createFilterFromFilterSpec( + request, FilterFactoryStub.class.getName()); + + // This assumption tested in shouldCreateFilterWithNoArguments() + assumeThat(filter, instanceOf(DummyFilter.class)); + + DummyFilter dummyFilter = (DummyFilter) filter; + assertThat(dummyFilter.getTopLevelDescription(), is(description)); + } + + @Test + public void shouldCreateFilter() throws Exception { + Filter filter = FilterFactories.createFilter( + FilterFactoryStub.class, + new FilterFactoryParams( + Description.createSuiteDescription(testName.getMethodName()), + "")); + + assertThat(filter, instanceOf(DummyFilter.class)); + } + + @Test + public void shouldThrowExceptionIfNotFilterFactory() throws Exception { + expectedException.expect(FilterFactory.FilterNotCreatedException.class); + + FilterFactories.createFilterFactory(NonFilterFactory.class.getName()); + } + + @Test + public void shouldThrowExceptionIfNotInstantiable() throws Exception { + expectedException.expect(FilterFactory.FilterNotCreatedException.class); + + FilterFactories.createFilterFactory(NonInstantiableFilterFactory.class); + } + + public static class NonFilterFactory { + } + + public static class NonInstantiableFilterFactory implements FilterFactory { + private NonInstantiableFilterFactory() { + } + + public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { + throw new FilterNotCreatedException(new Exception("not implemented")); + } + } + + public static class FilterFactoryStub implements FilterFactory { + public Filter createFilter(FilterFactoryParams params) { + return new DummyFilter(params.getTopLevelDescription()); + } + } + + private static class DummyFilter extends Filter { + private final Description fTopLevelDescription; + + public DummyFilter(Description topLevelDescription) { + fTopLevelDescription = topLevelDescription; + } + + public Description getTopLevelDescription() { + return fTopLevelDescription; + } + + @Override + public boolean shouldRun(Description description) { + return false; + } + + @Override + public String describe() { + return null; + } + } + + public static class DummyCategory { + } + + @RunWith(Suite.class) + @SuiteClasses(DummyTest.class) + public static class DummySuite { + } + + public static class DummyTest { + @Test + public void passes() { + } + } +} diff --git a/src/test/java/org/junit/runner/FilterOptionIntegrationTest.java b/src/test/java/org/junit/runner/FilterOptionIntegrationTest.java new file mode 100644 index 000000000000..25cde879385c --- /dev/null +++ b/src/test/java/org/junit/runner/FilterOptionIntegrationTest.java @@ -0,0 +1,190 @@ +package org.junit.runner; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.experimental.categories.ExcludeCategories; +import org.junit.experimental.categories.IncludeCategories; +import org.junit.runner.notification.RunListener; +import org.junit.tests.TestSystem; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class FilterOptionIntegrationTest { + private static final String INCLUDES_DUMMY_CATEGORY_0 = "--filter=" + + IncludeCategories.class.getName() + "=" + DummyCategory0.class.getName(); + private static final String EXCLUDES_DUMMY_CATEGORY_1 = "--filter=" + + ExcludeCategories.class.getName() + "=" + DummyCategory1.class.getName(); + + private JUnitCore jUnitCore = new JUnitCore(); + private TestListener testListener = new TestListener(); + + @Before + public void setUp() { + jUnitCore.addListener(testListener); + } + + @Test + public void shouldRunAllTests() { + Result result = runJUnit( + DummyTestClass.class.getName(), + DummyTestClass0.class.getName(), + DummyTestClass1.class.getName(), + DummyTestClass01.class.getName(), + DummyTestClass0TestMethod1.class.getName()); + + assertWasRun(DummyTestClass.class); + assertWasRun(DummyTestClass0.class); + assertWasRun(DummyTestClass1.class); + assertWasRun(DummyTestClass01.class); + assertWasRun(DummyTestClass0TestMethod1.class); + assertThat("runCount does not match", result.getRunCount(), is(5)); + assertThat("failureCount does not match", result.getFailureCount(), is(0)); + } + + @Test + public void shouldExcludeSomeTests() { + Result result = runJUnit( + EXCLUDES_DUMMY_CATEGORY_1, + DummyTestClass.class.getName(), + DummyTestClass0.class.getName(), + DummyTestClass1.class.getName(), + DummyTestClass01.class.getName(), + DummyTestClass0TestMethod1.class.getName()); + + assertWasRun(DummyTestClass.class); + assertWasRun(DummyTestClass0.class); + assertWasNotRun(DummyTestClass1.class); + assertWasNotRun(DummyTestClass01.class); + assertWasNotRun(DummyTestClass0TestMethod1.class); + assertThat("runCount does not match", result.getRunCount(), is(2)); + assertThat("failureCount does not match", result.getFailureCount(), is(0)); + } + + @Test + public void shouldIncludeSomeTests() { + Result result = runJUnit( + INCLUDES_DUMMY_CATEGORY_0, + DummyTestClass.class.getName(), + DummyTestClass0.class.getName(), + DummyTestClass1.class.getName(), + DummyTestClass01.class.getName(), + DummyTestClass0TestMethod1.class.getName()); + + assertWasNotRun(DummyTestClass.class); + assertWasRun(DummyTestClass0.class); + assertWasNotRun(DummyTestClass1.class); + assertWasRun(DummyTestClass01.class); + assertWasRun(DummyTestClass0TestMethod1.class); + assertThat("runCount does not match", result.getRunCount(), is(3)); + assertThat("failureCount does not match", result.getFailureCount(), is(0)); + } + + @Test + public void shouldCombineFilters() { + Result result = runJUnit( + INCLUDES_DUMMY_CATEGORY_0, + EXCLUDES_DUMMY_CATEGORY_1, + DummyTestClass.class.getName(), + DummyTestClass0.class.getName(), + DummyTestClass1.class.getName(), + DummyTestClass01.class.getName(), + DummyTestClass0TestMethod1.class.getName()); + + assertWasNotRun(DummyTestClass.class); + assertWasRun(DummyTestClass0.class); + assertWasNotRun(DummyTestClass1.class); + assertWasNotRun(DummyTestClass01.class); + assertWasNotRun(DummyTestClass0TestMethod1.class); + assertThat("runCount does not match", result.getRunCount(), is(1)); + assertThat("failureCount does not match", result.getFailureCount(), is(0)); + } + + private Result runJUnit(final String... args) { + return jUnitCore.runMain(new TestSystem(), args); + } + + private void assertWasRun(Class testClass) { + assertTrue(testClass.getName() + " expected to finish but did not", testListener.wasRun(testClass)); + } + + private void assertWasNotRun(Class testClass) { + assertFalse( + testClass.getName() + " expected not to have been started but was", + testListener.wasRun(testClass)); + } + + private static class TestListener extends RunListener { + private Set startedTests = new HashSet(); + private Set finishedTests = new HashSet(); + + @Override + public void testFinished(final Description description) { + finishedTests.add(description.getClassName()); + } + + private boolean testFinished(final Class testClass) { + return finishedTests.contains(testClass.getName()); + } + + @Override + public void testStarted(final Description description) { + startedTests.add(description.getClassName()); + } + + private boolean testStarted(final Class testClass) { + return startedTests.contains(testClass.getName()); + } + + public boolean wasRun(final Class testClass) { + return testStarted(testClass) && testFinished(testClass); + } + } + + public static class DummyTestClass { + @Test + public void dummyTest() { + } + } + + @Category(DummyCategory0.class) + public static class DummyTestClass0 { + @Test + public void dummyTest() { + } + } + + @Category(DummyCategory1.class) + public static class DummyTestClass1 { + @Test + public void dummyTest() { + } + } + + @Category({DummyCategory0.class, DummyCategory1.class}) + public static class DummyTestClass01 { + @Test + public void dummyTest() { + } + } + + @Category(DummyCategory0.class) + public static class DummyTestClass0TestMethod1 { + @Category(DummyCategory1.class) + @Test + public void dummyTest() { + } + } + + public static interface DummyCategory0 { + } + + public static interface DummyCategory1 { + } +} diff --git a/src/test/java/org/junit/runner/JUnitCommandLineParseResultTest.java b/src/test/java/org/junit/runner/JUnitCommandLineParseResultTest.java new file mode 100644 index 000000000000..ffd1f1c9552f --- /dev/null +++ b/src/test/java/org/junit/runner/JUnitCommandLineParseResultTest.java @@ -0,0 +1,146 @@ +package org.junit.runner; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.IncludeCategories; +import org.junit.rules.ExpectedException; +import org.junit.runner.manipulation.Filter; + +public class JUnitCommandLineParseResultTest { + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private final JUnitCommandLineParseResult jUnitCommandLineParseResult = new JUnitCommandLineParseResult(); + + @Test + public void shouldStopParsingOptionsUponDoubleHyphenArg() throws Exception { + String[] restOfArgs = jUnitCommandLineParseResult.parseOptions( + "--0", "--1", "--", "--2", "--3"); + + assertThat(restOfArgs, is(new String[]{"--2", "--3"})); + } + + @Test + public void shouldParseFilterArgWithEqualsSyntax() throws Exception { + String value= IncludeCategories.class.getName() + "=" + DummyCategory0.class.getName(); + jUnitCommandLineParseResult.parseOptions("--filter=" + value); + + List specs= jUnitCommandLineParseResult.getFilterSpecs(); + + assertThat(specs, hasItems(value)); + } + + @Test + public void shouldCreateFailureUponBaldFilterOptionNotFollowedByValue() { + jUnitCommandLineParseResult.parseOptions("--filter"); + + Runner runner = jUnitCommandLineParseResult.createRequest(new Computer()).getRunner(); + Description description = runner.getDescription().getChildren().get(0); + + assertThat(description.toString(), containsString("initializationError")); + } + + @Test + public void shouldParseFilterArgInWhichValueIsASeparateArg() throws Exception { + String value= IncludeCategories.class.getName() + "=" + DummyCategory0.class.getName(); + jUnitCommandLineParseResult.parseOptions("--filter", value); + + List specs= jUnitCommandLineParseResult.getFilterSpecs(); + + assertThat(specs, hasItems(value)); + } + + @Test + public void shouldStopParsingOptionsUponNonOption() throws Exception { + String[] restOfArgs = jUnitCommandLineParseResult.parseOptions(new String[]{ + "--0", "--1", "2", "3" + }); + + assertThat(restOfArgs, is(new String[]{"2", "3"})); + } + + @Test + public void shouldCreateFailureUponUnknownOption() throws Exception { + String unknownOption = "--unknown-option"; + jUnitCommandLineParseResult.parseOptions(new String[]{ + unknownOption + }); + + Runner runner = jUnitCommandLineParseResult.createRequest(new Computer()).getRunner(); + Description description = runner.getDescription().getChildren().get(0); + + assertThat(description.toString(), containsString("initializationError")); + } + + @Test + public void shouldCreateFailureUponUncreatedFilter() throws Exception { + jUnitCommandLineParseResult.parseOptions(new String[]{ + "--filter=" + FilterFactoryStub.class.getName() + }); + + Runner runner = jUnitCommandLineParseResult.createRequest(new Computer()).getRunner(); + Description description = runner.getDescription().getChildren().get(0); + + assertThat(description.toString(), containsString("initializationError")); + } + + @Test + public void shouldCreateFailureUponUnfoundFilterFactory() throws Exception { + String nonExistentFilterFactory = "NonExistentFilterFactory"; + jUnitCommandLineParseResult.parseOptions(new String[]{ + "--filter=" + nonExistentFilterFactory + }); + + Runner runner = jUnitCommandLineParseResult.createRequest(new Computer()).getRunner(); + Description description = runner.getDescription().getChildren().get(0); + + assertThat(description.toString(), containsString("initializationError")); + } + + @Test + public void shouldAddToClasses() { + jUnitCommandLineParseResult.parseParameters(new String[]{ + DummyTest.class.getName() + }); + + List> classes = jUnitCommandLineParseResult.getClasses(); + Class testClass = classes.get(0); + + assertThat(testClass.getName(), is(DummyTest.class.getName())); + } + + @Test + public void shouldCreateFailureUponUnknownTestClass() throws Exception { + String unknownTestClass = "UnknownTestClass"; + jUnitCommandLineParseResult.parseParameters(new String[]{ + unknownTestClass + }); + + Runner runner = jUnitCommandLineParseResult.createRequest(new Computer()).getRunner(); + Description description = runner.getDescription().getChildren().get(0); + + assertThat(description.toString(), containsString("initializationError")); + } + + public static class FilterFactoryStub implements FilterFactory { + public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { + throw new FilterNotCreatedException(new Exception("stub")); + } + } + + public static interface DummyCategory0 { + } + + public static class DummyTest { + @Test + public void dummyTest() { + } + } +} diff --git a/src/test/java/org/junit/runner/JUnitCoreTest.java b/src/test/java/org/junit/runner/JUnitCoreTest.java new file mode 100644 index 000000000000..2c5e408ed74a --- /dev/null +++ b/src/test/java/org/junit/runner/JUnitCoreTest.java @@ -0,0 +1,20 @@ +package org.junit.runner; + +import org.junit.Test; +import org.junit.tests.TestSystem; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class JUnitCoreTest { + @Test + public void shouldAddFailuresToResult() { + JUnitCore jUnitCore = new JUnitCore(); + + Result result = jUnitCore.runMain(new TestSystem(), "NonExistentTest"); + + assertThat(result.getFailureCount(), is(1)); + assertThat(result.getFailures().get(0).getException(), instanceOf(IllegalArgumentException.class)); + } +} diff --git a/src/test/java/org/junit/runner/RunnerSpy.java b/src/test/java/org/junit/runner/RunnerSpy.java new file mode 100644 index 000000000000..939cd75b79ea --- /dev/null +++ b/src/test/java/org/junit/runner/RunnerSpy.java @@ -0,0 +1,37 @@ +package org.junit.runner; + +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.RunnerBuilder; + +public class RunnerSpy extends Runner { + public static final Description DESCRIPTION = Description.TEST_MECHANISM; + + private RunnerBuilder invokedRunnerBuilder; + private Class invokedTestClass; + + public RunnerSpy(Class testClass) { + invokedTestClass = testClass; + } + + public RunnerSpy(Class testClass, RunnerBuilder runnerBuilder) { + invokedTestClass = testClass; + invokedRunnerBuilder = runnerBuilder; + } + + @Override + public Description getDescription() { + return DESCRIPTION; + } + + @Override + public void run(RunNotifier runNotifier) { + } + + public RunnerBuilder getInvokedRunnerBuilder() { + return invokedRunnerBuilder; + } + + public Class getInvokedTestClass() { + return invokedTestClass; + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/runner/notification/AllNotificationTests.java b/src/test/java/org/junit/runner/notification/AllNotificationTests.java new file mode 100644 index 000000000000..1c991a9e80e5 --- /dev/null +++ b/src/test/java/org/junit/runner/notification/AllNotificationTests.java @@ -0,0 +1,14 @@ +package org.junit.runner.notification; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + ConcurrentRunNotifierTest.class, + RunNotifierTest.class, + SynchronizedRunListenerTest.class +}) +public class AllNotificationTests { +} diff --git a/src/test/java/org/junit/runner/notification/ConcurrentRunNotifierTest.java b/src/test/java/org/junit/runner/notification/ConcurrentRunNotifierTest.java new file mode 100644 index 000000000000..3406ed91150f --- /dev/null +++ b/src/test/java/org/junit/runner/notification/ConcurrentRunNotifierTest.java @@ -0,0 +1,180 @@ +package org.junit.runner.notification; + +import org.junit.Test; +import org.junit.runner.Description; + +import java.util.Random; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +/** + * Testing RunNotifier in concurrent access. + * + * @author Tibor Digana (tibor17) + * @version 4.12 + * @since 4.12 + */ +public final class ConcurrentRunNotifierTest { + private static final long TIMEOUT = 3; + private final RunNotifier fNotifier = new RunNotifier(); + + private static class ConcurrentRunListener extends RunListener { + final AtomicInteger fTestStarted = new AtomicInteger(0); + + @Override + public void testStarted(Description description) throws Exception { + fTestStarted.incrementAndGet(); + } + } + + @Test + public void realUsage() throws Exception { + ConcurrentRunListener listener1 = new ConcurrentRunListener(); + ConcurrentRunListener listener2 = new ConcurrentRunListener(); + fNotifier.addListener(listener1); + fNotifier.addListener(listener2); + + final int numParallelTests = 4; + ExecutorService pool = Executors.newFixedThreadPool(numParallelTests); + for (int i = 0; i < numParallelTests; ++i) { + pool.submit(new Runnable() { + public void run() { + fNotifier.fireTestStarted(null); + } + }); + } + pool.shutdown(); + assertTrue(pool.awaitTermination(TIMEOUT, TimeUnit.SECONDS)); + + fNotifier.removeListener(listener1); + fNotifier.removeListener(listener2); + + assertThat(listener1.fTestStarted.get(), is(numParallelTests)); + assertThat(listener2.fTestStarted.get(), is(numParallelTests)); + } + + private static class ExaminedListener extends RunListener { + final boolean throwFromTestStarted; + volatile boolean hasTestFailure = false; + + ExaminedListener(boolean throwFromTestStarted) { + this.throwFromTestStarted = throwFromTestStarted; + } + + @Override + public void testStarted(Description description) throws Exception { + if (throwFromTestStarted) { + throw new Exception(); + } + } + + @Override + public void testFailure(Failure failure) throws Exception { + hasTestFailure = true; + } + } + + private abstract class AbstractConcurrentFailuresTest { + + protected abstract void addListener(ExaminedListener listener); + + public void test() throws Exception { + int totalListenersFailures = 0; + + Random random = new Random(42); + ExaminedListener[] examinedListeners = new ExaminedListener[1000]; + for (int i = 0; i < examinedListeners.length; ++i) { + boolean fail = random.nextDouble() >= 0.5d; + if (fail) { + ++totalListenersFailures; + } + examinedListeners[i] = new ExaminedListener(fail); + } + + final AtomicBoolean condition = new AtomicBoolean(true); + final CyclicBarrier trigger = new CyclicBarrier(2); + final CountDownLatch latch = new CountDownLatch(10); + + ExecutorService notificationsPool = Executors.newFixedThreadPool(4); + notificationsPool.submit(new Callable() { + public Void call() throws Exception { + trigger.await(); + while (condition.get()) { + fNotifier.fireTestStarted(null); + latch.countDown(); + } + fNotifier.fireTestStarted(null); + return null; + } + }); + + // Wait for callable to start + trigger.await(TIMEOUT, TimeUnit.SECONDS); + + // Wait for callable to fire a few events + latch.await(TIMEOUT, TimeUnit.SECONDS); + + for (ExaminedListener examinedListener : examinedListeners) { + addListener(examinedListener); + } + + notificationsPool.shutdown(); + condition.set(false); + assertTrue(notificationsPool.awaitTermination(TIMEOUT, TimeUnit.SECONDS)); + + if (totalListenersFailures != 0) { + // If no listener failures, then all the listeners do not report any failure. + int countTestFailures = examinedListeners.length - countReportedTestFailures(examinedListeners); + assertThat(totalListenersFailures, is(countTestFailures)); + } + } + } + + /** + * Verifies that listeners added while tests are run concurrently are + * notified about test failures. + */ + @Test + public void reportConcurrentFailuresAfterAddListener() throws Exception { + new AbstractConcurrentFailuresTest() { + @Override + protected void addListener(ExaminedListener listener) { + fNotifier.addListener(listener); + } + }.test(); + } + + /** + * Verifies that listeners added with addFirstListener() while tests are run concurrently are + * notified about test failures. + */ + @Test + public void reportConcurrentFailuresAfterAddFirstListener() throws Exception { + new AbstractConcurrentFailuresTest() { + @Override + protected void addListener(ExaminedListener listener) { + fNotifier.addFirstListener(listener); + } + }.test(); + } + + private static int countReportedTestFailures(ExaminedListener[] listeners) { + int count = 0; + for (ExaminedListener listener : listeners) { + if (listener.hasTestFailure) { + ++count; + } + } + return count; + } +} diff --git a/src/test/java/org/junit/runner/notification/RunNotifierTest.java b/src/test/java/org/junit/runner/notification/RunNotifierTest.java new file mode 100644 index 000000000000..1c2e7c9f6860 --- /dev/null +++ b/src/test/java/org/junit/runner/notification/RunNotifierTest.java @@ -0,0 +1,131 @@ +package org.junit.runner.notification; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.Result; + +public class RunNotifierTest { + private final RunNotifier fNotifier = new RunNotifier(); + + @Test + public void notifiesSecondListenerIfFirstThrowsException() { + FailureListener failureListener = new FailureListener(); + fNotifier.addListener(new CorruptListener()); + fNotifier.addListener(failureListener); + fNotifier.fireTestFailure(new Failure(null, null)); + assertNotNull("The FailureListener registered no failure.", + failureListener.failure); + } + + @Test + public void hasNoProblemsWithFailingListeners() { // see issues 209 and 395 + fNotifier.addListener(new CorruptListener()); + fNotifier.addListener(new FailureListener()); + fNotifier.addListener(new CorruptListener()); + fNotifier.fireTestRunFinished(new Result()); + } + + private static class CorruptListener extends RunListener { + @Override + public void testRunFinished(Result result) throws Exception { + throw new RuntimeException(); + } + + @Override + public void testFailure(Failure failure) throws Exception { + throw new RuntimeException(); + } + } + + @Test + public void addAndRemoveWithNonThreadSafeListener() { + CountingListener listener = new CountingListener(); + assertThat(listener.fTestStarted.get(), is(0)); + fNotifier.addListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + fNotifier.removeListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + } + + @Test + public void addFirstAndRemoveWithNonThreadSafeListener() { + CountingListener listener = new CountingListener(); + assertThat(listener.fTestStarted.get(), is(0)); + fNotifier.addFirstListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + fNotifier.removeListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + } + + @Test + public void addAndRemoveWithThreadSafeListener() { + ThreadSafeListener listener = new ThreadSafeListener(); + assertThat(listener.fTestStarted.get(), is(0)); + fNotifier.addListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + fNotifier.removeListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + } + + @Test + public void addFirstAndRemoveWithThreadSafeListener() { + ThreadSafeListener listener = new ThreadSafeListener(); + assertThat(listener.fTestStarted.get(), is(0)); + fNotifier.addFirstListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + fNotifier.removeListener(listener); + fNotifier.fireTestStarted(null); + assertThat(listener.fTestStarted.get(), is(1)); + } + + @Test + public void wrapIfNotThreadSafeShouldNotWrapThreadSafeListeners() { + ThreadSafeListener listener = new ThreadSafeListener();; + assertSame(listener, new RunNotifier().wrapIfNotThreadSafe(listener)); + } + + @Test + public void wrapIfNotThreadSafeShouldWrapNonThreadSafeListeners() { + CountingListener listener = new CountingListener(); + RunListener wrappedListener = new RunNotifier().wrapIfNotThreadSafe(listener); + assertThat(wrappedListener, instanceOf(SynchronizedRunListener.class)); + } + + private static class FailureListener extends RunListener { + private Failure failure; + + @Override + public void testFailure(Failure failure) throws Exception { + this.failure = failure; + } + } + + private static class CountingListener extends RunListener { + final AtomicInteger fTestStarted = new AtomicInteger(0); + + @Override + public void testStarted(Description description) throws Exception { + fTestStarted.incrementAndGet(); + } + } + + @RunListener.ThreadSafe + private static class ThreadSafeListener extends CountingListener { + } + +} diff --git a/src/test/java/org/junit/runner/notification/SynchronizedRunListenerTest.java b/src/test/java/org/junit/runner/notification/SynchronizedRunListenerTest.java new file mode 100644 index 000000000000..6bd39b78a44a --- /dev/null +++ b/src/test/java/org/junit/runner/notification/SynchronizedRunListenerTest.java @@ -0,0 +1,156 @@ +package org.junit.runner.notification; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Test; + +/** + * Tests for {@link SynchronizedRunListener}. + * + * @author kcooney (Kevin Cooney) + */ +public class SynchronizedRunListenerTest { + + private static class MethodSignature { + private final Method fMethod; + private final String fName; + private final List> fParameterTypes; + + public MethodSignature(Method method) { + fMethod = method; + fName = method.getName(); + fParameterTypes = Arrays.asList(method.getParameterTypes()); + } + + @Override + public String toString() { + return fMethod.toString(); + } + + @Override + public int hashCode() { + return fName.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof MethodSignature)) { + return false; + } + MethodSignature that = (MethodSignature) obj; + return fName.equals(that.fName) && fParameterTypes.equals(that.fParameterTypes); + } + } + + private Set getAllDeclaredMethods(Class type) { + Set methods = new HashSet(); + for (Method method : type.getDeclaredMethods()) { + methods.add(new MethodSignature(method)); + } + return methods; + } + + @Test + public void overridesAllMethodsInRunListener() { + Set runListenerMethods = getAllDeclaredMethods(RunListener.class); + Set synchronizedRunListenerMethods = getAllDeclaredMethods( + SynchronizedRunListener.class); + + assertTrue(synchronizedRunListenerMethods.containsAll(runListenerMethods)); + } + + private static class NamedListener extends RunListener { + private final String fName; + + public NamedListener(String name) { + fName = name; + } + + @Override + public String toString() { + return "NamedListener"; + } + + @Override + public int hashCode() { + return fName.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof NamedListener)) { + return false; + } + NamedListener that = (NamedListener) obj; + return this.fName.equals(that.fName); + } + } + + @Test + public void namedListenerCorrectlyImplementsEqualsAndHashCode() { + NamedListener listener1 = new NamedListener("blue"); + NamedListener listener2 = new NamedListener("blue"); + NamedListener listener3 = new NamedListener("red"); + + assertTrue(listener1.equals(listener1)); + assertTrue(listener2.equals(listener2)); + assertTrue(listener3.equals(listener3)); + + assertFalse(listener1.equals(null)); + assertFalse(listener1.equals(new Object())); + + assertTrue(listener1.equals(listener2)); + assertTrue(listener2.equals(listener1)); + assertFalse(listener1.equals(listener3)); + assertFalse(listener3.equals(listener1)); + + assertEquals(listener1.hashCode(), listener2.hashCode()); + assertNotEquals(listener1.hashCode(), listener3.hashCode()); + } + + @Test + public void toStringDelegates() { + NamedListener listener = new NamedListener("blue"); + + assertEquals("NamedListener", listener.toString()); + assertEquals("NamedListener (with synchronization wrapper)", wrap(listener).toString()); + } + + @Test + public void equalsDelegates() { + NamedListener listener1 = new NamedListener("blue"); + NamedListener listener2 = new NamedListener("blue"); + NamedListener listener3 = new NamedListener("red"); + + assertEquals(wrap(listener1), wrap(listener1)); + assertEquals(wrap(listener1), wrap(listener2)); + assertNotEquals(wrap(listener1), wrap(listener3)); + assertNotEquals(wrap(listener1), listener1); + assertNotEquals(listener1, wrap(listener1)); + } + + @Test + public void hashCodeDelegates() { + NamedListener listener = new NamedListener("blue"); + assertEquals(listener.hashCode(), wrap(listener).hashCode()); + } + + private SynchronizedRunListener wrap(RunListener listener) { + return new SynchronizedRunListener(listener, this); + } +} diff --git a/src/test/java/org/junit/runners/AllRunnersTests.java b/src/test/java/org/junit/runners/AllRunnersTests.java new file mode 100644 index 000000000000..1e92cece59a1 --- /dev/null +++ b/src/test/java/org/junit/runners/AllRunnersTests.java @@ -0,0 +1,16 @@ +package org.junit.runners; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.runners.model.AllModelTests; +import org.junit.runners.parameterized.AllParameterizedTests; + +@RunWith(Suite.class) +@SuiteClasses({ + AllModelTests.class, + AllParameterizedTests.class, + CustomBlockJUnit4ClassRunnerTest.class +}) +public class AllRunnersTests { +} diff --git a/src/test/java/org/junit/runners/CustomBlockJUnit4ClassRunnerTest.java b/src/test/java/org/junit/runners/CustomBlockJUnit4ClassRunnerTest.java new file mode 100644 index 000000000000..d9f072baacb6 --- /dev/null +++ b/src/test/java/org/junit/runners/CustomBlockJUnit4ClassRunnerTest.java @@ -0,0 +1,90 @@ +package org.junit.runners; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.Statement; + +/** + * Tests that verify proper behavior for custom runners that extend + * {@link BlockJUnit4ClassRunner}. + * + * @author Sam Brannen + * @since 4.13 + */ +public class CustomBlockJUnit4ClassRunnerTest { + + @Test + public void exceptionsFromMethodBlockMustNotResultInUnrootedTests() throws Exception { + TrackingRunListener listener = new TrackingRunListener(); + RunNotifier notifier = new RunNotifier(); + notifier.addListener(listener); + + new CustomBlockJUnit4ClassRunner(CustomBlockJUnit4ClassRunnerTestCase.class).run(notifier); + assertEquals("tests started.", 2, listener.testStartedCount.get()); + assertEquals("tests failed.", 1, listener.testFailureCount.get()); + assertEquals("tests finished.", 2, listener.testFinishedCount.get()); + } + + + public static class CustomBlockJUnit4ClassRunnerTestCase { + @Test public void shouldPass() { /* no-op */ } + @Test public void throwException() { /* no-op */ } + } + + /** + * Custom extension of {@link BlockJUnit4ClassRunner} that always throws + * an exception from the {@code methodBlock()} if a test method is named + * exactly {@code "throwException"}. + */ + private static class CustomBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner { + + CustomBlockJUnit4ClassRunner(Class testClass) throws InitializationError { + super(testClass); + } + + @Override + protected Statement methodBlock(FrameworkMethod method) { + if ("throwException".equals(method.getName())) { + throw new RuntimeException("throwException() test method invoked"); + } + return super.methodBlock(method); + } + } + + /** + * Simple {@link RunListener} that tracks the number of times that + * certain callbacks are invoked. + */ + private static class TrackingRunListener extends RunListener { + + final AtomicInteger testStartedCount = new AtomicInteger(); + final AtomicInteger testFailureCount = new AtomicInteger(); + final AtomicInteger testFinishedCount = new AtomicInteger(); + + + @Override + public void testStarted(Description description) throws Exception { + testStartedCount.incrementAndGet(); + } + + @Override + public void testFailure(Failure failure) throws Exception { + testFailureCount.incrementAndGet(); + } + + @Override + public void testFinished(Description description) throws Exception { + testFinishedCount.incrementAndGet(); + } + } + +} diff --git a/src/test/java/org/junit/runners/model/AllModelTests.java b/src/test/java/org/junit/runners/model/AllModelTests.java new file mode 100644 index 000000000000..b0c50d533ba6 --- /dev/null +++ b/src/test/java/org/junit/runners/model/AllModelTests.java @@ -0,0 +1,15 @@ +package org.junit.runners.model; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + FrameworkFieldTest.class, + FrameworkMethodTest.class, + InvalidTestClassErrorTest.class, + TestClassTest.class +}) +public class AllModelTests { +} diff --git a/src/test/java/org/junit/runners/model/FrameworkFieldTest.java b/src/test/java/org/junit/runners/model/FrameworkFieldTest.java new file mode 100644 index 000000000000..1d185a548e72 --- /dev/null +++ b/src/test/java/org/junit/runners/model/FrameworkFieldTest.java @@ -0,0 +1,58 @@ +package org.junit.runners.model; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.rules.ExpectedException.none; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; + +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class FrameworkFieldTest { + @Rule + public final ExpectedException thrown = none(); + + @Test + public void cannotBeCreatedWithoutUnderlyingField() { + thrown.expect(NullPointerException.class); + thrown.expectMessage("FrameworkField cannot be created without an underlying field."); + new FrameworkField(null); + } + + @Test + public void hasToStringWhichPrintsFieldName() throws Exception { + Field field = ClassWithDummyField.class.getField("dummyField"); + FrameworkField frameworkField = new FrameworkField(field); + assertTrue(frameworkField.toString().contains("dummyField")); + } + + @Test + public void presentAnnotationIsAvailable() throws Exception { + Field field = ClassWithDummyField.class.getField("annotatedField"); + FrameworkField frameworkField = new FrameworkField(field); + Annotation annotation = frameworkField.getAnnotation(Rule.class); + assertTrue(Rule.class.isAssignableFrom(annotation.getClass())); + } + + @Test + public void missingAnnotationIsNotAvailable() throws Exception { + Field field = ClassWithDummyField.class.getField("annotatedField"); + FrameworkField frameworkField = new FrameworkField(field); + Annotation annotation = frameworkField.getAnnotation(ClassRule.class); + assertThat(annotation, is(nullValue())); + } + + private static class ClassWithDummyField { + @SuppressWarnings("unused") + public final int dummyField = 0; + + @Rule + public final int annotatedField = 0; + } +} diff --git a/src/test/java/org/junit/runners/model/FrameworkMethodTest.java b/src/test/java/org/junit/runners/model/FrameworkMethodTest.java new file mode 100644 index 000000000000..9927d1908676 --- /dev/null +++ b/src/test/java/org/junit/runners/model/FrameworkMethodTest.java @@ -0,0 +1,60 @@ +package org.junit.runners.model; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.rules.ExpectedException.none; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class FrameworkMethodTest { + @Rule + public final ExpectedException thrown = none(); + + @Test + public void cannotBeCreatedWithoutUnderlyingField() { + thrown.expect(NullPointerException.class); + thrown.expectMessage("FrameworkMethod cannot be created without an underlying method."); + new FrameworkMethod(null); + } + + @Test + public void hasToStringWhichPrintsMethodName() throws Exception { + Method method = ClassWithDummyMethod.class.getMethod("dummyMethod"); + FrameworkMethod frameworkMethod = new FrameworkMethod(method); + assertTrue(frameworkMethod.toString().contains("dummyMethod")); + } + + @Test + public void presentAnnotationIsAvailable() throws Exception { + Method method = ClassWithDummyMethod.class.getMethod("annotatedDummyMethod"); + FrameworkMethod frameworkMethod = new FrameworkMethod(method); + Annotation annotation = frameworkMethod.getAnnotation(Rule.class); + assertTrue(Rule.class.isAssignableFrom(annotation.getClass())); + } + + @Test + public void missingAnnotationIsNotAvailable() throws Exception { + Method method = ClassWithDummyMethod.class.getMethod("annotatedDummyMethod"); + FrameworkMethod frameworkMethod = new FrameworkMethod(method); + Annotation annotation = frameworkMethod.getAnnotation(ClassRule.class); + assertThat(annotation, is(nullValue())); + } + + private static class ClassWithDummyMethod { + @SuppressWarnings("unused") + public void dummyMethod() { + } + + @Rule + public void annotatedDummyMethod() { + } + } +} diff --git a/src/test/java/org/junit/runners/model/InvalidTestClassErrorTest.java b/src/test/java/org/junit/runners/model/InvalidTestClassErrorTest.java new file mode 100644 index 000000000000..7d92dd42f600 --- /dev/null +++ b/src/test/java/org/junit/runners/model/InvalidTestClassErrorTest.java @@ -0,0 +1,23 @@ +package org.junit.runners.model; + +import org.junit.Test; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +public class InvalidTestClassErrorTest { + + @Test + public void invalidTestClassErrorShouldListAllValidationErrorsInItsMessage() { + InvalidTestClassError sut = new InvalidTestClassError(SampleTestClass.class, + asList(new Throwable("validation error 1"), new Throwable("validation error 2"))); + + assertThat(sut.getMessage(), equalTo("Invalid test class '" + SampleTestClass.class.getName() + "':" + + "\n 1. validation error 1" + + "\n 2. validation error 2")); + } + + private static class SampleTestClass { + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/runners/model/RunnerBuilderStub.java b/src/test/java/org/junit/runners/model/RunnerBuilderStub.java new file mode 100644 index 000000000000..2e111372d933 --- /dev/null +++ b/src/test/java/org/junit/runners/model/RunnerBuilderStub.java @@ -0,0 +1,11 @@ +package org.junit.runners.model; + +import org.junit.runner.Runner; +import org.junit.runner.RunnerSpy; + +public class RunnerBuilderStub extends RunnerBuilder { + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + return new RunnerSpy(testClass, this); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/runners/model/TestClassTest.java b/src/test/java/org/junit/runners/model/TestClassTest.java new file mode 100644 index 000000000000..7682968c1742 --- /dev/null +++ b/src/test/java/org/junit/runners/model/TestClassTest.java @@ -0,0 +1,245 @@ +package org.junit.runners.model; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.lang.annotation.Annotation; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TestRule; +import org.junit.runner.RunWith; + +public class TestClassTest { + + @Rule + public ExpectedException exception = ExpectedException.none(); + + public static class TwoConstructors { + public TwoConstructors() { + } + + public TwoConstructors(int x) { + } + } + + @Test(expected = IllegalArgumentException.class) + public void complainIfMultipleConstructors() { + new TestClass(TwoConstructors.class); + } + + 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)); + } + + public static class FieldAnnotated { + @Rule + public String fieldC= "andromeda"; + + @Rule + public boolean fieldA; + + @Rule + public boolean fieldB; + } + + @Test + public void providesAnnotatedFieldsSortedByName() { + TestClass tc= new TestClass(FieldAnnotated.class); + List annotatedFields= tc.getAnnotatedFields(); + assertThat("Wrong number of annotated fields.", annotatedFields.size(), is(3)); + assertThat("First annotated field is wrong.", annotatedFields + .iterator().next().getName(), is("fieldA")); + } + + @Test + public void annotatedFieldValues() { + TestClass tc = new TestClass(FieldAnnotated.class); + List values = tc.getAnnotatedFieldValues(new FieldAnnotated(), Rule.class, String.class); + assertThat(values, hasItem("andromeda")); + assertThat(values.size(), is(1)); + } + + public static class MethodsAnnotated { + @Ignore + @Test + public int methodC() { + return 0; + } + + @Ignore + @Test + public String methodA() { + return "jupiter"; + } + + @Ignore + @Test + public int methodB() { + return 0; + } + } + + @Test + public void providesAnnotatedMethodsSortedByName() { + TestClass tc = new TestClass(MethodsAnnotated.class); + List annotatedMethods = tc.getAnnotatedMethods(); + assertThat("Wrong number of annotated methods.", + annotatedMethods.size(), is(3)); + assertThat("First annotated method is wrong.", annotatedMethods + .iterator().next().getName(), is("methodA")); + } + + @Test + public void annotatedMethodValues() { + TestClass tc = new TestClass(MethodsAnnotated.class); + List values = tc.getAnnotatedMethodValues( + new MethodsAnnotated(), Ignore.class, String.class); + assertThat(values, hasItem("jupiter")); + assertThat(values.size(), is(1)); + } + + @Test + public void isEqualToTestClassThatWrapsSameJavaClass() { + TestClass testClass = new TestClass(DummyClass.class); + TestClass testClassThatWrapsSameJavaClass = new TestClass( + DummyClass.class); + assertTrue(testClass.equals(testClassThatWrapsSameJavaClass)); + } + + @Test + public void isEqualToTestClassThatWrapsNoJavaClassToo() { + TestClass testClass = new TestClass(null); + TestClass testClassThatWrapsNoJavaClassToo = new TestClass(null); + assertTrue(testClass.equals(testClassThatWrapsNoJavaClassToo)); + } + + @Test + public void isNotEqualToTestClassThatWrapsADifferentJavaClass() { + TestClass testClass = new TestClass(DummyClass.class); + TestClass testClassThatWrapsADifferentJavaClass = new TestClass( + AnotherDummyClass.class); + assertFalse(testClass.equals(testClassThatWrapsADifferentJavaClass)); + } + + @Test + public void isNotEqualToNull() { + TestClass testClass = new TestClass(DummyClass.class); + assertFalse(testClass.equals(null)); + } + + private static class DummyClass { + } + + private static class AnotherDummyClass { + } + + @Test + public void hasSameHashCodeAsTestClassThatWrapsSameJavaClass() { + TestClass testClass = new TestClass(DummyClass.class); + TestClass testClassThatWrapsSameJavaClass = new TestClass( + DummyClass.class); + assertEquals(testClass.hashCode(), + testClassThatWrapsSameJavaClass.hashCode()); + } + + @Test + public void hasHashCodeWithoutJavaClass() { + TestClass testClass = new TestClass(null); + testClass.hashCode(); + // everything is fine if no exception is thrown. + } + + public static class PublicClass { + + } + + @Test + public void identifiesPublicModifier() { + TestClass tc = new TestClass(PublicClass.class); + assertEquals("Wrong flag 'public',", true, tc.isPublic()); + } + + static class NonPublicClass { + + } + + @Test + public void identifiesNonPublicModifier() { + TestClass tc = new TestClass(NonPublicClass.class); + assertEquals("Wrong flag 'public',", false, tc.isPublic()); + } + + @Ignore + static class AnnotatedClass { + } + + @Test + public void presentAnnotationIsAvailable() { + TestClass tc = new TestClass(AnnotatedClass.class); + Annotation annotation = tc.getAnnotation(Ignore.class); + assertTrue(Ignore.class.isAssignableFrom(annotation.getClass())); + } + + @Test + public void missingAnnotationIsNotAvailable() { + TestClass tc = new TestClass(AnnotatedClass.class); + Annotation annotation = tc.getAnnotation(RunWith.class); + assertThat(annotation, is(nullValue())); + } +} diff --git a/src/test/java/org/junit/runners/parameterized/AllParameterizedTests.java b/src/test/java/org/junit/runners/parameterized/AllParameterizedTests.java new file mode 100644 index 000000000000..9a0f261d4001 --- /dev/null +++ b/src/test/java/org/junit/runners/parameterized/AllParameterizedTests.java @@ -0,0 +1,14 @@ +package org.junit.runners.parameterized; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + BlockJUnit4ClassRunnerWithParametersTest.class, + ParameterizedNamesTest.class, + TestWithParametersTest.class +}) +public class AllParameterizedTests { +} diff --git a/src/test/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersTest.java b/src/test/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersTest.java new file mode 100644 index 000000000000..0bf637402842 --- /dev/null +++ b/src/test/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersTest.java @@ -0,0 +1,45 @@ +package org.junit.runners.parameterized; + +import static java.util.Collections.emptyList; +import static org.junit.Assert.assertEquals; + +import java.lang.annotation.Annotation; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.model.TestClass; + +public class BlockJUnit4ClassRunnerWithParametersTest { + private static final List NO_PARAMETERS = emptyList(); + + @RunWith(Parameterized.class) + @DummyAnnotation + public static class ClassWithParameterizedAnnotation { + @Test + public void dummyTest() { + } + } + + @Test + public void hasAllAnnotationsExceptRunWith() throws Exception { + TestWithParameters testWithParameters = new TestWithParameters( + "dummy name", new TestClass( + ClassWithParameterizedAnnotation.class), NO_PARAMETERS); + BlockJUnit4ClassRunnerWithParameters runner = new BlockJUnit4ClassRunnerWithParameters( + testWithParameters); + Annotation[] annotations = runner.getRunnerAnnotations(); + assertEquals(1, annotations.length); + assertEquals(annotations[0].annotationType(), DummyAnnotation.class); + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + private static @interface DummyAnnotation { + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/runners/parameterized/ParameterizedNamesTest.java b/src/test/java/org/junit/runners/parameterized/ParameterizedNamesTest.java new file mode 100644 index 000000000000..25dedfebda9b --- /dev/null +++ b/src/test/java/org/junit/runners/parameterized/ParameterizedNamesTest.java @@ -0,0 +1,51 @@ +package org.junit.runners.parameterized; + +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.Request; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; + +/** + * @author Dmitry Baev charlie@yandex-team.ru + * Date: 03.05.14 + */ +public class ParameterizedNamesTest { + @RunWith(Parameterized.class) + public static class ParametrizedWithSpecialCharsInName { + + public ParametrizedWithSpecialCharsInName(String s) { + } + + @Parameterized.Parameters(name = "{0}") + public static Collection data() { + return Arrays.asList( + new Object[]{"\n"}, + new Object[]{"\r\n"}, + new Object[]{"\r"}, + new Object[]{"\u0085"}, + new Object[]{"\u2028"}, + new Object[]{"\u2029"} + ); + } + + @Test + public void test() { + } + } + + @Test + public void parameterizedTestsWithSpecialCharsInName() { + Request request = Request.aClass(ParametrizedWithSpecialCharsInName.class); + for (Description parent : request.getRunner().getDescription().getChildren()) { + for (Description description : parent.getChildren()) { + assertEquals("test" + parent.getDisplayName(), description.getMethodName()); + } + } + } +} diff --git a/src/test/java/org/junit/runners/parameterized/TestWithParametersTest.java b/src/test/java/org/junit/runners/parameterized/TestWithParametersTest.java new file mode 100644 index 000000000000..b8156e9fbd7b --- /dev/null +++ b/src/test/java/org/junit/runners/parameterized/TestWithParametersTest.java @@ -0,0 +1,137 @@ +package org.junit.runners.parameterized; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.rules.ExpectedException.none; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runners.model.TestClass; + +public class TestWithParametersTest { + private static final String DUMMY_NAME = "dummy name"; + + private static final TestClass DUMMY_TEST_CLASS = new TestClass( + DummyClass.class); + + private static final List DUMMY_PARAMETERS = Arrays + . asList("a", "b"); + + @Rule + public final ExpectedException thrown = none(); + + @Test + public void cannotBeCreatedWithoutAName() { + thrown.expect(NullPointerException.class); + thrown.expectMessage("The name is missing."); + new TestWithParameters(null, DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + } + + @Test + public void cannotBeCreatedWithoutTestClass() { + thrown.expect(NullPointerException.class); + thrown.expectMessage("The test class is missing."); + new TestWithParameters(DUMMY_NAME, null, DUMMY_PARAMETERS); + } + + @Test + public void cannotBeCreatedWithoutParameters() { + thrown.expect(NullPointerException.class); + thrown.expectMessage("The parameters are missing."); + new TestWithParameters(DUMMY_NAME, DUMMY_TEST_CLASS, + (List) null); + } + + @Test + public void doesNotAllowToModifyProvidedParameters() { + TestWithParameters test = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + thrown.expect(UnsupportedOperationException.class); + test.getParameters().set(0, "another parameter"); + } + + @Test + public void doesNotConsiderParametersWhichChangedAfterTestInstantiation() { + List parameters = Arrays. asList("dummy parameter"); + TestWithParameters test = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, parameters); + parameters.set(0, "another parameter"); + assertEquals(asList("dummy parameter"), test.getParameters()); + } + + @Test + public void isEqualToTestWithSameNameAndTestClassAndParameters() { + TestWithParameters firstTest = new TestWithParameters(DUMMY_NAME, + new TestClass(DummyClass.class), Arrays. asList("a", + "b")); + TestWithParameters secondTest = new TestWithParameters(DUMMY_NAME, + new TestClass(DummyClass.class), Arrays. asList("a", + "b")); + assertEquals(firstTest, secondTest); + } + + @Test + public void isNotEqualToTestWithDifferentName() { + TestWithParameters firstTest = new TestWithParameters("name", + DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + TestWithParameters secondTest = new TestWithParameters("another name", + DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + assertNotEquals(firstTest, secondTest); + } + + @Test + public void isNotEqualToTestWithDifferentTestClass() { + TestWithParameters firstTest = new TestWithParameters(DUMMY_NAME, + new TestClass(DummyClass.class), DUMMY_PARAMETERS); + TestWithParameters secondTest = new TestWithParameters(DUMMY_NAME, + new TestClass(AnotherDummyClass.class), DUMMY_PARAMETERS); + assertNotEquals(firstTest, secondTest); + } + + @Test + public void isNotEqualToTestWithDifferentParameters() { + TestWithParameters firstTest = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, Arrays. asList("a")); + TestWithParameters secondTest = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, Arrays. asList("b")); + assertNotEquals(firstTest, secondTest); + } + + @Test + public void isNotEqualToObjectWithDifferentClass() { + TestWithParameters test = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + assertNotEquals(test, new Integer(3)); + } + + @Test + public void hasSameHashCodeAsEqualTest() { + TestWithParameters firstTest = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + TestWithParameters secondTest = new TestWithParameters(DUMMY_NAME, + DUMMY_TEST_CLASS, DUMMY_PARAMETERS); + assertEquals(firstTest.hashCode(), secondTest.hashCode()); + } + + @Test + public void hasMeaningfulToString() { + TestWithParameters test = new TestWithParameters("name", new TestClass( + DummyClass.class), Arrays. asList("first parameter", + "second parameter")); + assertEquals( + "Wrong toString().", + "org.junit.runners.parameterized.TestWithParametersTest$DummyClass 'name' with parameters [first parameter, second parameter]", + test.toString()); + } + + private static class DummyClass { + } + + private static class AnotherDummyClass { + } +} diff --git a/src/test/java/org/junit/samples/AllSamplesTests.java b/src/test/java/org/junit/samples/AllSamplesTests.java new file mode 100644 index 000000000000..cbd5fce30dc5 --- /dev/null +++ b/src/test/java/org/junit/samples/AllSamplesTests.java @@ -0,0 +1,14 @@ +package org.junit.samples; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.samples.money.MoneyTest; + +@RunWith(Suite.class) +@SuiteClasses({ + ListTest.class, + MoneyTest.class +}) +public class AllSamplesTests { +} diff --git a/src/test/java/org/junit/samples/ListTest.java b/src/test/java/org/junit/samples/ListTest.java new file mode 100644 index 000000000000..02ade826a888 --- /dev/null +++ b/src/test/java/org/junit/samples/ListTest.java @@ -0,0 +1,91 @@ +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.ArrayList}. + */ +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/src/test/java/org/junit/samples/SimpleTest.java b/src/test/java/org/junit/samples/SimpleTest.java new file mode 100644 index 000000000000..02bae09e5f9b --- /dev/null +++ b/src/test/java/org/junit/samples/SimpleTest.java @@ -0,0 +1,47 @@ +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. + * + *

      This test is expected to fail. + */ +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/src/test/java/org/junit/samples/money/MoneyTest.java b/src/test/java/org/junit/samples/money/MoneyTest.java new file mode 100644 index 000000000000..617bcecd8b49 --- /dev/null +++ b/src/test/java/org/junit/samples/money/MoneyTest.java @@ -0,0 +1,205 @@ +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/src/test/java/org/junit/samples/money/package-info.java b/src/test/java/org/junit/samples/money/package-info.java new file mode 100644 index 000000000000..2429514258f6 --- /dev/null +++ b/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/src/test/java/org/junit/samples/package-info.java b/src/test/java/org/junit/samples/package-info.java new file mode 100644 index 000000000000..ec52263d133b --- /dev/null +++ b/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/src/test/java/org/junit/tests/AllTests.java b/src/test/java/org/junit/tests/AllTests.java new file mode 100644 index 000000000000..fd9169121d1a --- /dev/null +++ b/src/test/java/org/junit/tests/AllTests.java @@ -0,0 +1,49 @@ +package org.junit.tests; + +import junit.framework.JUnit4TestAdapter; +import junit.framework.Test; +import org.junit.AssumptionViolatedExceptionTest; +import org.junit.internal.AllInternalTests; +import org.junit.rules.AllRulesTests; +import org.junit.runner.AllRunnerTests; +import org.junit.runner.RunWith; +import org.junit.runners.AllRunnersTests; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.samples.AllSamplesTests; +import org.junit.tests.assertion.AllAssertionTests; +import org.junit.tests.deprecated.AllDeprecatedTests; +import org.junit.tests.description.AllDescriptionTests; +import org.junit.tests.experimental.AllExperimentalTests; +import org.junit.tests.junit3compatibility.AllJUnit3CompatibilityTests; +import org.junit.tests.listening.AllListeningTests; +import org.junit.tests.manipulation.AllManipulationTests; +import org.junit.tests.running.AllRunningTests; +import org.junit.tests.validation.AllValidationTests; +import org.junit.validator.AllValidatorTests; + +@RunWith(Suite.class) +@SuiteClasses({ + AllAssertionTests.class, + AllDeprecatedTests.class, + AllDescriptionTests.class, + AllExperimentalTests.class, + AllInternalTests.class, + AllJUnit3CompatibilityTests.class, + AllListeningTests.class, + AllManipulationTests.class, + AllRulesTests.class, + AllRunnersTests.class, + AllRunnerTests.class, + AllRunningTests.class, + AllSamplesTests.class, + AllValidationTests.class, + AllValidatorTests.class, + AssumptionViolatedExceptionTest.class, + ObjectContractTest.class +}) +public class AllTests { + public static Test suite() { + return new JUnit4TestAdapter(AllTests.class); + } +} diff --git a/src/test/java/org/junit/tests/ObjectContractTest.java b/src/test/java/org/junit/tests/ObjectContractTest.java new file mode 100644 index 000000000000..27172f93cb93 --- /dev/null +++ b/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/src/test/java/org/junit/tests/TestSystem.java b/src/test/java/org/junit/tests/TestSystem.java new file mode 100644 index 000000000000..d74166ca91b0 --- /dev/null +++ b/src/test/java/org/junit/tests/TestSystem.java @@ -0,0 +1,35 @@ +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); + } + + /** + * Will be removed in the next major release + */ + @Deprecated + public void exit(int code) { + fCode = code; + } + + public PrintStream out() { + return out; + } + + public OutputStream outContents() { + return fOutContents; + } + +} diff --git a/src/test/java/org/junit/tests/assertion/AllAssertionTests.java b/src/test/java/org/junit/tests/assertion/AllAssertionTests.java new file mode 100644 index 000000000000..5190e9439f5e --- /dev/null +++ b/src/test/java/org/junit/tests/assertion/AllAssertionTests.java @@ -0,0 +1,14 @@ +package org.junit.tests.assertion; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AssertionTest.class, + ComparisonFailureTest.class, + MultipleFailureExceptionTest.class +}) +public class AllAssertionTests { +} diff --git a/src/test/java/org/junit/tests/assertion/AssertionTest.java b/src/test/java/org/junit/tests/assertion/AssertionTest.java new file mode 100755 index 000000000000..fabda1336761 --- /dev/null +++ b/src/test/java/org/junit/tests/assertion/AssertionTest.java @@ -0,0 +1,874 @@ +package org.junit.tests.assertion; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.expectThrows; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.math.BigDecimal; + +import org.junit.Assert; +import org.junit.ComparisonFailure; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +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 + public void arraysNotEqual() { + assertArrayEqualsFailure( + new Object[]{"right"}, + new Object[]{"wrong"}, + "arrays first differed at element [0]; expected:<[right]> but was:<[wrong]>"); + } + + @Test + public void arraysNotEqualWithMessage() { + assertArrayEqualsFailure( + "not equal", + new Object[]{"right"}, + new Object[]{"wrong"}, + "not equal: arrays first differed at element [0]; expected:<[right]> but was:<[wrong]>"); + } + + @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()); + return; + } + fail("should have thrown an exception"); + } + + @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()); + return; + } + fail("should have thrown an exception"); + } + + @Test + public void arraysDifferentLengthDifferingAtStartMessage() { + assertArrayEqualsFailure( + "not equal", + new Object[]{true}, + new Object[]{false, true}, + "not equal: array lengths differed, expected.length=1 actual.length=2; arrays first differed at element [0]; expected: but was:"); + } + + @Test + public void arraysDifferentLengthDifferingAtEndMessage() { + assertArrayEqualsFailure( + "not equal", + new Object[]{true}, + new Object[]{true, false}, + "not equal: array lengths differed, expected.length=1 actual.length=2; arrays first differed at element [1]; expected: but was:"); + } + + @Test + public void arraysDifferentLengthDifferingAtEndAndExpectedArrayLongerMessage() { + assertArrayEqualsFailure( + "not equal", + new Object[]{true, false}, + new Object[]{true}, + "not equal: array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1]; expected: but was:"); + } + + @Test + public void arraysElementsDiffer() { + assertArrayEqualsFailure( + "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"}, + "not equal: arrays first differed at element [0]; expected: but was:"); + } + + @Test + public void arraysDifferAtElement0nullMessage() { + assertArrayEqualsFailure( + new Object[]{true}, + new Object[]{false}, + "arrays first differed at element [0]; expected: but was:" + ); + } + + @Test + public void arraysDifferAtElement1nullMessage() { + assertArrayEqualsFailure( + new Object[]{true, true}, + new Object[]{true, false}, + "arrays first differed at element [1]; expected: but was:" + ); + } + + @Test + public void arraysDifferAtElement0withMessage() { + assertArrayEqualsFailure( + "message", + new Object[]{true}, + new Object[]{false}, + "message: arrays first differed at element [0]; expected: but was:" + ); + } + + @Test + public void arraysDifferAtElement1withMessage() { + assertArrayEqualsFailure( + "message", + new Object[]{true, true}, + new Object[]{true, false}, + "message: arrays first differed at element [1]; expected: but was:" + ); + } + + @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 boolean[]{true}, new boolean[]{true}); + 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 oneDimensionalBooleanArraysAreNotEqual() { + assertArrayEquals(new boolean[]{true}, new boolean[]{false}); + } + + @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() { + assertArrayEqualsFailure( + "message", + new Object[][]{{true, true}, {false, false}}, + new Object[][]{{true, true}, {true, false}}, + "message: arrays first differed at element [1][0]; expected: but was:"); + } + + @Test + public void multiDimensionalArraysAreNotEqualNoMessage() { + assertArrayEqualsFailure( + new Object[][]{{true, true}, {false, false}}, + new Object[][]{{true, true}, {true, false}}, + "arrays first differed at element [1][0]; expected: but was:"); + } + + @Test + public void twoDimensionalArraysDifferentOuterLengthNotEqual() { + assertArrayEqualsFailure( + "not equal", + new Object[][]{{true}, {}}, + new Object[][]{{}}, + "not equal: array lengths differed, expected.length=1 actual.length=0; arrays first differed at element [0][0]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new Object[][]{{}, {true}}, + new Object[][]{{}}, + "not equal: array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new Object[][]{{}}, + new Object[][]{{true}, {}}, + "not equal: array lengths differed, expected.length=0 actual.length=1; arrays first differed at element [0][0]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new Object[][]{{}}, + new Object[][]{{}, {true}}, + "not equal: array lengths differed, expected.length=1 actual.length=2; arrays first differed at element [1]; expected: but was:"); + } + + @Test + public void primitiveArraysConvertedToStringCorrectly() { + assertArrayEqualsFailure( + "not equal", + new boolean[][]{{}, {true}}, + new boolean[][]{{}}, + "not equal: array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new int[][]{{}, {23}}, + new int[][]{{}}, + "not equal: array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1]; expected: but was:"); + } + + @Test + public void twoDimensionalArraysConvertedToStringCorrectly() { + assertArrayEqualsFailure( + "not equal", + new Object[][][]{{}, {{true}}}, + new Object[][][]{{}}, + "not equal: array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1]; expected: but was:"); + } + + @Test + public void twoDimensionalArraysDifferentInnerLengthNotEqual() { + assertArrayEqualsFailure( + "not equal", + new Object[][]{{true}, {}}, + new Object[][]{{}, {}}, + "not equal: array lengths differed, expected.length=1 actual.length=0; arrays first differed at element [0][0]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new Object[][]{{}, {true}}, + new Object[][]{{}, {}}, + "not equal: array lengths differed, expected.length=1 actual.length=0; arrays first differed at element [1][0]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new Object[][]{{}, {}}, + new Object[][]{{true}, {}}, + "not equal: array lengths differed, expected.length=0 actual.length=1; arrays first differed at element [0][0]; expected: but was:"); + assertArrayEqualsFailure( + "not equal", + new Object[][]{{}, {}}, + new Object[][]{{}, {true}}, + "not equal: array lengths differed, expected.length=0 actual.length=1; arrays first differed at element [1][0]; expected: but was:"); + } + + private void assertArrayEqualsFailure(Object[] expecteds, Object[] actuals, String expectedMessage) { + try { + assertArrayEquals(expecteds, actuals); + } catch (ArrayComparisonFailure e) { + assertEquals(expectedMessage, e.getMessage()); + return; + } + fail("should have thrown an exception"); + } + + private void assertArrayEqualsFailure(String message, Object[] expecteds, Object[] actuals, String expectedMessage) { + try { + assertArrayEquals(message, expecteds, actuals); + } catch (ArrayComparisonFailure e) { + assertEquals(expectedMessage, e.getMessage()); + return; + } + fail("should have thrown an exception"); + } + + @Test + public void multiDimensionalArraysDifferentLengthMessage() { + try { + assertArrayEquals("message", new Object[][]{{true, true}, {false, false}}, new Object[][]{{true, true}, {false}}); + } catch (AssertionError exception) { + assertEquals("message: array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1][1]; expected: but was:", exception.getMessage()); + return; + } + + fail("Expected AssertionError to be thrown"); + } + + @Test + public void multiDimensionalArraysDifferentLengthNoMessage() { + try { + assertArrayEquals(new Object[][]{{true, true}, {false, false}}, new Object[][]{{true, true}, {false}}); + } catch (AssertionError exception) { + assertEquals("array lengths differed, expected.length=2 actual.length=1; arrays first differed at element [1][1]; expected: but was:", exception.getMessage()); + return; + } + + fail("Expected AssertionError to be thrown"); + } + + @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 + public void floatsNotDoublesInArrays() { + float delta = 4.444f; + float[] f1 = new float[]{1.111f}; + float[] f2 = new float[]{5.555f}; + Assert.assertArrayEquals(f1, f2, delta); + } + + @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); + } + + @SuppressWarnings("unused") + @Test + public void nullNullmessage() { + try { + assertNull("junit"); + fail(); + } catch (AssertionError e) { + assertEquals("expected null, but was:", e.getMessage()); + } + } + + @SuppressWarnings("unused") + @Test + public void nullWithMessage() { + try { + assertNull("message", "hello"); + fail(); + } catch (AssertionError exception) { + assertEquals("message expected null, but was:", exception.getMessage()); + } + } + + @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 but: was \"actual\""; + + 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 but: \"actual\" is a java.lang.String"; + + try { + assertThat("identifier", "actual", is(instanceOf(Integer.class))); + } catch (AssertionError e) { + assertEquals(expectedMessage, e.getMessage()); + } + } + + @Test + public void assertThatDescriptionCanBeElided() { + String expected = "expected"; + String actual = "actual"; + + String expectedMessage = "\nExpected: \"expected\"\n but: was \"actual\""; + + 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); + } + + @Test(expected = AssertionError.class) + public void sameObjectIsNotEqual() { + Object o = new Object(); + assertNotEquals(o, o); + } + + @Test + public void objectsWithDiferentReferencesAreNotEqual() { + assertNotEquals(new Object(), new Object()); + } + + @Test + public void assertNotEqualsIncludesCorrectMessage() { + Integer value1 = new Integer(1); + Integer value2 = new Integer(1); + String message = "The values should be different"; + + try { + assertNotEquals(message, value1, value2); + } catch (AssertionError e) { + assertEquals(message + ". Actual: " + value1, e.getMessage()); + return; + } + + fail("Failed on assertion."); + } + + @Test + public void assertNotEqualsIncludesTheValueBeingTested() { + Integer value1 = new Integer(1); + Integer value2 = new Integer(1); + + try { + assertNotEquals(value1, value2); + } catch (AssertionError e) { + assertTrue(e.getMessage().contains(value1.toString())); + return; + } + + fail("Failed on assertion."); + } + + @Test + public void assertNotEqualsWorksWithPrimitiveTypes() { + assertNotEquals(1L, 2L); + assertNotEquals("The values should be different", 1L, 2L); + assertNotEquals(1.0, 2.0, 0); + assertNotEquals("The values should be different", 1.0, 2.0, 0); + assertNotEquals(1.0f, 2.0f, 0f); + assertNotEquals("The values should be different", 1.0f, 2.0f, 0f); + } + + @Test(expected = AssertionError.class) + public void assertNotEqualsConsidersDeltaCorrectly() { + assertNotEquals(1.0, 0.9, 0.1); + } + + @Test(expected = AssertionError.class) + public void assertNotEqualsConsidersFloatDeltaCorrectly() { + assertNotEquals(1.0f, 0.75f, 0.25f); + } + + @Test(expected = AssertionError.class) + public void assertNotEqualsIgnoresDeltaOnNaN() { + assertNotEquals(Double.NaN, Double.NaN, 1); + } + + @Test(expected = AssertionError.class) + public void assertNotEqualsIgnoresFloatDeltaOnNaN() { + assertNotEquals(Float.NaN, Float.NaN, 1f); + } + + @Test(expected = AssertionError.class) + public void expectThrowsRequiresAnExceptionToBeThrown() { + expectThrows(Throwable.class, nonThrowingRunnable()); + } + + @Test + public void expectThrowsIncludesAnInformativeDefaultMessage() { + try { + expectThrows(Throwable.class, nonThrowingRunnable()); + } catch (AssertionError ex) { + assertEquals("expected Throwable to be thrown, but nothing was thrown", ex.getMessage()); + return; + } + fail(); + } + + @Test + public void expectThrowsReturnsTheSameObjectThrown() { + NullPointerException npe = new NullPointerException(); + + Throwable throwable = expectThrows(Throwable.class, throwingRunnable(npe)); + + assertSame(npe, throwable); + } + + @Test(expected = AssertionError.class) + public void expectThrowsDetectsTypeMismatchesViaExplicitTypeHint() { + NullPointerException npe = new NullPointerException(); + + expectThrows(IOException.class, throwingRunnable(npe)); + } + + @Test + public void expectThrowsWrapsAndPropagatesUnexpectedExceptions() { + NullPointerException npe = new NullPointerException("inner-message"); + + try { + expectThrows(IOException.class, throwingRunnable(npe)); + } catch (AssertionError ex) { + assertSame(npe, ex.getCause()); + assertEquals("inner-message", ex.getCause().getMessage()); + return; + } + fail(); + } + + @Test + public void expectThrowsSuppliesACoherentErrorMessageUponTypeMismatch() { + NullPointerException npe = new NullPointerException(); + + try { + expectThrows(IOException.class, throwingRunnable(npe)); + } catch (AssertionError error) { + assertEquals("unexpected exception type thrown; expected: but was:", + error.getMessage()); + assertSame(npe, error.getCause()); + return; + } + fail(); + } + + private static ThrowingRunnable nonThrowingRunnable() { + return new ThrowingRunnable() { + public void run() throws Throwable { + } + }; + } + + private static ThrowingRunnable throwingRunnable(final Throwable t) { + return new ThrowingRunnable() { + public void run() throws Throwable { + throw t; + } + }; + } +} diff --git a/src/test/java/org/junit/tests/assertion/ComparisonFailureTest.java b/src/test/java/org/junit/tests/assertion/ComparisonFailureTest.java new file mode 100644 index 000000000000..17ff2af786ce --- /dev/null +++ b/src/test/java/org/junit/tests/assertion/ComparisonFailureTest.java @@ -0,0 +1,78 @@ +package org.junit.tests.assertion; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.ComparisonFailure; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public class ComparisonFailureTest { + + private String expected, actual, message; + + public ComparisonFailureTest(String e, String a, String m) { + expected = e; + actual = a; + message = m; + } + + @Parameters(name = "compact-msg-{index}, exp=\"{1}\"") + public static Collection data() { + return Arrays.asList(new Object[][] { + // simple base case + { "a", "b", "expected:<[a]> but was:<[b]>" }, + + // common prefix + { "ba", "bc", "expected: but was:" }, + + // common suffix + { "ab", "cb", "expected:<[a]b> but was:<[c]b>" }, + + // common pre and suffix + { "abc", "adc", "expected: but was:" }, + + // expected is subset of actual + { "ab", "abc", "expected: but was:" }, + + // expected is superset of actual + { "abc", "ab", "expected: but was:" }, + + // overlapping matches. + { "abc", "abbc", "expected: but was:" }, + + // long prefix yielding "..." + { "01234567890123456789PRE:hello:POST", + "01234567890123456789PRE:world:POST", + "expected:<...4567890123456789PRE:[hello]:POST> but was:<...4567890123456789PRE:[world]:POST>" }, + + // long suffix yielding "..." + { "PRE:hello:01234567890123456789POST", + "PRE:world:01234567890123456789POST", + "expected: but was:" + }, + + // bug609972 + { "S&P500", "0", "expected:<[S&P50]0> but was:<[]0>" }, + + // empty expected string + { "", "a", "expected:<[]> but was:<[a]>" }, + + // empty actual string + { "a", "", "expected:<[a]> but was:<[]>" } + + }); + } + + @Test + public void compactFailureMessage() { + ComparisonFailure failure = new ComparisonFailure("", expected, actual); + assertEquals(message, failure.getMessage()); + } + +} diff --git a/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java b/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java new file mode 100644 index 000000000000..9999650a6180 --- /dev/null +++ b/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java @@ -0,0 +1,79 @@ +package org.junit.tests.assertion; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.lang.annotation.AnnotationFormatError; +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 Exception { + MultipleFailureException.assertEmpty(Collections.emptyList()); + } + + @Test + public void assertEmptyRethrowsSingleRuntimeException() throws Exception { + Throwable exception= new ExpectedException("pesto"); + List errors= Collections.singletonList(exception); + try { + MultipleFailureException.assertEmpty(errors); + fail(); + } catch (ExpectedException e) { + assertSame(e, exception); + } + } + + @Test + public void assertEmptyRethrowsSingleError() throws Exception { + Throwable exception= new AnnotationFormatError("changeo"); + List errors= Collections.singletonList(exception); + try { + MultipleFailureException.assertEmpty(errors); + fail(); + } catch (AnnotationFormatError e) { + assertSame(e, exception); + } + } + + @Test + public void assertEmptyThrowsMultipleFailureExceptionForManyThrowables() throws Exception { + 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/src/test/java/org/junit/tests/deprecated/AllDeprecatedTests.java b/src/test/java/org/junit/tests/deprecated/AllDeprecatedTests.java new file mode 100644 index 000000000000..4e1a3f42548d --- /dev/null +++ b/src/test/java/org/junit/tests/deprecated/AllDeprecatedTests.java @@ -0,0 +1,13 @@ +package org.junit.tests.deprecated; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@SuppressWarnings("deprecation") +@RunWith(Suite.class) +@SuiteClasses({ + JUnit4ClassRunnerTest.class +}) +public class AllDeprecatedTests { +} diff --git a/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java b/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java new file mode 100644 index 000000000000..43983ba97637 --- /dev/null +++ b/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java @@ -0,0 +1,64 @@ +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/src/test/java/org/junit/tests/description/AllDescriptionTests.java b/src/test/java/org/junit/tests/description/AllDescriptionTests.java new file mode 100644 index 000000000000..6de5efb4e550 --- /dev/null +++ b/src/test/java/org/junit/tests/description/AllDescriptionTests.java @@ -0,0 +1,15 @@ +package org.junit.tests.description; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AnnotatedDescriptionTest.class, + SuiteDescriptionTest.class, + TestDescriptionMethodNameTest.class, + TestDescriptionTest.class +}) +public class AllDescriptionTests { +} diff --git a/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java b/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java new file mode 100644 index 000000000000..cbe35220efdc --- /dev/null +++ b/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/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java b/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java new file mode 100644 index 000000000000..5b17d1e91b35 --- /dev/null +++ b/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java @@ -0,0 +1,38 @@ +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/src/test/java/org/junit/tests/description/TestDescriptionMethodNameTest.java b/src/test/java/org/junit/tests/description/TestDescriptionMethodNameTest.java new file mode 100644 index 000000000000..21943e922608 --- /dev/null +++ b/src/test/java/org/junit/tests/description/TestDescriptionMethodNameTest.java @@ -0,0 +1,50 @@ +package org.junit.tests.description; + +import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * @author Dmitry Baev charlie@yandex-team.ru + * Date: 03.05.14 + */ +@RunWith(Parameterized.class) +public class TestDescriptionMethodNameTest { + + private String methodName; + + public TestDescriptionMethodNameTest(String methodName) { + this.methodName = methodName; + } + + @Parameterized.Parameters + public static Collection getMethodNames() { + return Arrays.asList( + new Object[]{"simple"}, + new Object[]{"with space"}, + new Object[]{"[]!@#$%^&*()"}, + new Object[]{""}, + new Object[]{"\t"}, + new Object[]{"\n"}, + new Object[]{"\r\n"}, + new Object[]{"\r"}, + new Object[]{"\u0085"}, + new Object[]{"\u2028"}, + new Object[]{"\u2029"} + ); + } + + @Test + public void methodNameTest() throws Exception { + Description description = Description.createTestDescription("some-class-name", methodName); + assertNotNull("Method name should be not null", description.getMethodName()); + assertEquals(methodName, description.getMethodName()); + } +} diff --git a/src/test/java/org/junit/tests/description/TestDescriptionTest.java b/src/test/java/org/junit/tests/description/TestDescriptionTest.java new file mode 100644 index 000000000000..3bc07f403a74 --- /dev/null +++ b/src/test/java/org/junit/tests/description/TestDescriptionTest.java @@ -0,0 +1,24 @@ +package org.junit.tests.description; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +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))); + } + + @Test + public void equalsIsTrueForSameNameAndNoExplicitUniqueId() { + assertTrue(Description.createSuiteDescription("Hello").equals(Description.createSuiteDescription("Hello"))); + } + + @Test + public void equalsIsFalseForSameNameAndDifferentUniqueId() { + assertFalse(Description.createSuiteDescription("Hello", 2).equals(Description.createSuiteDescription("Hello", 3))); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/tests/experimental/AllExperimentalTests.java b/src/test/java/org/junit/tests/experimental/AllExperimentalTests.java new file mode 100644 index 000000000000..58c3219c3ea0 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/AllExperimentalTests.java @@ -0,0 +1,39 @@ +package org.junit.tests.experimental; + +import org.junit.experimental.categories.AllCategoriesTests; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.tests.experimental.max.AllMaxTests; +import org.junit.tests.experimental.parallel.AllParallelTests; +import org.junit.tests.experimental.results.AllResultsTests; +import org.junit.tests.experimental.results.PrintableResultTest; +import org.junit.tests.experimental.results.ResultMatchersTest; +import org.junit.tests.experimental.theories.AllTheoriesTests; +import org.junit.tests.experimental.theories.ParameterSignatureTest; +import org.junit.tests.experimental.theories.extendingwithstubs.StubbedTheoriesTest; +import org.junit.tests.experimental.theories.internal.ParameterizedAssertionErrorTest; +import org.junit.tests.experimental.theories.internal.SpecificDataPointsSupplierTest; +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.WithAutoGeneratedDataPoints; +import org.junit.tests.experimental.theories.runner.WithDataPointMethod; +import org.junit.tests.experimental.theories.runner.WithExtendedParameterSources; +import org.junit.tests.experimental.theories.runner.WithNamedDataPoints; +import org.junit.tests.experimental.theories.runner.WithOnlyTestAnnotations; +import org.junit.tests.experimental.theories.runner.WithUnresolvedGenericTypeVariablesOnTheoryParms; + +@RunWith(Suite.class) +@SuiteClasses({ + AllCategoriesTests.class, + AllMaxTests.class, + AllParallelTests.class, + AllResultsTests.class, + AllTheoriesTests.class, + AssumptionTest.class, + MatcherTest.class, + StubbedTheoriesTest.class +}) +public class AllExperimentalTests { +} diff --git a/src/test/java/org/junit/tests/experimental/AssumptionTest.java b/src/test/java/org/junit/tests/experimental/AssumptionTest.java new file mode 100644 index 000000000000..8c5bbe780129 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/AssumptionTest.java @@ -0,0 +1,283 @@ +package org.junit.tests.experimental; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +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 java.util.ArrayList; +import java.util.List; + +import org.junit.Assume; +import org.junit.AssumptionViolatedException; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +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 + public void assumeThatWorks() { + try { + assumeThat(1, is(2)); + fail("should throw AssumptionViolatedException"); + } catch (AssumptionViolatedException e) { + // expected + } + } + + @Test + public void assumeThatPasses() { + assumeThat(1, is(1)); + assertCompletesNormally(); + } + + @Test + public void assumeThatPassesOnStrings() { + assumeThat("x", is("x")); + assertCompletesNormally(); + } + + @Test + public void assumeNotNullThrowsException() { + Object[] objects = {1, 2, null}; + try { + assumeNotNull(objects); + fail("should throw AssumptionViolatedException"); + } catch (AssumptionViolatedException e) { + // expected + } + } + + @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 + public void assumeTrueWorks() { + try { + Assume.assumeTrue(false); + fail("should throw AssumptionViolatedException"); + } catch (AssumptionViolatedException e) { + // expected + } + } + + 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); + } + + final static String message = "Some random message string."; + final static Throwable e = new Throwable(); + + /** + * @see AssumptionTest#assumptionsWithMessage() + */ + public static class HasAssumeWithMessage { + @Test + public void testMethod() { + assumeTrue(message, false); + } + } + + @Test + public void assumptionsWithMessage() { + final List failures = + runAndGetAssumptionFailures(HasAssumeWithMessage.class); + + assertTrue(failures.get(0).getMessage().contains(message)); + } + + /** + * @see AssumptionTest#assumptionsWithMessageAndCause() + */ + public static class HasAssumeWithMessageAndCause { + @Test + public void testMethod() { + assumeNoException(message, e); + } + } + + @Test + public void assumptionsWithMessageAndCause() { + final List failures = + runAndGetAssumptionFailures(HasAssumeWithMessageAndCause.class); + assertTrue(failures.get(0).getMessage().contains(message)); + assertSame(failures.get(0).getException().getCause(), e); + } + + public static class HasFailingAssumptionWithMessage { + @Test + public void assumptionsFail() { + assumeThat(message, 3, is(4)); + fail(); + } + } + + @Test + public void failedAssumptionsWithMessage() { + final List failures = + runAndGetAssumptionFailures(HasFailingAssumptionWithMessage.class); + + assertEquals(failures.size(), 1); + assertTrue(failures.get(0).getMessage().contains(message)); + } + + /** + * Helper method that runs tests on clazz and returns any + * {@link Failure} objects that were {@link AssumptionViolatedException}s. + */ + private static List runAndGetAssumptionFailures(Class clazz) { + final List failures = new ArrayList(); + final JUnitCore core = new JUnitCore(); + core.addListener(new RunListener() { + @Override + public void testAssumptionFailure(Failure failure) { + failures.add(failure); + } + }); + core.run(clazz); + return failures; + } +} diff --git a/src/test/java/org/junit/tests/experimental/MatcherTest.java b/src/test/java/org/junit/tests/experimental/MatcherTest.java new file mode 100644 index 000000000000..6a1eb42b7c17 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/MatcherTest.java @@ -0,0 +1,44 @@ +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 + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void differentMatchersHaveDifferentDescriptions( + Matcher matcher1, Matcher matcher2, Object 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/src/test/java/org/junit/tests/experimental/max/AllMaxTests.java b/src/test/java/org/junit/tests/experimental/max/AllMaxTests.java new file mode 100644 index 000000000000..d78ca3643a27 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/max/AllMaxTests.java @@ -0,0 +1,14 @@ +package org.junit.tests.experimental.max; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + DescriptionTest.class, + JUnit38SortingTest.class, + MaxStarterTest.class +}) +public class AllMaxTests { +} diff --git a/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java b/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java new file mode 100644 index 000000000000..4d2396ad5cbf --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java @@ -0,0 +1,123 @@ +package org.junit.tests.experimental.max; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; + +import java.lang.annotation.Annotation; +import java.net.URL; +import java.net.URLClassLoader; + +import org.junit.Ignore; +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(""); + } + + @Test(expected = IllegalArgumentException.class) + public void createSuiteDescription_whenNull() { + Description.createSuiteDescription((String) null); + } + + @Test + public void parseClassAndMethodNoAnnotations() throws Exception { + Description description = Description.createTestDescription(Description.class, "aTestMethod"); + + assertThat(description.getClassName(), equalTo("org.junit.runner.Description")); + assertThat(description.getMethodName(), equalTo("aTestMethod")); + assertThat(description.getAnnotations().size(), equalTo(0)); + } + + @Test + public void parseClassAndMethodWithAnnotations() throws Exception { + Annotation[] annotations = + DescriptionTest.class.getMethod("parseClassAndMethodWithAnnotations").getDeclaredAnnotations(); + + Description description = Description.createTestDescription(Description.class, "aTestMethod", annotations); + + assertThat(description.getClassName(), equalTo("org.junit.runner.Description")); + assertThat(description.getMethodName(), equalTo("aTestMethod")); + assertThat(description.getAnnotations().size(), equalTo(1)); + } + + @Test + public void parseClassNameAndMethodUniqueId() throws Exception { + Description description = Description.createTestDescription("not a class name", "aTestMethod", 123); + + assertThat(description.getClassName(), equalTo("not a class name")); + assertThat(description.getMethodName(), equalTo("aTestMethod")); + assertThat(description.getAnnotations().size(), equalTo(0)); + } + + @Test + public void sameNamesButDifferentUniqueIdAreNotEqual() throws Exception { + assertThat(Description.createTestDescription("not a class name", "aTestMethod", 1), + not(equalTo(Description.createTestDescription("not a class name", "aTestMethod", 2)))); + } + + @Test + public void usesPassedInClassObject() throws Exception { + class URLClassLoader2 extends URLClassLoader { + URLClassLoader2(URL... urls) { + super(urls); + } + + @Override // just making public + public Class findClass(String name) throws ClassNotFoundException { + return super.findClass(name); + } + } + URL classpath = Sweet.class.getProtectionDomain().getCodeSource().getLocation(); + URLClassLoader2 loader = new URLClassLoader2(classpath); + Class clazz = loader.findClass(Sweet.class.getName()); + assertEquals(loader, clazz.getClassLoader()); + + Description d = Description.createSuiteDescription(clazz); + assertEquals(clazz, d.getTestClass()); + assertNull(d.getMethodName()); + assertEquals(1, d.getAnnotations().size()); + assertEquals(Ignore.class, d.getAnnotations().iterator().next().annotationType()); + + d = Description.createTestDescription(clazz, "tessed"); + assertEquals(clazz, d.getTestClass()); + assertEquals("tessed", d.getMethodName()); + assertEquals(0, d.getAnnotations().size()); + + d = Description.createTestDescription(clazz, "tessed", clazz.getMethod("tessed").getAnnotations()); + assertEquals(clazz, d.getTestClass()); + assertEquals("tessed", d.getMethodName()); + assertEquals(1, d.getAnnotations().size()); + assertEquals(Test.class, d.getAnnotations().iterator().next().annotationType()); + + d = d.childlessCopy(); + assertEquals(clazz, d.getTestClass()); + assertEquals("tessed", d.getMethodName()); + assertEquals(1, d.getAnnotations().size()); + assertEquals(Test.class, d.getAnnotations().iterator().next().annotationType()); + } + + @Ignore + private static class Sweet { + @Test + public void tessed() { + } + } + +} diff --git a/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java b/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java new file mode 100644 index 000000000000..0d893fb62680 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java @@ -0,0 +1,62 @@ +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/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java b/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java new file mode 100644 index 000000000000..9c8008012270 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java @@ -0,0 +1,292 @@ +package org.junit.tests.experimental.max; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import 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() { + } + } + + @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/src/test/java/org/junit/tests/experimental/parallel/AllParallelTests.java b/src/test/java/org/junit/tests/experimental/parallel/AllParallelTests.java new file mode 100644 index 000000000000..ef21dd23b66f --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/parallel/AllParallelTests.java @@ -0,0 +1,13 @@ +package org.junit.tests.experimental.parallel; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + ParallelClassTest.class, + ParallelMethodTest.class +}) +public class AllParallelTests { +} diff --git a/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java b/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java new file mode 100644 index 000000000000..1752c0df1be1 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java @@ -0,0 +1,79 @@ +package org.junit.tests.experimental.parallel; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.ParallelComputer; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; + +public class ParallelClassTest { + private static final long TIMEOUT = 15; + private static volatile Thread fExample1One = null; + private static volatile Thread fExample1Two = null; + private static volatile Thread fExample2One = null; + private static volatile Thread fExample2Two = null; + private static volatile CountDownLatch fSynchronizer; + + public static class Example1 { + @Test + public void one() throws InterruptedException { + fSynchronizer.countDown(); + assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); + fExample1One = Thread.currentThread(); + } + + @Test + public void two() throws InterruptedException { + fSynchronizer.countDown(); + assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); + fExample1Two = Thread.currentThread(); + } + } + + public static class Example2 { + @Test + public void one() throws InterruptedException { + fSynchronizer.countDown(); + assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); + fExample2One = Thread.currentThread(); + } + + @Test + public void two() throws InterruptedException { + fSynchronizer.countDown(); + assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); + fExample2Two = Thread.currentThread(); + } + } + + @Before + public void init() { + fExample1One = null; + fExample1Two = null; + fExample2One = null; + fExample2Two = null; + fSynchronizer = new CountDownLatch(2); + } + + @Test + public void testsRunInParallel() { + Result result = JUnitCore.runClasses(ParallelComputer.classes(), Example1.class, Example2.class); + assertTrue(result.wasSuccessful()); + assertNotNull(fExample1One); + assertNotNull(fExample1Two); + assertNotNull(fExample2One); + assertNotNull(fExample2Two); + assertThat(fExample1One, is(fExample1Two)); + assertThat(fExample2One, is(fExample2Two)); + assertThat(fExample1One, is(not(fExample2One))); + } +} diff --git a/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java b/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java new file mode 100644 index 000000000000..053e2f5a4eb4 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java @@ -0,0 +1,61 @@ +package org.junit.tests.experimental.parallel; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.ParallelComputer; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; + +public class ParallelMethodTest { + private static final long TIMEOUT = 15; + private static volatile Thread fOne = null; + private static volatile Thread fTwo = null; + + public static class Example { + private static volatile CountDownLatch fSynchronizer; + + @BeforeClass + public static void init() { + fSynchronizer = new CountDownLatch(2); + } + + @Test + public void one() throws InterruptedException { + fSynchronizer.countDown(); + assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); + fOne = Thread.currentThread(); + } + + @Test + public void two() throws InterruptedException { + fSynchronizer.countDown(); + assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); + fTwo = Thread.currentThread(); + } + } + + @Before + public void init() { + fOne = null; + fTwo = null; + } + + @Test + public void testsRunInParallel() { + Result result = JUnitCore.runClasses(ParallelComputer.methods(), Example.class); + assertTrue(result.wasSuccessful()); + assertNotNull(fOne); + assertNotNull(fTwo); + assertThat(fOne, is(not(fTwo))); + } +} diff --git a/src/test/java/org/junit/tests/experimental/results/AllResultsTests.java b/src/test/java/org/junit/tests/experimental/results/AllResultsTests.java new file mode 100644 index 000000000000..f1975696b3d9 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/results/AllResultsTests.java @@ -0,0 +1,13 @@ +package org.junit.tests.experimental.results; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + PrintableResultTest.class, + ResultMatchersTest.class +}) +public class AllResultsTests { +} diff --git a/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java b/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java new file mode 100644 index 000000000000..ba9ae3d5f141 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java @@ -0,0 +1,50 @@ +package org.junit.tests.experimental.results; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +import 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 { + @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/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java b/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java new file mode 100644 index 000000000000..024fe32b09fa --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java @@ -0,0 +1,23 @@ +package org.junit.tests.experimental.results; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import 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/src/test/java/org/junit/tests/experimental/theories/AllTheoriesTests.java b/src/test/java/org/junit/tests/experimental/theories/AllTheoriesTests.java new file mode 100644 index 000000000000..41d653bcf77a --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/AllTheoriesTests.java @@ -0,0 +1,19 @@ +package org.junit.tests.experimental.theories; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.tests.experimental.theories.internal.AllTheoriesInternalTests; +import org.junit.tests.experimental.theories.runner.AllTheoriesRunnerTests; + +@RunWith(Suite.class) +@SuiteClasses({ + AllTheoriesInternalTests.class, + AllTheoriesRunnerTests.class, + ParameterSignatureTest.class, + TestedOnSupplierTest.class, + AssumingInTheoriesTest.class, + PotentialAssignmentTest.class +}) +public class AllTheoriesTests { +} diff --git a/src/test/java/org/junit/tests/experimental/theories/AssumingInTheoriesTest.java b/src/test/java/org/junit/tests/experimental/theories/AssumingInTheoriesTest.java new file mode 100644 index 000000000000..758e6fbe2b2d --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/AssumingInTheoriesTest.java @@ -0,0 +1,42 @@ +package org.junit.tests.experimental.theories; + +import static org.junit.tests.experimental.theories.TheoryTestUtils.runTheoryClass; +import org.junit.Assert; +import org.junit.Assume; +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.Result; +import org.junit.runner.RunWith; +import org.junit.runners.model.InitializationError; + +@RunWith(Theories.class) +public class AssumingInTheoriesTest { + + @Test + public void noTheoryAnnotationMeansAssumeShouldIgnore() { + Assume.assumeTrue(false); + } + + @Test + public void theoryMeansOnlyAssumeShouldFail() throws InitializationError { + Result result = runTheoryClass(TheoryWithNoUnassumedParameters.class); + Assert.assertEquals(1, result.getFailureCount()); + } + + /** + * Simple class that SHOULD fail because no parameters are met. + */ + public static class TheoryWithNoUnassumedParameters { + + @DataPoint + public final static boolean FALSE = false; + + @Theory + public void theoryWithNoUnassumedParameters(boolean value) { + Assume.assumeTrue(value); + } + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java b/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java new file mode 100644 index 000000000000..edfcdd1c841b --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java @@ -0,0 +1,92 @@ +package org.junit.tests.experimental.theories; + +import static org.hamcrest.CoreMatchers.isA; +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.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.List; + +import org.hamcrest.CoreMatchers; +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 = getClass().getMethod("foo", int.class); + List annotations = ParameterSignature.signatures(method) + .get(0).getAnnotations(); + assertThat(annotations, + CoreMatchers.hasItem(isA(TestedOn.class))); + } + + public void intMethod(int param) { + } + + public void integerMethod(Integer param) { + } + + public void numberMethod(Number param) { + } + + @Test + public void primitiveTypesShouldBeAcceptedAsWrapperTypes() throws Exception { + List signatures = ParameterSignature + .signatures(getClass().getMethod("integerMethod", Integer.class)); + ParameterSignature integerSignature = signatures.get(0); + + assertTrue(integerSignature.canAcceptType(int.class)); + } + + @Test + public void primitiveTypesShouldBeAcceptedAsWrapperTypeAssignables() throws Exception { + List signatures = ParameterSignature + .signatures(getClass().getMethod("numberMethod", Number.class)); + ParameterSignature numberSignature = signatures.get(0); + + assertTrue(numberSignature.canAcceptType(int.class)); + } + + @Test + public void wrapperTypesShouldBeAcceptedAsPrimitiveTypes() throws Exception { + List signatures = ParameterSignature + .signatures(getClass().getMethod("intMethod", int.class)); + ParameterSignature intSignature = signatures.get(0); + + assertTrue(intSignature.canAcceptType(Integer.class)); + } +} diff --git a/src/test/java/org/junit/tests/experimental/theories/PotentialAssignmentTest.java b/src/test/java/org/junit/tests/experimental/theories/PotentialAssignmentTest.java new file mode 100644 index 000000000000..45071ed0a36f --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/PotentialAssignmentTest.java @@ -0,0 +1,57 @@ +package org.junit.tests.experimental.theories; + +import static org.junit.Assert.*; +import org.junit.Test; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException; + +public class PotentialAssignmentTest { + + @Test + public void shouldUseQuotedValueInDescription() throws CouldNotGenerateValueException { + String name = "stringDatapoint"; + Object value = new Object() { + @Override + public String toString() { + return "string value"; + } + }; + + PotentialAssignment assignment = PotentialAssignment.forValue(name, value); + + assertEquals("\"string value\" ", assignment.getDescription()); + } + + @Test + public void shouldNotUseQuotesForNullValueDescriptions() throws CouldNotGenerateValueException { + String name = "nullDatapoint"; + Object value = null; + + PotentialAssignment assignment = PotentialAssignment.forValue(name, value); + + assertEquals("null ", assignment.getDescription()); + } + + @Test + public void shouldIncludeFailureInDescriptionIfToStringFails() throws CouldNotGenerateValueException { + String name = "explodingValue"; + Object value = new Object() { + @Override + public String toString() { + throw new RuntimeException("Oh no!"); + } + }; + + PotentialAssignment assignment = PotentialAssignment.forValue(name, value); + + assertEquals("[toString() threw RuntimeException: Oh no!] ", assignment.getDescription()); + } + + @Test + public void shouldReturnGivenValue() throws CouldNotGenerateValueException { + Object value = new Object(); + PotentialAssignment assignment = PotentialAssignment.forValue("name", value); + assertEquals(value, assignment.getValue()); + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/TestedOnSupplierTest.java b/src/test/java/org/junit/tests/experimental/theories/TestedOnSupplierTest.java new file mode 100644 index 000000000000..90fcd461dd86 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/TestedOnSupplierTest.java @@ -0,0 +1,32 @@ +package org.junit.tests.experimental.theories; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.lang.reflect.Method; +import java.util.List; + +import org.junit.Test; +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.suppliers.TestedOn; +import org.junit.experimental.theories.suppliers.TestedOnSupplier; + +public class TestedOnSupplierTest { + + public void foo(@TestedOn(ints = {1}) int x) { + } + + @Test + public void descriptionStatesParameterName() throws Exception { + TestedOnSupplier supplier = new TestedOnSupplier(); + List assignments = supplier.getValueSources(signatureOfFoo()); + assertThat(assignments.get(0).getDescription(), is("\"1\" ")); + } + + private ParameterSignature signatureOfFoo() throws NoSuchMethodException { + Method method = getClass().getMethod("foo", int.class); + return ParameterSignature.signatures(method).get(0); + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/TheoryTestUtils.java b/src/test/java/org/junit/tests/experimental/theories/TheoryTestUtils.java new file mode 100644 index 000000000000..6e1b35165cc2 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/TheoryTestUtils.java @@ -0,0 +1,33 @@ +package org.junit.tests.experimental.theories; + +import java.lang.reflect.Method; +import java.util.List; + +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.internal.Assignments; +import org.junit.runner.JUnitCore; +import org.junit.runner.Request; +import org.junit.runner.Result; +import org.junit.runner.Runner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.TestClass; + +public final class TheoryTestUtils { + + private TheoryTestUtils() { } + + public static List potentialAssignments(Method method) + throws Throwable { + return Assignments.allUnassigned(method, + new TestClass(method.getDeclaringClass())) + .potentialsForNextUnassigned(); + } + + public static Result runTheoryClass(Class testClass) throws InitializationError { + Runner theoryRunner = new Theories(testClass); + Request request = Request.runner(theoryRunner); + return new JUnitCore().run(request); + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.java new file mode 100644 index 000000000000..81297b52010f --- /dev/null +++ b/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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java new file mode 100644 index 000000000000..e57a3b320616 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java @@ -0,0 +1,126 @@ +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.Map.Entry; +import java.util.Random; + +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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java new file mode 100644 index 000000000000..272263133ddb --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java @@ -0,0 +1,58 @@ +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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java new file mode 100644 index 000000000000..b79ac2b22603 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java @@ -0,0 +1,55 @@ +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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.java new file mode 100644 index 000000000000..6c1fe75739f6 --- /dev/null +++ b/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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java new file mode 100644 index 000000000000..de3ce986a6e4 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.java @@ -0,0 +1,29 @@ +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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java new file mode 100644 index 000000000000..aa320d50270d --- /dev/null +++ b/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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.java new file mode 100644 index 000000000000..cf6a6ef80ece --- /dev/null +++ b/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 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 Throwable { + 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/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java new file mode 100644 index 000000000000..a86bcd69bdea --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.java @@ -0,0 +1,16 @@ +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")); + } +} diff --git a/src/test/java/org/junit/tests/experimental/theories/internal/AllMembersSupplierTest.java b/src/test/java/org/junit/tests/experimental/theories/internal/AllMembersSupplierTest.java new file mode 100644 index 000000000000..a3ee3635bd48 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/internal/AllMembersSupplierTest.java @@ -0,0 +1,209 @@ +package org.junit.tests.experimental.theories.internal; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; +import static org.junit.tests.experimental.theories.TheoryTestUtils.potentialAssignments; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.Theory; +import org.junit.experimental.theories.internal.AllMembersSupplier; +import org.junit.rules.ExpectedException; +import org.junit.runners.model.TestClass; + +public class AllMembersSupplierTest { + @Rule + public ExpectedException expected = ExpectedException.none(); + + public static class HasDataPointsArrayField { + @DataPoints + public static String[] list = new String[] { "qwe", "asd" }; + + @Theory + public void theory(String param) { + } + } + + @Test + public void dataPointsArrayShouldBeRecognized() throws Throwable { + List assignments = potentialAssignments( + HasDataPointsArrayField.class.getMethod("theory", String.class)); + + assertEquals(2, assignments.size()); + } + + public static class HasDataPointsArrayWithMatchingButInaccurateTypes { + @DataPoints + public static Object[] objects = {1, "string!", 2}; + + @Theory + public void theory(Integer param) { + } + } + + @Test + public void dataPointsArrayShouldBeRecognizedOnValueTypeNotFieldType() throws Throwable { + List assignments = potentialAssignments( + HasDataPointsArrayWithMatchingButInaccurateTypes.class.getMethod("theory", Integer.class)); + + assertEquals(2, assignments.size()); + } + + public static class HasDataPointMethodWithOverlyGeneralTypes { + @DataPoint + public static Integer object() { + return 1; + } + + @Theory + public void theory(Object param) { + } + } + + @Test + public void dataPointMethodShouldBeRecognizedForOverlyGeneralParameters() throws Throwable { + List assignments = potentialAssignments( + HasDataPointMethodWithOverlyGeneralTypes.class.getMethod("theory", Object.class)); + + assertEquals(1, assignments.size()); + } + + public static class HasDataPointsWithObjectParameter { + @DataPoints + public static Object[] objectField = {1, 2}; + + @Theory + public void theory(Object obj) { + } + } + + @Test + public void dataPointsAnnotationMeansTreatAsArrayOnly() throws Throwable { + List assignments = potentialAssignments( + HasDataPointsWithObjectParameter.class.getMethod("theory", Object.class)); + + assertEquals(2, assignments.size()); + for (PotentialAssignment assignment : assignments) { + assertNotEquals(HasDataPointsWithObjectParameter.objectField, assignment.getValue()); + } + } + + public static class HasDataPointsFieldWithNullValue { + @DataPoints + public static Object[] objects = {null, "a"}; + + public HasDataPointsFieldWithNullValue(Object obj) { + } + } + + @Test + public void dataPointsArrayFieldMayContainNullValue() throws Throwable { + List valueSources = allMemberValuesFor( + HasDataPointsFieldWithNullValue.class, Object.class); + assertThat(valueSources.size(), is(2)); + } + + public static class HasDataPointsMethodWithNullValue { + @DataPoints + public static Integer[] getObjects() { + return new Integer[] {null, 1}; + } + + public HasDataPointsMethodWithNullValue(Integer i) { + } + } + + @Test + public void dataPointsArrayMethodMayContainNullValue() throws Throwable { + List valueSources = allMemberValuesFor( + HasDataPointsMethodWithNullValue.class, Integer.class); + assertThat(valueSources.size(), is(2)); + } + + public static class HasFailingDataPointsArrayMethod { + @DataPoints + public static Object[] objects() { + throw new RuntimeException("failing method"); + } + + public HasFailingDataPointsArrayMethod(Object obj) { + } + } + + @Test + public void allMembersFailsOnFailingDataPointsArrayMethod() throws Throwable { + expected.expect(RuntimeException.class); + expected.expectMessage("failing method"); + allMemberValuesFor(HasFailingDataPointsArrayMethod.class, Object.class); + } + + private List allMemberValuesFor(Class testClass, + Class... constructorParameterTypes) throws Throwable { + return new AllMembersSupplier(new TestClass(testClass)) + .getValueSources(ParameterSignature.signatures( + testClass.getConstructor(constructorParameterTypes)) + .get(0)); + } + + public static class HasDataPointsListField { + @DataPoints + public static List list = Arrays.asList("one", "two"); + + @Theory + public void theory(String param) { + } + } + + @Test + public void dataPointsCollectionFieldsShouldBeRecognized() throws Throwable { + List assignments = potentialAssignments( + HasDataPointsListField.class.getMethod("theory", String.class)); + + assertEquals(2, assignments.size()); + } + + public static class HasDataPointsListMethod { + @DataPoints + public static List getList() { + return Arrays.asList("one", "two"); + } + + @Theory + public void theory(String param) { + } + } + + @Test + public void dataPointsCollectionMethodShouldBeRecognized() throws Throwable { + List assignments = potentialAssignments( + HasDataPointsListMethod.class.getMethod("theory", String.class)); + + assertEquals(2, assignments.size()); + } + + public static class HasDataPointsListFieldWithOverlyGenericTypes { + @DataPoints + public static List list = Arrays.asList("string", new Object()); + + @Theory + public void theory(String param) { + } + } + + @Test + public void dataPointsCollectionShouldBeRecognizedIgnoringStrangeTypes() throws Throwable { + List assignments = potentialAssignments( + HasDataPointsListFieldWithOverlyGenericTypes.class.getMethod("theory", String.class)); + + assertEquals(1, assignments.size()); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/tests/experimental/theories/internal/AllTheoriesInternalTests.java b/src/test/java/org/junit/tests/experimental/theories/internal/AllTheoriesInternalTests.java new file mode 100644 index 000000000000..7c87afa35e7d --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/internal/AllTheoriesInternalTests.java @@ -0,0 +1,14 @@ +package org.junit.tests.experimental.theories.internal; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AllMembersSupplierTest.class, + ParameterizedAssertionErrorTest.class, + SpecificDataPointsSupplierTest.class +}) +public class AllTheoriesInternalTests { +} diff --git a/src/test/java/org/junit/tests/experimental/theories/internal/ParameterizedAssertionErrorTest.java b/src/test/java/org/junit/tests/experimental/theories/internal/ParameterizedAssertionErrorTest.java new file mode 100644 index 000000000000..2d42d992c3c2 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/internal/ParameterizedAssertionErrorTest.java @@ -0,0 +1,95 @@ +package org.junit.tests.experimental.theories.internal; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assume.assumeThat; + +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 + public void sameHashCodeWhenEquals(Throwable targetException, String methodName, + Object[] params) { + ParameterizedAssertionError one = new ParameterizedAssertionError( + targetException, methodName, params); + ParameterizedAssertionError two = new ParameterizedAssertionError( + targetException, methodName, params); + assumeThat(one, is(two)); + + assertThat(one.hashCode(), is(two.hashCode())); + } + + @Theory(nullsAccepted = false) + public void buildParameterizedAssertionError(String methodName, String param) { + assertThat(new ParameterizedAssertionError( + new RuntimeException(), methodName, param).toString(), + containsString(methodName)); + } + + @Theory + public void isNotEqualToNull(ParameterizedAssertionError a) { + assertFalse(a.equals(null)); + } + + @Test + public void canJoinWhenToStringFails() { + assertThat(ParameterizedAssertionError.join(" ", new Object() { + @Override + public String toString() { + throw new UnsupportedOperationException(); + } + }), is("[toString failed]")); + } +} diff --git a/src/test/java/org/junit/tests/experimental/theories/internal/SpecificDataPointsSupplierTest.java b/src/test/java/org/junit/tests/experimental/theories/internal/SpecificDataPointsSupplierTest.java new file mode 100644 index 000000000000..3ccf902c9bcf --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/internal/SpecificDataPointsSupplierTest.java @@ -0,0 +1,156 @@ +package org.junit.tests.experimental.theories.internal; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.FromDataPoints; +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException; +import org.junit.experimental.theories.internal.SpecificDataPointsSupplier; +import org.junit.runners.model.TestClass; + +public class SpecificDataPointsSupplierTest { + + public static class TestClassWithNamedDataPoints { + + @DataPoints({"field", "named"}) + public static String[] values = new String[] { "named field" }; + + @DataPoints + public static String[] otherValues = new String[] { "other" }; + + @DataPoints({"method", "named"}) + public static String[] getValues() { + return new String[] { "named method" }; + } + + @DataPoint({"single", "named"}) + public static String singleValue = "named single value"; + + @DataPoint + public static String otherSingleValue = "other value"; + + @DataPoint({"singlemethod", "named"}) + public static String getSingleValue() { + return "named single method value"; + } + + @DataPoint + public static String getSingleOtherValue() { + return "other single method value"; + } + + @DataPoints + public static String[] getOtherValues() { + return new String[] { "other method" }; + } + } + + @Test + public void shouldReturnOnlyTheNamedDataPoints() throws Throwable { + SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); + + List assignments = supplier.getValueSources(signature("methodWantingAllNamedStrings")); + List assignedStrings = getStringValuesFromAssignments(assignments); + + assertEquals(4, assignedStrings.size()); + assertThat(assignedStrings, hasItems("named field", "named method", "named single value", "named single method value")); + } + + @Test + public void shouldReturnOnlyTheNamedFieldDataPoints() throws Throwable { + SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); + + List assignments = supplier.getValueSources(signature("methodWantingNamedFieldString")); + List assignedStrings = getStringValuesFromAssignments(assignments); + + assertEquals(1, assignedStrings.size()); + assertThat(assignedStrings, hasItem("named field")); + } + + @Test + public void shouldReturnOnlyTheNamedMethodDataPoints() throws Throwable { + SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); + + List assignments = supplier.getValueSources(signature("methodWantingNamedMethodString")); + List assignedStrings = getStringValuesFromAssignments(assignments); + + assertEquals(1, assignedStrings.size()); + assertThat(assignedStrings, hasItem("named method")); + } + + @Test + public void shouldReturnOnlyTheNamedSingleFieldDataPoints() throws Throwable { + SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); + + List assignments = supplier.getValueSources(signature("methodWantingNamedSingleFieldString")); + List assignedStrings = getStringValuesFromAssignments(assignments); + + assertEquals(1, assignedStrings.size()); + assertThat(assignedStrings, hasItem("named single value")); + } + + @Test + public void shouldReturnOnlyTheNamedSingleMethodDataPoints() throws Throwable { + SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); + + List assignments = supplier.getValueSources(signature("methodWantingNamedSingleMethodString")); + List assignedStrings = getStringValuesFromAssignments(assignments); + + assertEquals(1, assignedStrings.size()); + assertThat(assignedStrings, hasItem("named single method value")); + } + + @Test + public void shouldReturnNothingIfTheNamedDataPointsAreMissing() throws Throwable { + SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); + + List assignments = supplier.getValueSources(signature("methodWantingWrongNamedString")); + List assignedStrings = getStringValuesFromAssignments(assignments); + + assertEquals(0, assignedStrings.size()); + } + + private List getStringValuesFromAssignments(List assignments) throws CouldNotGenerateValueException { + List stringValues = new ArrayList(); + for (PotentialAssignment assignment : assignments) { + stringValues.add((String) assignment.getValue()); + } + return stringValues; + } + + private ParameterSignature signature(String methodName) throws Exception { + return ParameterSignature.signatures(this.getClass().getMethod(methodName, String.class)).get(0); + } + + public void methodWantingAnyString(String input) { + } + + public void methodWantingNamedFieldString(@FromDataPoints("field") String input) { + } + + public void methodWantingNamedMethodString(@FromDataPoints("method") String input) { + } + + public void methodWantingNamedSingleFieldString(@FromDataPoints("single") String input) { + } + + public void methodWantingNamedSingleMethodString(@FromDataPoints("singlemethod") String input) { + } + + public void methodWantingAllNamedStrings(@FromDataPoints("named") String input) { + } + + public void methodWantingWrongNamedString(@FromDataPoints("invalid name") String input) { + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/AllTheoriesRunnerTests.java b/src/test/java/org/junit/tests/experimental/theories/runner/AllTheoriesRunnerTests.java new file mode 100644 index 000000000000..26465caecc9a --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/AllTheoriesRunnerTests.java @@ -0,0 +1,24 @@ +package org.junit.tests.experimental.theories.runner; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + FailingDataPointMethods.class, + SuccessfulWithDataPointFields.class, + TheoriesPerformanceTest.class, + TypeMatchingBetweenMultiDataPointsMethod.class, + UnsuccessfulWithDataPointFields.class, + WhenNoParametersMatch.class, + WithAutoGeneratedDataPoints.class, + WithDataPointMethod.class, + WithExtendedParameterSources.class, + WithNamedDataPoints.class, + WithOnlyTestAnnotations.class, + WithParameterSupplier.class, + WithUnresolvedGenericTypeVariablesOnTheoryParms.class +}) +public class AllTheoriesRunnerTests { +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/FailingDataPointMethods.java b/src/test/java/org/junit/tests/experimental/theories/runner/FailingDataPointMethods.java new file mode 100644 index 000000000000..5abc0ea480fb --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/FailingDataPointMethods.java @@ -0,0 +1,136 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.not; +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.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 FailingDataPointMethods { + + @RunWith(Theories.class) + public static class HasFailingSingleDataPointMethod { + @DataPoint + public static int num = 10; + + @DataPoint + public static int failingDataPoint() { + throw new RuntimeException(); + } + + @Theory + public void theory(int x) { + } + } + + @Test + public void shouldFailFromExceptionsInSingleDataPointMethods() { + assertThat(testResult(HasWronglyIgnoredFailingSingleDataPointMethod.class), not(isSuccessful())); + } + + @RunWith(Theories.class) + public static class HasFailingDataPointArrayMethod { + @DataPoints + public static int[] num = { 1, 2, 3 }; + + @DataPoints + public static int[] failingDataPoints() { + throw new RuntimeException(); + } + + @Theory + public void theory(int x) { + } + } + + @Test + public void shouldFailFromExceptionsInDataPointArrayMethods() { + assertThat(testResult(HasFailingDataPointArrayMethod.class), not(isSuccessful())); + } + + @RunWith(Theories.class) + public static class HasIgnoredFailingSingleDataPointMethod { + @DataPoint + public static int num = 10; + + @DataPoint(ignoredExceptions=Throwable.class) + public static int failingDataPoint() { + throw new RuntimeException(); + } + + @Theory + public void theory(int x) { + } + } + + @Test + public void shouldIgnoreSingleDataPointMethodExceptionsOnRequest() { + assertThat(testResult(HasIgnoredFailingSingleDataPointMethod.class), isSuccessful()); + } + + @RunWith(Theories.class) + public static class HasIgnoredFailingMultipleDataPointMethod { + @DataPoint + public static int num = 10; + + @DataPoints(ignoredExceptions=Throwable.class) + public static int[] failingDataPoint() { + throw new RuntimeException(); + } + + @Theory + public void theory(int x) { + } + } + + @Test + public void shouldIgnoreMultipleDataPointMethodExceptionsOnRequest() { + assertThat(testResult(HasIgnoredFailingMultipleDataPointMethod.class), isSuccessful()); + } + + @RunWith(Theories.class) + public static class HasWronglyIgnoredFailingSingleDataPointMethod { + @DataPoint + public static int num = 10; + + @DataPoint(ignoredExceptions=NullPointerException.class) + public static int failingDataPoint() { + throw new RuntimeException(); + } + + @Theory + public void theory(int x) { + } + } + + @Test + public void shouldNotIgnoreNonMatchingSingleDataPointExceptions() { + assertThat(testResult(HasWronglyIgnoredFailingSingleDataPointMethod.class), not(isSuccessful())); + } + + @RunWith(Theories.class) + public static class HasWronglyIgnoredFailingMultipleDataPointMethod { + @DataPoint + public static int num = 10; + + @DataPoint(ignoredExceptions=NullPointerException.class) + public static int failingDataPoint() { + throw new RuntimeException(); + } + + @Theory + public void theory(int x) { + } + } + + @Test + public void shouldNotIgnoreNonMatchingMultipleDataPointExceptions() { + assertThat(testResult(HasWronglyIgnoredFailingMultipleDataPointMethod.class), not(isSuccessful())); + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java b/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java new file mode 100644 index 000000000000..41d766a7e9ab --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.java @@ -0,0 +1,211 @@ +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/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java b/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java new file mode 100644 index 000000000000..8136493a90a9 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java @@ -0,0 +1,38 @@ +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/src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataPointsMethod.java b/src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataPointsMethod.java new file mode 100644 index 000000000000..8232a902790c --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataPointsMethod.java @@ -0,0 +1,57 @@ +package org.junit.tests.experimental.theories.runner; + +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.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 TypeMatchingBetweenMultiDataPointsMethod { + + @RunWith(Theories.class) + public static class WithWrongfullyTypedDataPointsMethod { + @DataPoint + public static String[] correctlyTyped = {"Good", "Morning"}; + + @DataPoints + public static String[] wrongfullyTyped() { + return new String[]{"Hello", "World"}; + } + + @Theory + public void testTheory(String[] array) { + } + } + + @Test + public void ignoreWrongTypedDataPointsMethod() { + assertThat(testResult(WithWrongfullyTypedDataPointsMethod.class), isSuccessful()); + } + + @RunWith(Theories.class) + public static class WithCorrectlyTypedDataPointsMethod { + @DataPoint + public static String[] correctlyTyped = {"Good", "Morning"}; + + @DataPoints + public static String[][] anotherCorrectlyTyped() { + return new String[][]{ + {"Hello", "World"} + }; + } + + @Theory + public void testTheory(String[] array) { + } + } + + @Test + public void pickUpMultiPointDataPointMethods() throws Exception { + assertThat(testResult(WithCorrectlyTypedDataPointsMethod.class), isSuccessful()); + } +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java b/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java new file mode 100644 index 000000000000..3298ef4a0fda --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.java @@ -0,0 +1,243 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.allOf; +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.hasFailureContaining; +import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; +import org.hamcrest.CoreMatchers; +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; +import org.junit.runners.model.TestClass; + +public class UnsuccessfulWithDataPointFields { + @RunWith(Theories.class) + public static class HasAFailingTheory { + @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(HasAFailingTheory.class).getDescription() + .getChildren().size(), is(1)); + } + + @Test + public void theoryAnnotationsAreRetained() throws Exception { + assertThat(new TestClass(HasAFailingTheory.class).getAnnotatedMethods( + Theory.class).size(), is(1)); + } + + @Test + public void canRunTheories() throws Exception { + assertThat(testResult(HasAFailingTheory.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(\"1\" , \"1\" )")); + } + + @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 TheoriesMustBePublic { + @DataPoint + public static int THREE = 3; + + @Theory + void numbers(int x) { + + } + } + + @Test + public void theoriesMustBePublic() { + assertThat( + testResult(TheoriesMustBePublic.class), + hasSingleFailureContaining("public")); + } + + @RunWith(Theories.class) + public static class DataPointFieldsMustBeStatic { + @DataPoint + public int THREE = 3; + + @DataPoints + public int[] FOURS = new int[] { 4 }; + + @Theory + public void numbers(int x) { + + } + } + + @Test + public void dataPointFieldsMustBeStatic() { + assertThat( + testResult(DataPointFieldsMustBeStatic.class), + CoreMatchers.both(hasFailureContaining("DataPoint field THREE must be static")) + .and(hasFailureContaining("DataPoint field FOURS must be static"))); + } + + @RunWith(Theories.class) + public static class DataPointMethodsMustBeStatic { + @DataPoint + public int singleDataPointMethod() { + return 1; + } + + @DataPoints + public int[] dataPointArrayMethod() { + return new int[] { 1, 2, 3 }; + } + + @Theory + public void numbers(int x) { + + } + } + + @Test + public void dataPointMethodsMustBeStatic() { + assertThat( + testResult(DataPointMethodsMustBeStatic.class), + CoreMatchers.both( + hasFailureContaining("DataPoint method singleDataPointMethod must be static")) + .and( + hasFailureContaining("DataPoint method dataPointArrayMethod must be static"))); + } + + @RunWith(Theories.class) + public static class DataPointFieldsMustBePublic { + @DataPoint + static int THREE = 3; + + @DataPoints + static int[] THREES = new int[] { 3 }; + + @DataPoint + protected static int FOUR = 4; + + @DataPoints + protected static int[] FOURS = new int[] { 4 }; + + @DataPoint + private static int FIVE = 5; + + @DataPoints + private static int[] FIVES = new int[] { 5 }; + + @Theory + public void numbers(int x) { + + } + } + + @Test + public void dataPointFieldsMustBePublic() { + PrintableResult result = testResult(DataPointFieldsMustBePublic.class); + + assertThat(result, + allOf(hasFailureContaining("DataPoint field THREE must be public"), + hasFailureContaining("DataPoint field THREES must be public"), + hasFailureContaining("DataPoint field FOUR must be public"), + hasFailureContaining("DataPoint field FOURS must be public"), + hasFailureContaining("DataPoint field FIVE must be public"), + hasFailureContaining("DataPoint field FIVES must be public"))); + } + + @RunWith(Theories.class) + public static class DataPointMethodsMustBePublic { + @DataPoint + static int three() { + return 3; + } + + @DataPoints + static int[] threes() { + return new int[] { 3 }; + } + + @DataPoint + protected static int four() { + return 4; + } + + @DataPoints + protected static int[] fours() { + return new int[] { 4 }; + } + + @DataPoint + private static int five() { + return 5; + } + + @DataPoints + private static int[] fives() { + return new int[] { 5 }; + } + + @Theory + public void numbers(int x) { + + } + } + + @Test + public void dataPointMethodsMustBePublic() { + PrintableResult result = testResult(DataPointMethodsMustBePublic.class); + + assertThat(result, + allOf(hasFailureContaining("DataPoint method three must be public"), + hasFailureContaining("DataPoint method threes must be public"), + hasFailureContaining("DataPoint method four must be public"), + hasFailureContaining("DataPoint method fours must be public"), + hasFailureContaining("DataPoint method five must be public"), + hasFailureContaining("DataPoint method fives must be public"))); + } +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java b/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java new file mode 100644 index 000000000000..17afed98029b --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java @@ -0,0 +1,51 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.containsString; +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 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/src/test/java/org/junit/tests/experimental/theories/runner/WithAutoGeneratedDataPoints.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithAutoGeneratedDataPoints.java new file mode 100644 index 000000000000..26eb5156e43b --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithAutoGeneratedDataPoints.java @@ -0,0 +1,71 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.junit.Assert.assertEquals; +import static org.junit.tests.experimental.theories.TheoryTestUtils.potentialAssignments; +import org.junit.Test; +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.Theories; +import org.junit.runner.RunWith; + +public class WithAutoGeneratedDataPoints { + + private enum ENUM { VALUE, OTHER_VALUE, THIRD_VALUE }; + + @RunWith(Theories.class) + public static class TheoryTestClassWithAutogeneratedParameterValues { + + public void theory(ENUM e) { + } + + public void theory(boolean b) { + } + + } + + @Test + public void shouldAutomaticallyGenerateEnumDataPoints() throws Throwable { + assertEquals(ENUM.values().length, potentialAssignments( + TheoryTestClassWithAutogeneratedParameterValues.class.getMethod("theory", ENUM.class)).size()); + } + + @Test + public void shouldAutomaticallyGenerateBooleanDataPoints() throws Throwable { + assertEquals(2, potentialAssignments( + TheoryTestClassWithAutogeneratedParameterValues.class.getMethod("theory", boolean.class)).size()); + } + + @RunWith(Theories.class) + public static class TheoryTestClassWithSpecificEnumDataPoint { + + @DataPoint + public static ENUM value = ENUM.OTHER_VALUE; + + public void theory(ENUM e) { + } + + } + + @Test + public void shouldNotAutogenerateEnumDataPointsWhenSpecificDataPointGiven() throws Throwable { + assertEquals(1, potentialAssignments( + TheoryTestClassWithSpecificEnumDataPoint.class.getMethod("theory", ENUM.class)).size()); + } + + @RunWith(Theories.class) + public static class TheoryTestClassWithSpecificBooleanDataPoint { + + @DataPoint + public static boolean value = true; + + public void theory(boolean b) { + } + + } + + @Test + public void shouldNotAutogenerateBooleanDataPointsWhenSpecificDataPointGiven() throws Throwable { + assertEquals(1, potentialAssignments( + TheoryTestClassWithSpecificBooleanDataPoint.class.getMethod("theory", boolean.class)).size()); + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java new file mode 100644 index 000000000000..c814508de897 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java @@ -0,0 +1,114 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.everyItem; +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.tests.experimental.theories.TheoryTestUtils.potentialAssignments; + +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.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.JUnitCore; +import org.junit.runner.RunWith; +import org.junit.runner.notification.Failure; + +public class WithDataPointMethod { + @RunWith(Theories.class) + public static class HasDataPointMethod { + @DataPoint + public static int oneHundred() { + return 100; + } + + @Theory + public void allIntsOk(int x) { + } + } + + @Test + public void pickUpDataPointMethods() { + assertThat(testResult(HasDataPointMethod.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 static int oneHundred() { + return 100; + } + + public static 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 Throwable { + assertThat(potentialAssignments( + HasDateMethod.class.getMethod("onlyStringsOk", String.class)) + .toString(), not(containsString("100"))); + } + + @Test + public void ignoreDataPointMethodsWithoutAnnotation() throws Throwable { + assertThat(potentialAssignments( + HasDateMethod.class.getMethod("onlyDatesOk", Date.class)) + .size(), is(0)); + } + + private List failures(Class type) { + return JUnitCore.runClasses(type).getFailures(); + } + + private Matcher> empty() { + return everyItem(nullValue(Failure.class)); + } +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java new file mode 100644 index 000000000000..bcda189588bf --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.java @@ -0,0 +1,184 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +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 ShouldFilterOutNullSingleDataPoints { + + @DataPoint + public static String A = "a"; + + @DataPoint + public static String NULL = null; + + @Theory(nullsAccepted = false) + public void allStringsAreNonNull(String s) { + assertThat(s, notNullValue()); + } + } + + @Test + public void shouldFilterOutNullSingleDataPoints() { + assertThat(testResult(ShouldFilterOutNullSingleDataPoints.class), isSuccessful()); + } + + @RunWith(Theories.class) + public static class ShouldFilterOutNullElementsFromDataPointArrays { + @DataPoints + public static String[] SOME_NULLS = { "non-null", null }; + + @Theory(nullsAccepted = false) + public void allStringsAreNonNull(String s) { + assertThat(s, notNullValue()); + } + } + + @Test + public void shouldFilterOutNullElementsFromDataPointArrays() { + assertThat(testResult(ShouldFilterOutNullElementsFromDataPointArrays.class), isSuccessful()); + } + + @RunWith(Theories.class) + public static class ShouldRejectTheoriesWithOnlyDisallowedNullData { + @DataPoints + public static String value = null; + + @Theory(nullsAccepted = false) + public void allStringsAreNonNull(String s) { + } + } + + @Test + public void ShouldRejectTheoriesWithOnlyDisallowedNullData() { + assertThat(testResult(ShouldRejectTheoriesWithOnlyDisallowedNullData.class), not(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/src/test/java/org/junit/tests/experimental/theories/runner/WithNamedDataPoints.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithNamedDataPoints.java new file mode 100644 index 000000000000..249ef1041c4b --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithNamedDataPoints.java @@ -0,0 +1,73 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.tests.experimental.theories.TheoryTestUtils.potentialAssignments; + +import java.util.List; + +import org.junit.Test; +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.FromDataPoints; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +public class WithNamedDataPoints { + + @RunWith(Theories.class) + public static class HasSpecificDatapointsParameters { + + @DataPoints + public static String[] badStrings = new String[] { "bad" }; + + @DataPoint + public static String badString = "also bad"; + + @DataPoints("named") + public static String[] goodStrings = new String[] { "expected", "also expected" }; + + @DataPoint("named") + public static String goodString = "expected single value"; + + @DataPoints("named") + public static String[] methodStrings() { + return new String[] { "expected method value" }; + } + + @DataPoint("named") + public static String methodString() { + return "expected single method string"; + } + + @DataPoints + public static String[] otherMethod() { + return new String[] { "other method value" }; + } + + @DataPoint + public static String otherSingleValueMethod() { + return "other single value string"; + } + + @Theory + public void theory(@FromDataPoints("named") String param) { + } + + } + + @Test + public void onlyUseSpecificDataPointsIfSpecified() throws Throwable { + List assignments = potentialAssignments(HasSpecificDatapointsParameters.class + .getMethod("theory", String.class)); + + assertEquals(5, assignments.size()); + for (PotentialAssignment assignment : assignments) { + assertThat((String) assignment.getValue(), containsString("expected")); + } + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java new file mode 100644 index 000000000000..2dea231a2b88 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java @@ -0,0 +1,82 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.experimental.results.PrintableResult.testResult; +import static org.junit.experimental.results.ResultMatchers.failureCountIs; +import static org.junit.experimental.results.ResultMatchers.isSuccessful; + +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/src/test/java/org/junit/tests/experimental/theories/runner/WithParameterSupplier.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithParameterSupplier.java new file mode 100644 index 000000000000..1802390a87d4 --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithParameterSupplier.java @@ -0,0 +1,165 @@ +package org.junit.tests.experimental.theories.runner; + +import static org.junit.Assert.assertEquals; +import static org.junit.tests.experimental.theories.TheoryTestUtils.potentialAssignments; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.theories.ParameterSignature; +import org.junit.experimental.theories.ParameterSupplier; +import org.junit.experimental.theories.ParametersSuppliedBy; +import org.junit.experimental.theories.PotentialAssignment; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.TestClass; + +public class WithParameterSupplier { + + @Rule + public ExpectedException expected = ExpectedException.none(); + + private static class SimplePotentialAssignment extends PotentialAssignment { + private String description; + private Object value; + + public SimplePotentialAssignment(Object value, String description) { + this.value = value; + this.description = description; + } + + @Override + public Object getValue() throws CouldNotGenerateValueException { + return value; + } + + @Override + public String getDescription() throws CouldNotGenerateValueException { + return description; + } + } + + private static final List DATAPOINTS = Arrays.asList("qwe", "asd"); + + public static class SimpleSupplier extends ParameterSupplier { + + @Override + public List getValueSources(ParameterSignature sig) { + List assignments = new ArrayList(); + + for (String datapoint : DATAPOINTS) { + assignments.add(new SimplePotentialAssignment(datapoint, + datapoint)); + } + + return assignments; + } + + } + + @RunWith(Theories.class) + public static class TestClassUsingParameterSupplier { + + @Theory + public void theoryMethod(@ParametersSuppliedBy(SimpleSupplier.class) String param) { + } + + } + + @Test + public void shouldPickUpDataPointsFromParameterSupplier() throws Throwable { + List assignments = potentialAssignments(TestClassUsingParameterSupplier.class + .getMethod("theoryMethod", String.class)); + + assertEquals(2, assignments.size()); + assertEquals(DATAPOINTS.get(0), assignments.get(0).getValue()); + assertEquals(DATAPOINTS.get(1), assignments.get(1).getValue()); + } + + public static class SupplierWithUnknownConstructor extends ParameterSupplier { + + public SupplierWithUnknownConstructor(String param) { + } + + @Override + public List getValueSources(ParameterSignature sig) { + return null; + } + + } + + @RunWith(Theories.class) + public static class TestClassUsingSupplierWithUnknownConstructor { + + @Theory + public void theory(@ParametersSuppliedBy(SupplierWithUnknownConstructor.class) String param) { + } + + } + + @Test + public void shouldRejectSuppliersWithUnknownConstructors() throws Exception { + expected.expect(InitializationError.class); + new Theories(TestClassUsingSupplierWithUnknownConstructor.class); + } + + public static class SupplierWithTwoConstructors extends ParameterSupplier { + + public SupplierWithTwoConstructors(String param) { + } + + @Override + public List getValueSources(ParameterSignature sig) { + return null; + } + + } + + @RunWith(Theories.class) + public static class TestClassUsingSupplierWithTwoConstructors { + + @Theory + public void theory(@ParametersSuppliedBy(SupplierWithTwoConstructors.class) String param) { + } + + } + + @Test + public void shouldRejectSuppliersWithTwoConstructors() throws Exception { + expected.expect(InitializationError.class); + new Theories(TestClassUsingSupplierWithTwoConstructors.class); + } + + public static class SupplierWithTestClassConstructor extends ParameterSupplier { + + public SupplierWithTestClassConstructor(TestClass param) { + } + + @Override + public List getValueSources(ParameterSignature sig) { + return null; + } + + } + + @RunWith(Theories.class) + public static class TestClassUsingSupplierWithTestClassConstructor { + + @Theory + public void theory(@ParametersSuppliedBy(SupplierWithTestClassConstructor.class) String param) { + } + + } + + @Test + public void shouldAcceptSuppliersWithTestClassConstructor() throws Exception { + new Theories(TestClassUsingSupplierWithTestClassConstructor.class); + } + +} diff --git a/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java b/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java new file mode 100644 index 000000000000..50ac09c16b9d --- /dev/null +++ b/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.java @@ -0,0 +1,180 @@ +package org.junit.tests.experimental.theories.runner; + +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.experimental.results.ResultMatchers.isSuccessful; + +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(1)); + 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/src/test/java/org/junit/tests/junit3compatibility/AllJUnit3CompatibilityTests.java b/src/test/java/org/junit/tests/junit3compatibility/AllJUnit3CompatibilityTests.java new file mode 100644 index 000000000000..812908cc4040 --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/AllJUnit3CompatibilityTests.java @@ -0,0 +1,20 @@ +package org.junit.tests.junit3compatibility; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AllTestsTest.class, + ClassRequestTest.class, + ForwardCompatibilityPrintingTest.class, + ForwardCompatibilityTest.class, + InitializationErrorForwardCompatibilityTest.class, + JUnit38ClassRunnerTest.class, + OldTestClassAdaptingListenerTest.class, + OldTests.class, + SuiteMethodTest.class +}) +public class AllJUnit3CompatibilityTests { +} diff --git a/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java b/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java new file mode 100644 index 000000000000..96fad3d3ade5 --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java @@ -0,0 +1,87 @@ +package org.junit.tests.junit3compatibility; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +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/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java b/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java new file mode 100644 index 000000000000..4c5c2cebdcec --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java @@ -0,0 +1,20 @@ +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/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java b/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java new file mode 100644 index 000000000000..cf40916f505e --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java @@ -0,0 +1,91 @@ +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/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java b/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java new file mode 100644 index 000000000000..34673e9fbd1b --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java @@ -0,0 +1,254 @@ +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 ").append(test); + } + + public void endTest(junit.framework.Test test) { + log.append(" end ").append(test); + } + + public void addFailure(junit.framework.Test test, AssertionFailedError t) { + log.append(" failure ").append(test); + } + + public void addError(junit.framework.Test test, Throwable e) { + 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/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java b/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java new file mode 100644 index 000000000000..ec497012e73b --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.java @@ -0,0 +1,102 @@ +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 e) { + 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/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java b/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java new file mode 100644 index 000000000000..b7a1c515e3f2 --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java @@ -0,0 +1,155 @@ +package org.junit.tests.junit3compatibility; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertNotNull; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +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; +import org.junit.runner.manipulation.Filter; +import org.junit.runner.manipulation.NoTestsRemainException; + +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()); + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + public static @interface MyAnnotation { + } + + public static class JUnit3ClassWithAnnotatedMethod extends TestCase { + @MyAnnotation + public void testAnnotated() { + } + + public void testNotAnnotated() { + } + } + + public static class DerivedAnnotatedMethod extends JUnit3ClassWithAnnotatedMethod { + } + + @Test + public void getDescriptionWithAnnotation() { + JUnit38ClassRunner runner = new JUnit38ClassRunner(JUnit3ClassWithAnnotatedMethod.class); + assertAnnotationFiltering(runner); + } + + @Test + public void getDescriptionWithAnnotationInSuper() { + JUnit38ClassRunner runner = new JUnit38ClassRunner(DerivedAnnotatedMethod.class); + assertAnnotationFiltering(runner); + } + + private void assertAnnotationFiltering(JUnit38ClassRunner runner) { + Description d = runner.getDescription(); + assertEquals(2, d.testCount()); + for (Description methodDesc : d.getChildren()) { + if (methodDesc.getMethodName().equals("testAnnotated")) { + assertNotNull(methodDesc.getAnnotation(MyAnnotation.class)); + } else { + assertNull(methodDesc.getAnnotation(MyAnnotation.class)); + } + } + } + + public static class RejectAllTestsFilter extends Filter { + @Override + public boolean shouldRun(Description description) { + return description.isSuite(); + } + + @Override + public String describe() { + return "filter all"; + } + } + + /** + * Test that NoTestsRemainException is thrown when all methods have been filtered. + */ + @Test(expected = NoTestsRemainException.class) + public void filterNoTestsRemain() throws NoTestsRemainException { + JUnit38ClassRunner runner = new JUnit38ClassRunner(OneTest.class); + runner.filter(new RejectAllTestsFilter()); + } +} diff --git a/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java b/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java new file mode 100644 index 000000000000..9822b14c4c9e --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java @@ -0,0 +1,28 @@ +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/src/test/java/org/junit/tests/junit3compatibility/OldTests.java b/src/test/java/org/junit/tests/junit3compatibility/OldTests.java new file mode 100644 index 000000000000..e8b3ab8eca32 --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/OldTests.java @@ -0,0 +1,12 @@ +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/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java b/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java new file mode 100644 index 000000000000..edc9eac2b0c4 --- /dev/null +++ b/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java @@ -0,0 +1,134 @@ +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 suite = new TestSuite(); + suite.addTest(new OldTest("notObviouslyATest")); + return suite; + } + + 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/src/test/java/org/junit/tests/listening/AllListeningTests.java b/src/test/java/org/junit/tests/listening/AllListeningTests.java new file mode 100644 index 000000000000..cadbd2e332a9 --- /dev/null +++ b/src/test/java/org/junit/tests/listening/AllListeningTests.java @@ -0,0 +1,16 @@ +package org.junit.tests.listening; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + ListenerTest.class, + RunnerTest.class, + TestListenerTest.class, + TextListenerTest.class, + UserStopTest.class +}) +public class AllListeningTests { +} diff --git a/src/test/java/org/junit/tests/listening/ListenerTest.java b/src/test/java/org/junit/tests/listening/ListenerTest.java new file mode 100644 index 000000000000..c76581a0d5c6 --- /dev/null +++ b/src/test/java/org/junit/tests/listening/ListenerTest.java @@ -0,0 +1,38 @@ +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/src/test/java/org/junit/tests/listening/RunnerTest.java b/src/test/java/org/junit/tests/listening/RunnerTest.java new file mode 100644 index 000000000000..cd12c350ae95 --- /dev/null +++ b/src/test/java/org/junit/tests/listening/RunnerTest.java @@ -0,0 +1,75 @@ +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/src/test/java/org/junit/tests/listening/TestListenerTest.java b/src/test/java/org/junit/tests/listening/TestListenerTest.java new file mode 100644 index 000000000000..693c15edc2c0 --- /dev/null +++ b/src/test/java/org/junit/tests/listening/TestListenerTest.java @@ -0,0 +1,65 @@ +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 reportsFailureOfListener() { + 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()); + } + + @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/src/test/java/org/junit/tests/listening/TextListenerTest.java b/src/test/java/org/junit/tests/listening/TextListenerTest.java new file mode 100644 index 000000000000..c266d0c8c9ff --- /dev/null +++ b/src/test/java/org/junit/tests/listening/TextListenerTest.java @@ -0,0 +1,73 @@ +package org.junit.tests.listening; + +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertThat; + +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; + + @Override + public void setUp() { + runner = new JUnitCore(); + TestSystem system = new TestSystem(); + results = system.outContents(); + runner.addListener(new TextListener(system)); + } + + 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 Time { + @Test + public void time() { + } + } + + public void testTime() { + runner.run(Time.class); + assertThat(results.toString(), containsString("Time: ")); + assertThat(results.toString(), not(containsString(convert("Time: \n")))); + } + + 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/src/test/java/org/junit/tests/listening/UserStopTest.java b/src/test/java/org/junit/tests/listening/UserStopTest.java new file mode 100644 index 000000000000..1233cce75aa5 --- /dev/null +++ b/src/test/java/org/junit/tests/listening/UserStopTest.java @@ -0,0 +1,33 @@ +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/src/test/java/org/junit/tests/manipulation/AllManipulationTests.java b/src/test/java/org/junit/tests/manipulation/AllManipulationTests.java new file mode 100644 index 000000000000..d7532152b490 --- /dev/null +++ b/src/test/java/org/junit/tests/manipulation/AllManipulationTests.java @@ -0,0 +1,15 @@ +package org.junit.tests.manipulation; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + FilterableTest.class, + FilterTest.class, + SingleMethodTest.class, + SortableTest.class +}) +public class AllManipulationTests { +} diff --git a/src/test/java/org/junit/tests/manipulation/FilterTest.java b/src/test/java/org/junit/tests/manipulation/FilterTest.java new file mode 100644 index 000000000000..a9c013661ebe --- /dev/null +++ b/src/test/java/org/junit/tests/manipulation/FilterTest.java @@ -0,0 +1,50 @@ +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/src/test/java/org/junit/tests/manipulation/FilterableTest.java b/src/test/java/org/junit/tests/manipulation/FilterableTest.java new file mode 100644 index 000000000000..f1f5060a1941 --- /dev/null +++ b/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/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java b/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java new file mode 100644 index 000000000000..c056f0a5d7dc --- /dev/null +++ b/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java @@ -0,0 +1,190 @@ +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.Parameterized.Parameters; +import org.junit.runners.Suite; +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/src/test/java/org/junit/tests/manipulation/SortableTest.java b/src/test/java/org/junit/tests/manipulation/SortableTest.java new file mode 100644 index 000000000000..9d10ff95f313 --- /dev/null +++ b/src/test/java/org/junit/tests/manipulation/SortableTest.java @@ -0,0 +1,205 @@ +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/src/test/java/org/junit/tests/package-info.java b/src/test/java/org/junit/tests/package-info.java new file mode 100644 index 000000000000..fc5bdf60448f --- /dev/null +++ b/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/src/test/java/org/junit/tests/running/AllRunningTests.java b/src/test/java/org/junit/tests/running/AllRunningTests.java new file mode 100644 index 000000000000..0c05c92c2c2e --- /dev/null +++ b/src/test/java/org/junit/tests/running/AllRunningTests.java @@ -0,0 +1,17 @@ +package org.junit.tests.running; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; +import org.junit.tests.running.classes.AllClassesTests; +import org.junit.tests.running.core.AllCoreTests; +import org.junit.tests.running.methods.AllMethodsTests; + +@RunWith(Suite.class) +@SuiteClasses({ + AllClassesTests.class, + AllCoreTests.class, + AllMethodsTests.class +}) +public class AllRunningTests { +} diff --git a/src/test/java/org/junit/tests/running/classes/AllClassesTests.java b/src/test/java/org/junit/tests/running/classes/AllClassesTests.java new file mode 100644 index 000000000000..4420bafe4729 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/AllClassesTests.java @@ -0,0 +1,21 @@ +package org.junit.tests.running.classes; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + BlockJUnit4ClassRunnerTest.class, + ClassLevelMethodsWithIgnoredTestsTest.class, + EnclosedTest.class, + IgnoreClassTest.class, + ParameterizedTestTest.class, + ParentRunnerFilteringTest.class, + ParentRunnerTest.class, + RunWithTest.class, + SuiteTest.class, + UseSuiteAsASuperclassTest.class +}) +public class AllClassesTests { +} diff --git a/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java b/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java new file mode 100644 index 000000000000..47405f6b1127 --- /dev/null +++ b/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/src/test/java/org/junit/tests/running/classes/ClassLevelMethodsWithIgnoredTestsTest.java b/src/test/java/org/junit/tests/running/classes/ClassLevelMethodsWithIgnoredTestsTest.java new file mode 100644 index 000000000000..076988bab965 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/ClassLevelMethodsWithIgnoredTestsTest.java @@ -0,0 +1,165 @@ +package org.junit.tests.running.classes; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.experimental.categories.Categories.CategoryFilter; +import org.junit.experimental.categories.Category; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runner.JUnitCore; +import org.junit.runner.Request; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; +import org.junit.runners.model.Statement; + +/** + * Tests verifying that class-level fixtures ({@link BeforeClass} and + * {@link AfterClass}) and rules ({@link ClassRule}) are not executed when there + * are no test methods to be run in a test class because they have been ignored. + * + */ +public class ClassLevelMethodsWithIgnoredTestsTest { + private static final String FAILURE_MESSAGE = "This should not have happened!"; + + public static class BeforeClassWithIgnoredTest { + @BeforeClass + public static void beforeClass() { + fail(FAILURE_MESSAGE); + } + + @Ignore + @Test + public void test() throws Exception { + fail("test() should not run"); + } + } + + @Test + public void beforeClassShouldNotRunWhenAllTestsAreIgnored() { + runClassAndVerifyNoFailures(BeforeClassWithIgnoredTest.class, + "BeforeClass should not have been executed because the test method is ignored!"); + } + + @Ignore + public static class BeforeClassWithIgnoredClass { + @BeforeClass + public static void beforeClass() { + fail(FAILURE_MESSAGE); + } + + @Test + public void test() throws Exception { + fail("test() should not run"); + } + } + + @Test + public void beforeClassShouldNotRunWhenWholeClassIsIgnored() { + runClassAndVerifyNoFailures( + BeforeClassWithIgnoredClass.class, + "BeforeClass should not have been executed because the whole test class is ignored!"); + } + + public static class AfterClassWithIgnoredTest { + @Ignore + @Test + public void test() throws Exception { + fail("test() should not run"); + } + + @AfterClass + public static void afterClass() { + fail(FAILURE_MESSAGE); + } + } + + @Test + public void afterClassShouldNotRunWhenAllTestsAreIgnored() { + runClassAndVerifyNoFailures(AfterClassWithIgnoredTest.class, + "AfterClass should not have been executed because the test method is ignored!"); + } + + public interface FilteredTests { + } + + public static class BeforeClassWithFilteredTest { + @BeforeClass + public static void setUpClass() { + fail(FAILURE_MESSAGE); + } + + @Category(FilteredTests.class) + @Test + public void test() throws Exception { + fail("test() should not run"); + } + } + + public static class HasUnfilteredTest { + @Test + public void unfilteredTest() { + // to prevent errors when all other tests have been filtered + } + } + + @Test + public void beforeClassShouldNotRunWhenAllTestsAreFiltered() { + Result result = new JUnitCore().run(Request.classes( + BeforeClassWithFilteredTest.class, HasUnfilteredTest.class) + .filterWith(CategoryFilter.exclude(FilteredTests.class))); + analyseResult( + result, + "BeforeClass should not have been executed because the test method is filtered!"); + } + + public static class BrokenRule implements TestRule { + public Statement apply(Statement base, Description description) { + throw new RuntimeException("this rule is broken"); + } + } + + public static class ClassRuleWithIgnoredTest { + @ClassRule + public static BrokenRule brokenRule = new BrokenRule(); + + @Ignore + @Test + public void test() throws Exception { + fail("test() should not be run"); + } + } + + @Test + public void classRuleShouldNotBeAppliedWhenAllTestsAreIgnored() { + runClassAndVerifyNoFailures(ClassRuleWithIgnoredTest.class, + "The class rule should have been applied because the test method is ignored!"); + } + + private void runClassAndVerifyNoFailures(Class klass, + String testFailureDescription) { + Result result = JUnitCore.runClasses(klass); + analyseResult(result, testFailureDescription); + } + + private void analyseResult(Result result, String testFailureDescription) { + List failures = result.getFailures(); + if (failures.isEmpty() == false) { + analyzeFailure(failures.get(0), testFailureDescription); + } + } + + private void analyzeFailure(Failure failure, String testFailureDescription) { + String actualFailureMsg = failure.getMessage(); + if (FAILURE_MESSAGE.equals(actualFailureMsg)) { + fail(testFailureDescription); + } + fail("Unexpected failure : " + actualFailureMsg); + } +} diff --git a/src/test/java/org/junit/tests/running/classes/EnclosedTest.java b/src/test/java/org/junit/tests/running/classes/EnclosedTest.java new file mode 100644 index 000000000000..9f71deadaf18 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/EnclosedTest.java @@ -0,0 +1,55 @@ +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() {} + } + abstract public static class C { + @Test public void a() {} + } + } + + @Test + public void enclosedRunnerPlansConcreteEnclosedClasses() throws Exception { + Runner runner= Request.aClass(Enclosing.class).getRunner(); + assertEquals(5, runner.testCount()); + } + + @Test + public void enclosedRunnerRunsConcreteEnclosedClasses() 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/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java b/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java new file mode 100644 index 000000000000..28cbe76300e0 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java @@ -0,0 +1,31 @@ +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/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java b/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java new file mode 100644 index 000000000000..14916c6f5565 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java @@ -0,0 +1,496 @@ +package org.junit.tests.running.classes; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +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 java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +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.runner.notification.Failure; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.runners.model.InitializationError; +import org.junit.runners.parameterized.ParametersRunnerFactory; +import org.junit.runners.parameterized.TestWithParameters; + +public class ParameterizedTestTest { + @RunWith(Parameterized.class) + public static class AdditionTest { + @Parameters(name = "{index}: {0} + {1} = {2}") + public static Iterable data() { + return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 }, + { 3, 2, 5 }, { 4, 3, 7 } }); + } + + private int firstSummand; + + private int secondSummand; + + private int sum; + + public AdditionTest(int firstSummand, int secondSummand, int sum) { + this.firstSummand = firstSummand; + this.secondSummand = secondSummand; + this.sum = sum; + } + + @Test + public void test() { + assertEquals(sum, firstSummand + secondSummand); + } + } + + @Test + public void countsRuns() { + Result result = JUnitCore.runClasses(AdditionTest.class); + assertEquals(4, result.getRunCount()); + } + + @Test + public void countBeforeRun() throws Exception { + Runner runner = Request.aClass(AdditionTest.class).getRunner(); + assertEquals(4, runner.testCount()); + } + + @Test + public void plansNamedCorrectly() throws Exception { + Runner runner = Request.aClass(AdditionTest.class).getRunner(); + Description description = runner.getDescription(); + assertEquals("[2: 3 + 2 = 5]", description.getChildren().get(2) + .getDisplayName()); + } + + @RunWith(Parameterized.class) + public static class ThreeFailures { + @Parameters(name = "{index}: x={0}") + public static Collection data() { + return Arrays.asList(1, 2, 3); + } + + @Parameter(0) + public int unused; + + @Test + public void testSomething() { + fail(); + } + } + + @Test + public void countsFailures() throws Exception { + Result result = JUnitCore.runClasses(ThreeFailures.class); + assertEquals(3, result.getFailureCount()); + } + + @Test + public void failuresNamedCorrectly() { + Result result = JUnitCore.runClasses(ThreeFailures.class); + assertEquals( + "testSomething[0: x=1](" + ThreeFailures.class.getName() + ")", + result.getFailures().get(0).getTestHeader()); + } + + @RunWith(Parameterized.class) + public static class ParameterizedWithoutSpecialTestname { + @Parameters + public static Collection data() { + return Arrays.asList(new Object[][]{{3}, {3}}); + } + + public ParameterizedWithoutSpecialTestname(Object something) { + } + + @Test + public void testSomething() { + } + } + + @Test + public void usesIndexAsTestName() { + Runner runner = Request + .aClass(ParameterizedWithoutSpecialTestname.class).getRunner(); + Description description = runner.getDescription(); + assertEquals("[1]", description.getChildren().get(1).getDisplayName()); + } + + @RunWith(Parameterized.class) + public static class AdditionTestWithAnnotatedFields { + @Parameters(name = "{index}: {0} + {1} = {2}") + public static Iterable data() { + return Arrays.asList(new Object[][] { { 0, 0, 0 }, { 1, 1, 2 }, + { 3, 2, 5 }, { 4, 3, 7 } }); + } + + @Parameter(0) + public int firstSummand; + + @Parameter(1) + public int secondSummand; + + @Parameter(2) + public int sum; + + @Test + public void test() { + assertEquals(sum, firstSummand + secondSummand); + } + } + + @Test + public void providesDataByAnnotatedFields() { + Result result = JUnitCore.runClasses(AdditionTestWithAnnotatedFields.class); + assertEquals(4, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + } + + @RunWith(Parameterized.class) + static public class BadIndexForAnnotatedFieldTest { + @Parameters + public static Collection data() { + return Arrays.asList(new Object[][]{{0}}); + } + + @Parameter(2) + public int fInput; + + public int fExpected; + + @Test + public void test() { + assertEquals(fExpected, fib(fInput)); + } + + private int fib(int x) { + return 0; + } + } + + @Test + public void failureOnInitialization() { + Result result = JUnitCore.runClasses(BadIndexForAnnotatedFieldTest.class); + assertEquals(1, result.getFailureCount()); + List failures = result.getFailures(); + assertThat(failures.get(0).getException().getMessage(), allOf( + containsString("Invalid @Parameter value: 2. @Parameter fields counted: 1. Please use an index between 0 and 0."), + containsString("@Parameter(0) is never used."))); + } + + @RunWith(Parameterized.class) + static public class BadNumberOfAnnotatedFieldTest { + @Parameters + public static Collection data() { + return Arrays.asList(new Object[][]{{0, 0}}); + } + + @Parameter(0) + public int fInput; + + public int fExpected; + + @Test + public void test() { + assertEquals(fExpected, fib(fInput)); + } + + private int fib(int x) { + return 0; + } + } + + @Test + public void numberOfFieldsAndParametersShouldMatch() { + Result result = JUnitCore.runClasses(BadNumberOfAnnotatedFieldTest.class); + assertEquals(1, result.getFailureCount()); + List failures = result.getFailures(); + assertTrue(failures.get(0).getException().getMessage().contains("Wrong number of parameters and @Parameter fields. @Parameter fields counted: 1, available parameters: 2.")); + } + + 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() { + assertTestCreatesSingleFailureWithMessage(ProtectedParametersTest.class, + "No public static parameters method on class " + + ProtectedParametersTest.class.getName()); + } + + @RunWith(Parameterized.class) + static public class ParametersNotIterable { + @Parameters + public static String data() { + return "foo"; + } + + @Test + public void aTest() { + } + } + + @Test + public void meaningfulFailureWhenParametersAreNotAnIterable() { + assertThat( + testResult(ParametersNotIterable.class).toString(), + containsString("ParametersNotIterable.data() must return an Iterable of arrays.")); + } + + @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); + } + + @RunWith(Parameterized.class) + public static class AdditionTestWithArray { + @Parameters(name = "{index}: {0} + {1} = {2}") + public static Object[][] data() { + return new Object[][] { { 0, 0, 0 }, { 1, 1, 2 }, { 3, 2, 5 }, + { 4, 3, 7 } }; + } + + @Parameter(0) + public int firstSummand; + + @Parameter(1) + public int secondSummand; + + @Parameter(2) + public int sum; + + @Test + public void test() { + assertEquals(sum, firstSummand + secondSummand); + } + } + + @Test + public void runsEveryTestOfArray() { + Result result= JUnitCore.runClasses(AdditionTestWithArray.class); + assertEquals(4, result.getRunCount()); + } + + @RunWith(Parameterized.class) + static public class SingleArgumentTestWithArray { + @Parameters + public static Object[] data() { + return new Object[] { "first test", "second test" }; + } + + public SingleArgumentTestWithArray(Object argument) { + } + + @Test + public void aTest() { + } + } + + @Test + public void runsForEverySingleArgumentOfArray() { + Result result= JUnitCore.runClasses(SingleArgumentTestWithArray.class); + assertEquals(2, result.getRunCount()); + } + + @RunWith(Parameterized.class) + static public class SingleArgumentTestWithIterable { + @Parameters + public static Iterable data() { + return asList("first test", "second test"); + } + + public SingleArgumentTestWithIterable(Object argument) { + } + + @Test + public void aTest() { + } + } + + @Test + public void runsForEverySingleArgumentOfIterable() { + Result result= JUnitCore + .runClasses(SingleArgumentTestWithIterable.class); + assertEquals(2, result.getRunCount()); + } + + static public class ExceptionThrowingRunnerFactory implements + ParametersRunnerFactory { + public Runner createRunnerForTestWithParameters(TestWithParameters test) + throws InitializationError { + throw new InitializationError( + "Called ExceptionThrowingRunnerFactory."); + } + } + + @RunWith(Parameterized.class) + @UseParametersRunnerFactory(ExceptionThrowingRunnerFactory.class) + static public class TestWithUseParametersRunnerFactoryAnnotation { + @Parameters + public static Iterable data() { + return asList("single test"); + } + + public TestWithUseParametersRunnerFactoryAnnotation(Object argument) { + } + + @Test + public void aTest() { + } + } + + @Test + public void usesParametersRunnerFactoryThatWasSpecifiedByAnnotation() { + assertTestCreatesSingleFailureWithMessage( + TestWithUseParametersRunnerFactoryAnnotation.class, + "Called ExceptionThrowingRunnerFactory."); + } + + private void assertTestCreatesSingleFailureWithMessage(Class test, String message) { + Result result = JUnitCore.runClasses(test); + assertEquals(1, result.getFailures().size()); + assertEquals(message, result.getFailures().get(0).getMessage()); + } + + @RunWith(Parameterized.class) + @UseParametersRunnerFactory(ExceptionThrowingRunnerFactory.class) + public static abstract class UseParameterizedFactoryAbstractTest { + @Parameters + public static Iterable data() { + return asList("single test"); + } + } + + public static class UseParameterizedFactoryTest extends + UseParameterizedFactoryAbstractTest { + + public UseParameterizedFactoryTest(String parameter) { + + } + + @Test + public void parameterizedTest() { + } + } + + @Test + public void usesParametersRunnerFactoryThatWasSpecifiedByAnnotationInSuperClass() { + assertTestCreatesSingleFailureWithMessage( + UseParameterizedFactoryTest.class, + "Called ExceptionThrowingRunnerFactory."); + } +} \ No newline at end of file diff --git a/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java b/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java new file mode 100644 index 000000000000..12e12b428d86 --- /dev/null +++ b/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/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java b/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java new file mode 100644 index 000000000000..3eee8f1e82ee --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java @@ -0,0 +1,308 @@ +package org.junit.tests.running.classes; + +import static org.hamcrest.CoreMatchers.containsString; +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.hamcrest.TypeSafeMatcher; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.internal.AssumptionViolatedException; +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.Failure; +import org.junit.runner.notification.RunListener; +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.rules.RuleMemberValidatorTest.TestWithNonStaticClassRule; +import org.junit.rules.RuleMemberValidatorTest.TestWithProtectedClassRule; + +public class ParentRunnerTest { + public static String log = ""; + + public static class FruitTest { + @Test + public void apple() { + log += "apple "; + } + + @Test + public void /* must hash-sort after "apple" */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 final 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."); + } + + static class NonPublicTestClass { + public NonPublicTestClass() { + } + } + + @Test + public void cannotBeCreatedWithNonPublicTestClass() { + assertClassHasFailureMessage( + NonPublicTestClass.class, + "The class org.junit.tests.running.classes.ParentRunnerTest$NonPublicTestClass is not public."); + } + + 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(1)); + assertThat(result.getFailures().get(0).getMessage(), + containsString(message)); + } + + public static class AssertionErrorAtParentLevelTest { + @BeforeClass + public static void beforeClass() throws Throwable { + throw new AssertionError("Thrown from @BeforeClass"); + } + + @Test + public void test() {} + } + + @Test + public void assertionErrorAtParentLevelTest() throws InitializationError { + CountingRunListener countingRunListener = runTestWithParentRunner(AssertionErrorAtParentLevelTest.class); + Assert.assertEquals(1, countingRunListener.testSuiteStarted); + Assert.assertEquals(1, countingRunListener.testSuiteFinished); + Assert.assertEquals(1, countingRunListener.testSuiteFailure); + Assert.assertEquals(0, countingRunListener.testSuiteAssumptionFailure); + + Assert.assertEquals(0, countingRunListener.testStarted); + Assert.assertEquals(0, countingRunListener.testFinished); + Assert.assertEquals(0, countingRunListener.testFailure); + Assert.assertEquals(0, countingRunListener.testAssumptionFailure); + Assert.assertEquals(0, countingRunListener.testIgnored); + } + + public static class AssumptionViolatedAtParentLevelTest { + @SuppressWarnings("deprecation") + @BeforeClass + public static void beforeClass() { + throw new AssumptionViolatedException("Thrown from @BeforeClass"); + } + + @Test + public void test() {} + } + + @Test + public void assumptionViolatedAtParentLevel() throws InitializationError { + CountingRunListener countingRunListener = runTestWithParentRunner(AssumptionViolatedAtParentLevelTest.class); + Assert.assertEquals(1, countingRunListener.testSuiteStarted); + Assert.assertEquals(1, countingRunListener.testSuiteFinished); + Assert.assertEquals(0, countingRunListener.testSuiteFailure); + Assert.assertEquals(1, countingRunListener.testSuiteAssumptionFailure); + + Assert.assertEquals(0, countingRunListener.testStarted); + Assert.assertEquals(0, countingRunListener.testFinished); + Assert.assertEquals(0, countingRunListener.testFailure); + Assert.assertEquals(0, countingRunListener.testAssumptionFailure); + Assert.assertEquals(0, countingRunListener.testIgnored); + } + + public static class TestTest { + @Test + public void pass() {} + + @Test + public void fail() { + throw new AssertionError("Thrown from @Test"); + } + + @Ignore + @Test + public void ignore() {} + + @SuppressWarnings("deprecation") + @Test + public void assumptionFail() { + throw new AssumptionViolatedException("Thrown from @Test"); + } + } + + @Test + public void parentRunnerTestMethods() throws InitializationError { + CountingRunListener countingRunListener = runTestWithParentRunner(TestTest.class); + Assert.assertEquals(1, countingRunListener.testSuiteStarted); + Assert.assertEquals(1, countingRunListener.testSuiteFinished); + Assert.assertEquals(0, countingRunListener.testSuiteFailure); + Assert.assertEquals(0, countingRunListener.testSuiteAssumptionFailure); + + Assert.assertEquals(3, countingRunListener.testStarted); + Assert.assertEquals(3, countingRunListener.testFinished); + Assert.assertEquals(1, countingRunListener.testFailure); + Assert.assertEquals(1, countingRunListener.testAssumptionFailure); + Assert.assertEquals(1, countingRunListener.testIgnored); + } + + private CountingRunListener runTestWithParentRunner(Class testClass) throws InitializationError { + CountingRunListener listener = new CountingRunListener(); + RunNotifier runNotifier = new RunNotifier(); + runNotifier.addListener(listener); + ParentRunner runner = new BlockJUnit4ClassRunner(testClass); + runner.run(runNotifier); + return listener; + } + + private static class CountingRunListener extends RunListener { + private int testSuiteStarted = 0; + private int testSuiteFinished = 0; + private int testSuiteFailure = 0; + private int testSuiteAssumptionFailure = 0; + + private int testStarted = 0; + private int testFinished = 0; + private int testFailure = 0; + private int testAssumptionFailure = 0; + private int testIgnored = 0; + + @Override + public void testSuiteStarted(Description description) throws Exception { + testSuiteStarted++; + } + + @Override + public void testSuiteFinished(Description description) throws Exception { + testSuiteFinished++; + } + + @Override + public void testStarted(Description description) throws Exception { + testStarted++; + } + + @Override + public void testFinished(Description description) throws Exception { + testFinished++; + } + + @Override + public void testFailure(Failure failure) throws Exception { + if (failure.getDescription().isSuite()) { + testSuiteFailure++; + } else { + testFailure++; + } + } + + @Override + public void testAssumptionFailure(Failure failure) { + if (failure.getDescription().isSuite()) { + testSuiteAssumptionFailure++; + } else { + testAssumptionFailure++; + } + } + + @Override + public void testIgnored(Description description) throws Exception { + testIgnored++; + } + } +} diff --git a/src/test/java/org/junit/tests/running/classes/RunWithTest.java b/src/test/java/org/junit/tests/running/classes/RunWithTest.java new file mode 100644 index 000000000000..c41a40aac3a8 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/RunWithTest.java @@ -0,0 +1,88 @@ +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/src/test/java/org/junit/tests/running/classes/SuiteTest.java b/src/test/java/org/junit/tests/running/classes/SuiteTest.java new file mode 100644 index 000000000000..1d95ebc87a49 --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/SuiteTest.java @@ -0,0 +1,192 @@ +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/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java b/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java new file mode 100644 index 000000000000..c55a8abb0c4c --- /dev/null +++ b/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java @@ -0,0 +1,45 @@ +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/src/test/java/org/junit/tests/running/core/AllCoreTests.java b/src/test/java/org/junit/tests/running/core/AllCoreTests.java new file mode 100644 index 000000000000..a17a7e20cdb6 --- /dev/null +++ b/src/test/java/org/junit/tests/running/core/AllCoreTests.java @@ -0,0 +1,14 @@ +package org.junit.tests.running.core; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + CommandLineTest.class, + JUnitCoreReturnsCorrectExitCodeTest.class, + SystemExitTest.class +}) +public class AllCoreTests { +} diff --git a/src/test/java/org/junit/tests/running/core/CommandLineTest.java b/src/test/java/org/junit/tests/running/core/CommandLineTest.java new file mode 100644 index 000000000000..f72b3e916075 --- /dev/null +++ b/src/test/java/org/junit/tests/running/core/CommandLineTest.java @@ -0,0 +1,78 @@ +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.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; + new MainRunner().runWithCheckForSystemExit(new Runnable() { + public void run() { + JUnitCore.main("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/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java b/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java new file mode 100644 index 000000000000..21e13ddb7c6f --- /dev/null +++ b/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java @@ -0,0 +1,47 @@ +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; + +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(final String className, int returnCode) { + Integer exitValue = new MainRunner().runWithCheckForSystemExit(new Runnable() { + public void run() { + JUnitCore.main(className); + } + }); + assertEquals(Integer.valueOf(returnCode), exitValue); + } +} diff --git a/src/test/java/org/junit/tests/running/core/MainRunner.java b/src/test/java/org/junit/tests/running/core/MainRunner.java new file mode 100644 index 000000000000..3068e1432778 --- /dev/null +++ b/src/test/java/org/junit/tests/running/core/MainRunner.java @@ -0,0 +1,293 @@ +package org.junit.tests.running.core; + +import java.io.ByteArrayOutputStream; +import java.io.FileDescriptor; +import java.io.PrintStream; +import java.net.InetAddress; +import java.security.Permission; + +public class MainRunner { + private static class ExitException extends SecurityException { + private static final long serialVersionUID = -9104651568237766642L; + + private final int status; + + public ExitException(int status) { + super(""); + this.status = status; + } + + public int getStatus() { + return status; + } + } + + /** + * A {@code NoExitSecurityManager} throws a {@link ExitException} exception + * whenever {@link #checkExit(int)} is called. All other method calls are + * delegated to the original security manager. + */ + public class NoExitSecurityManager extends SecurityManager { + private final SecurityManager originalSecurityManager; + + public NoExitSecurityManager(SecurityManager originalSecurityManager) { + this.originalSecurityManager = originalSecurityManager; + } + + @Override + public void checkExit(int status) { + throw new ExitException(status); + } + + @SuppressWarnings("deprecation") + @Override + public boolean getInCheck() { + return (originalSecurityManager != null) && originalSecurityManager.getInCheck(); + } + + @Override + public Object getSecurityContext() { + return (originalSecurityManager == null) ? super.getSecurityContext() : originalSecurityManager.getSecurityContext(); + } + + @Override + public void checkPermission(Permission perm) { + if (originalSecurityManager != null) { + originalSecurityManager.checkPermission(perm); + } + } + + @Override + public void checkPermission(Permission perm, Object context) { + if (originalSecurityManager != null) { + originalSecurityManager.checkPermission(perm, context); + } + } + + @Override + public void checkCreateClassLoader() { + if (originalSecurityManager != null) { + originalSecurityManager.checkCreateClassLoader(); + } + } + + @Override + public void checkAccess(Thread t) { + if (originalSecurityManager != null) { + originalSecurityManager.checkAccess(t); + } + } + + @Override + public void checkAccess(ThreadGroup g) { + if (originalSecurityManager != null) { + originalSecurityManager.checkAccess(g); + } + } + + @Override + public void checkExec(String cmd) { + if (originalSecurityManager != null) { + originalSecurityManager.checkExec(cmd); + } + } + + @Override + public void checkLink(String lib) { + if (originalSecurityManager != null) { + originalSecurityManager.checkLink(lib); + } + } + + @Override + public void checkRead(FileDescriptor fd) { + if (originalSecurityManager != null) { + originalSecurityManager.checkRead(fd); + } + } + + @Override + public void checkRead(String file) { + if (originalSecurityManager != null) { + originalSecurityManager.checkRead(file); + } + } + + @Override + public void checkRead(String file, Object context) { + if (originalSecurityManager != null) { + originalSecurityManager.checkRead(file, context); + } + } + + @Override + public void checkWrite(FileDescriptor fd) { + if (originalSecurityManager != null) { + originalSecurityManager.checkWrite(fd); + } + } + + @Override + public void checkWrite(String file) { + if (originalSecurityManager != null) { + originalSecurityManager.checkWrite(file); + } + } + + @Override + public void checkDelete(String file) { + if (originalSecurityManager != null) { + originalSecurityManager.checkDelete(file); + } + } + + @Override + public void checkConnect(String host, int port) { + if (originalSecurityManager != null) { + originalSecurityManager.checkConnect(host, port); + } + } + + @Override + public void checkConnect(String host, int port, Object context) { + if (originalSecurityManager != null) { + originalSecurityManager.checkConnect(host, port, context); + } + } + + @Override + public void checkListen(int port) { + if (originalSecurityManager != null) { + originalSecurityManager.checkListen(port); + } + } + + @Override + public void checkAccept(String host, int port) { + if (originalSecurityManager != null) { + originalSecurityManager.checkAccept(host, port); + } + } + + @Override + public void checkMulticast(InetAddress maddr) { + if (originalSecurityManager != null) { + originalSecurityManager.checkMulticast(maddr); + } + } + + @SuppressWarnings("deprecation") + @Override + public void checkMulticast(InetAddress maddr, byte ttl) { + if (originalSecurityManager != null) { + originalSecurityManager.checkMulticast(maddr, ttl); + } + } + + @Override + public void checkPropertiesAccess() { + if (originalSecurityManager != null) { + originalSecurityManager.checkPropertiesAccess(); + } + } + + @Override + public void checkPropertyAccess(String key) { + if (originalSecurityManager != null) { + originalSecurityManager.checkPropertyAccess(key); + } + } + + @Override + public boolean checkTopLevelWindow(Object window) { + return (originalSecurityManager == null) ? super.checkTopLevelWindow(window) : originalSecurityManager.checkTopLevelWindow(window); + } + + @Override + public void checkPrintJobAccess() { + if (originalSecurityManager != null) { + originalSecurityManager.checkPrintJobAccess(); + } + } + + @Override + public void checkSystemClipboardAccess() { + if (originalSecurityManager != null) { + originalSecurityManager.checkSystemClipboardAccess(); + } + } + + @Override + public void checkAwtEventQueueAccess() { + if (originalSecurityManager != null) { + originalSecurityManager.checkAwtEventQueueAccess(); + } + } + + @Override + public void checkPackageAccess(String pkg) { + if (originalSecurityManager != null) { + originalSecurityManager.checkPackageAccess(pkg); + } + } + + @Override + public void checkPackageDefinition(String pkg) { + if (originalSecurityManager != null) { + originalSecurityManager.checkPackageDefinition(pkg); + } + } + + @Override + public void checkSetFactory() { + if (originalSecurityManager != null) { + originalSecurityManager.checkSetFactory(); + } + } + + @Override + public void checkMemberAccess(Class clazz, int which) { + if (originalSecurityManager != null) { + originalSecurityManager.checkMemberAccess(clazz, which); + } + } + + @Override + public void checkSecurityAccess(String target) { + if (originalSecurityManager != null) { + originalSecurityManager.checkSecurityAccess(target); + } + } + + @Override + public ThreadGroup getThreadGroup() { + return (originalSecurityManager == null) ? super.getThreadGroup() : originalSecurityManager.getThreadGroup(); + } + } + + /** + * Execute runnable.run(), preventing System.exit(). If System.exit() is called + * in runnable.run(), the value is returned. If System.exit() + * is not called, null is returned. + * + * @return null if System.exit() is not called, Integer.valueof(status) if not + */ + public Integer runWithCheckForSystemExit(Runnable runnable) { + SecurityManager oldSecurityManager = System.getSecurityManager(); + System.setSecurityManager(new NoExitSecurityManager(oldSecurityManager)); + PrintStream oldOut = System.out; + + System.setOut(new PrintStream(new ByteArrayOutputStream())); + try { + runnable.run(); + System.out.println("System.exit() not called, return null"); + return null; + } catch (ExitException e) { + System.out.println("System.exit() called, value=" + e.getStatus()); + return e.getStatus(); + } finally { + System.setSecurityManager(oldSecurityManager); + System.setOut(oldOut); + } + } +} diff --git a/src/test/java/org/junit/tests/running/core/SystemExitTest.java b/src/test/java/org/junit/tests/running/core/SystemExitTest.java new file mode 100644 index 000000000000..3e2dc7cb76da --- /dev/null +++ b/src/test/java/org/junit/tests/running/core/SystemExitTest.java @@ -0,0 +1,31 @@ +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/src/test/java/org/junit/tests/running/methods/AllMethodsTests.java b/src/test/java/org/junit/tests/running/methods/AllMethodsTests.java new file mode 100644 index 000000000000..533bb5e1318f --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/AllMethodsTests.java @@ -0,0 +1,17 @@ +package org.junit.tests.running.methods; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AnnotationTest.class, + ExpectedTest.class, + InheritedTestTest.class, + ParameterizedTestMethodTest.class, + TestMethodTest.class, + TimeoutTest.class +}) +public class AllMethodsTests { +} diff --git a/src/test/java/org/junit/tests/running/methods/AnnotationTest.java b/src/test/java/org/junit/tests/running/methods/AnnotationTest.java new file mode 100644 index 000000000000..71fd79baab13 --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/AnnotationTest.java @@ -0,0 +1,643 @@ +package org.junit.tests.running.methods; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +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(), allOf(containsString("hereAfter"), 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/src/test/java/org/junit/tests/running/methods/ExpectedTest.java b/src/test/java/org/junit/tests/running/methods/ExpectedTest.java new file mode 100644 index 000000000000..236de9d72908 --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/ExpectedTest.java @@ -0,0 +1,70 @@ +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/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java b/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java new file mode 100644 index 000000000000..53f858b50fcf --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java @@ -0,0 +1,39 @@ +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/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java b/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java new file mode 100644 index 000000000000..e2442a5b4513 --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java @@ -0,0 +1,188 @@ +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/src/test/java/org/junit/tests/running/methods/TestMethodTest.java b/src/test/java/org/junit/tests/running/methods/TestMethodTest.java new file mode 100644 index 000000000000..69a437e7bb39 --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/TestMethodTest.java @@ -0,0 +1,255 @@ +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/src/test/java/org/junit/tests/running/methods/TimeoutTest.java b/src/test/java/org/junit/tests/running/methods/TimeoutTest.java new file mode 100644 index 000000000000..8d23909bd893 --- /dev/null +++ b/src/test/java/org/junit/tests/running/methods/TimeoutTest.java @@ -0,0 +1,334 @@ +package org.junit.tests.running.methods; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.not; +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 java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.util.concurrent.TimeUnit; + +import junit.framework.JUnit4TestAdapter; +import junit.framework.TestResult; +import org.junit.After; +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 TimeoutTest { + + public static 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()); + } + + public static 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()); + } + + public static 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()); + } + + public static 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()); + } + + public static 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")); + } + + public static 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; + } + + private String stackForException(Throwable exception) { + Writer buffer = new StringWriter(); + PrintWriter writer = new PrintWriter(buffer); + exception.printStackTrace(writer); + return buffer.toString(); + } + + @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(); + assertThat(stackForException(exception), containsString("infiniteLoop")); // Make sure we have the stalled frame on the stack somewhere + } + + public static class InfiniteLoopMultithreaded { + + private static class ThreadTest implements Runnable { + private boolean fStall; + + public ThreadTest(boolean stall) { + fStall = stall; + } + + public void run() { + if (fStall) + for (; ; ) ; + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + } + } + + public void failure(boolean mainThreadStalls) throws Exception { + Thread t1 = new Thread(new ThreadTest(false), "timeout-thr1"); + Thread t2 = new Thread(new ThreadTest(!mainThreadStalls), "timeout-thr2"); + Thread t3 = new Thread(new ThreadTest(false), "timeout-thr3"); + t1.start(); + t2.start(); + t3.start(); + if (mainThreadStalls) + for (; ; ) ; + t1.join(); + t2.join(); + t3.join(); + } + } + + public static class InfiniteLoopWithStuckThreadTest { + @Rule + public TestRule globalTimeout = Timeout.builder() + .withTimeout(100, TimeUnit.MILLISECONDS) + .withLookingForStuckThread(true) + .build(); + + @Test + public void failure() throws Exception { + (new InfiniteLoopMultithreaded()).failure(false); + } + } + + public static class InfiniteLoopStuckInMainThreadTest { + @Rule + public TestRule globalTimeout = Timeout.builder() + .withTimeout(100, TimeUnit.MILLISECONDS) + .withLookingForStuckThread(true) + .build(); + + @Test + public void failure() throws Exception { + (new InfiniteLoopMultithreaded()).failure(true); + } + } + + @Test + public void timeoutFailureMultithreaded() throws Exception { + JUnitCore core = new JUnitCore(); + Result result = core.run(InfiniteLoopWithStuckThreadTest.class); + assertEquals(1, result.getRunCount()); + assertEquals(2, result.getFailureCount()); + Throwable exception[] = new Throwable[2]; + for (int i = 0; i < 2; i++) + exception[i] = result.getFailures().get(i).getException(); + assertThat(exception[0].getMessage(), containsString("test timed out after 100 milliseconds")); + assertThat(stackForException(exception[0]), containsString("Thread.join")); + assertThat(exception[1].getMessage(), containsString("Appears to be stuck in thread timeout-thr2")); + } + + @Test + public void timeoutFailureMultithreadedStuckInMain() throws Exception { + JUnitCore core = new JUnitCore(); + Result result = core.run(InfiniteLoopStuckInMainThreadTest.class); + assertEquals(1, result.getRunCount()); + assertEquals(1, result.getFailureCount()); + Throwable exception = result.getFailures().get(0).getException(); + assertThat(exception.getMessage(), containsString("test timed out after 100 milliseconds")); + assertThat(exception.getMessage(), not(containsString("Appears to be stuck"))); + } + + @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)); + } + + public static class TimeOutZero { + @Rule + public Timeout timeout = Timeout.seconds(0); + + @Test + public void test() { + try { + Thread.sleep(200); // long enough to suspend thread execution + } catch (InterruptedException e) { + // Don't care + } + } + } + + @Test + public void testZeroTimeoutIsIgnored() { + JUnitCore core = new JUnitCore(); + Result result = core.run(TimeOutZero.class); + assertEquals("Should run the test", 1, result.getRunCount()); + assertEquals("Test should not have failed", 0, result.getFailureCount()); + } + + private static class TimeoutSubclass extends Timeout { + + public TimeoutSubclass(long timeout, TimeUnit timeUnit) { + super(timeout, timeUnit); + } + + public long getTimeoutFromSuperclass(TimeUnit unit) { + return super.getTimeout(unit); + } + } + + public static class TimeOutOneSecond { + @Rule + public TimeoutSubclass timeout = new TimeoutSubclass(1, TimeUnit.SECONDS); + + @Test + public void test() { + assertEquals(1000, timeout.getTimeoutFromSuperclass(TimeUnit.MILLISECONDS)); + } + } + + @Test + public void testGetTimeout() { + JUnitCore core = new JUnitCore(); + Result result = core.run(TimeOutOneSecond.class); + assertEquals("Should run the test", 1, result.getRunCount()); + assertEquals("Test should not have failed", 0, result.getFailureCount()); + } +} diff --git a/src/test/java/org/junit/tests/validation/AllValidationTests.java b/src/test/java/org/junit/tests/validation/AllValidationTests.java new file mode 100644 index 000000000000..f04723ef2856 --- /dev/null +++ b/src/test/java/org/junit/tests/validation/AllValidationTests.java @@ -0,0 +1,14 @@ +package org.junit.tests.validation; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + BadlyFormedClassesTest.class, + FailedConstructionTest.class, + ValidationTest.class +}) +public class AllValidationTests { +} diff --git a/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java b/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java new file mode 100644 index 000000000000..c3d6e89c6622 --- /dev/null +++ b/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java @@ -0,0 +1,75 @@ +package org.junit.tests.validation; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +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() { + assertThat(exceptionMessageFrom(NoTests.class), containsString("No runnable methods")); + } + + @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/src/test/java/org/junit/tests/validation/FailedConstructionTest.java b/src/test/java/org/junit/tests/validation/FailedConstructionTest.java new file mode 100644 index 000000000000..a7aa1a5644dd --- /dev/null +++ b/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/src/test/java/org/junit/tests/validation/ValidationTest.java b/src/test/java/org/junit/tests/validation/ValidationTest.java new file mode 100644 index 000000000000..7a81b50f7a18 --- /dev/null +++ b/src/test/java/org/junit/tests/validation/ValidationTest.java @@ -0,0 +1,42 @@ +package org.junit.tests.validation; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +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); + assertThat(result.getFailures().get(0).getMessage(), containsString("Method before() should be static")); + } +} diff --git a/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java b/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java new file mode 100644 index 000000000000..d02a39d06131 --- /dev/null +++ b/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/src/test/java/org/junit/tests/validation/anotherpackage/Super.java b/src/test/java/org/junit/tests/validation/anotherpackage/Super.java new file mode 100644 index 000000000000..bfd193be252a --- /dev/null +++ b/src/test/java/org/junit/tests/validation/anotherpackage/Super.java @@ -0,0 +1,9 @@ +package org.junit.tests.validation.anotherpackage; + +import org.junit.Test; + +class Super { + @Test + public void a() { + } +} diff --git a/src/test/java/org/junit/validator/AllValidatorTests.java b/src/test/java/org/junit/validator/AllValidatorTests.java new file mode 100644 index 000000000000..f9c1ca90c40d --- /dev/null +++ b/src/test/java/org/junit/validator/AllValidatorTests.java @@ -0,0 +1,14 @@ +package org.junit.validator; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ + AnnotationsValidatorTest.class, + AnnotationValidatorFactoryTest.class, + PublicClassValidatorTest.class +}) +public class AllValidatorTests { +} diff --git a/src/test/java/org/junit/validator/AnnotationValidatorFactoryTest.java b/src/test/java/org/junit/validator/AnnotationValidatorFactoryTest.java new file mode 100644 index 000000000000..4003ff347280 --- /dev/null +++ b/src/test/java/org/junit/validator/AnnotationValidatorFactoryTest.java @@ -0,0 +1,47 @@ +package org.junit.validator; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertThat; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class AnnotationValidatorFactoryTest { + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void createAnnotationValidator() { + ValidateWith validateWith = SampleTestWithValidator.class.getAnnotation(ValidateWith.class); + AnnotationValidator annotationValidator = new AnnotationValidatorFactory().createAnnotationValidator(validateWith); + assertThat(annotationValidator, is(instanceOf(Validator.class))); + } + + @ValidateWith(value = Validator.class) + public static class SampleTestWithValidator { + } + + public static class Validator extends AnnotationValidator { + } + + @Test + public void exceptionWhenAnnotationValidatorCantBeCreated() { + ValidateWith validateWith = SampleTestWithValidatorThatThrowsException.class.getAnnotation(ValidateWith.class); + exception.expect(RuntimeException.class); + exception.expectMessage("Exception received when creating AnnotationValidator class " + + "org.junit.validator.AnnotationValidatorFactoryTest$ValidatorThatThrowsException"); + new AnnotationValidatorFactory().createAnnotationValidator(validateWith); + } + + @ValidateWith(value = ValidatorThatThrowsException.class) + public static class SampleTestWithValidatorThatThrowsException { + } + + public static class ValidatorThatThrowsException extends AnnotationValidator { + public ValidatorThatThrowsException() throws InstantiationException { + throw new InstantiationException("Simulating exception in test"); + } + } +} diff --git a/src/test/java/org/junit/validator/AnnotationsValidatorTest.java b/src/test/java/org/junit/validator/AnnotationsValidatorTest.java new file mode 100644 index 000000000000..657330930274 --- /dev/null +++ b/src/test/java/org/junit/validator/AnnotationsValidatorTest.java @@ -0,0 +1,98 @@ +package org.junit.validator; + +import static java.util.Arrays.asList; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Collection; +import java.util.List; + +import org.junit.Test; +import org.junit.runners.model.FrameworkField; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.TestClass; + +public class AnnotationsValidatorTest { + public static class ExampleAnnotationValidator extends AnnotationValidator { + private static final String ANNOTATED_METHOD_CALLED= "annotated method called"; + + private static final String ANNOTATED_FIELD_CALLED= "annotated field called"; + + private static final String ANNOTATED_CLASS_CALLED= "annotated class called"; + + @Override + public List validateAnnotatedClass(TestClass testClass) { + return asList(new Exception(ANNOTATED_CLASS_CALLED)); + } + + @Override + public List validateAnnotatedField(FrameworkField field) { + return asList(new Exception(ANNOTATED_FIELD_CALLED)); + } + + @Override + public List validateAnnotatedMethod(FrameworkMethod method) { + return asList(new Exception(ANNOTATED_METHOD_CALLED)); + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Inherited + @ValidateWith(ExampleAnnotationValidator.class) + public @interface ExampleAnnotationWithValidator { + } + + public static class AnnotationValidatorMethodTest { + @ExampleAnnotationWithValidator + @Test + public void test() { + } + } + + public static class AnnotationValidatorFieldTest { + @ExampleAnnotationWithValidator + private String field; + + @Test + public void test() { + } + } + + @ExampleAnnotationWithValidator + public static class AnnotationValidatorClassTest { + @Test + public void test() { + } + } + + @Test + public void validatorIsCalledForAClass() { + assertClassHasFailureMessage(AnnotationValidatorClassTest.class, + ExampleAnnotationValidator.ANNOTATED_CLASS_CALLED); + } + + @Test + public void validatorIsCalledForAMethod() { + assertClassHasFailureMessage(AnnotationValidatorMethodTest.class, + ExampleAnnotationValidator.ANNOTATED_METHOD_CALLED); + } + + @Test + public void validatorIsCalledForAField() { + assertClassHasFailureMessage(AnnotationValidatorFieldTest.class, + ExampleAnnotationValidator.ANNOTATED_FIELD_CALLED); + } + + private void assertClassHasFailureMessage(Class klass, + String expectedFailure) { + AnnotationsValidator validator= new AnnotationsValidator(); + Collection errors= validator + .validateTestClass(new TestClass(klass)); + assertThat(errors.size(), is(1)); + assertThat(errors.iterator().next().getMessage(), + is(expectedFailure)); + } +} diff --git a/src/test/java/org/junit/validator/PublicClassValidatorTest.java b/src/test/java/org/junit/validator/PublicClassValidatorTest.java new file mode 100644 index 000000000000..dfecbbcd2886 --- /dev/null +++ b/src/test/java/org/junit/validator/PublicClassValidatorTest.java @@ -0,0 +1,41 @@ +package org.junit.validator; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.Collections; +import java.util.List; + +import org.junit.Test; +import org.junit.runners.model.TestClass; + +public class PublicClassValidatorTest { + private final PublicClassValidator validator = new PublicClassValidator(); + + public static class PublicClass { + + } + + @Test + public void acceptsPublicClass() { + TestClass testClass = new TestClass(PublicClass.class); + List validationErrors = validator + .validateTestClass(testClass); + assertThat(validationErrors, + is(equalTo(Collections. emptyList()))); + } + + static class NonPublicClass { + + } + + @Test + public void rejectsNonPublicClass() { + TestClass testClass = new TestClass(NonPublicClass.class); + List validationErrors = validator + .validateTestClass(testClass); + assertThat("Wrong number of errors.", validationErrors.size(), + is(equalTo(1))); + } +} diff --git a/src/test/resources/junit/tests/runner/testRunFailureResultCanBeSerialised b/src/test/resources/junit/tests/runner/testRunFailureResultCanBeSerialised new file mode 100644 index 0000000000000000000000000000000000000000..79d8c014b3daf4fcf69b5f2251243620d93f67ae GIT binary patch literal 4849 zcmbtYU2GIp6u!G{rGK=GQ0fm5!~z03D^O7cqh)EK&9-6-eGr3QX727zJ3BMpxzlcm z5`UtJ0&0vti27*M=!2S=7@jmnO@tRUzL*#_8lN;i8BIj-oO@^H&UP0u+N5`9=G=46 zcYg1gdGlw|7I4z<@v<=!y0$QQ=(>y>lPm}wLDXL+OWMXrducLs5872WMmkGVf^va3 zMRHlG;DxRbWJ_^|&e41*Y$tDet{HO9T#={3tJ-FMNdAnvf|VKHRU{py5o$XjXMrHO z6lc*61dzK+qh;6QOv=8W94DEYAHm5IlG%Tza()va--Id+RB33HhEi$Nshqz3$hniw z$|tiVGfLX#s1vdpCppRQP`7MMgw>;rKmO+PtGk~2_5>)A3NxT&gH}@T9EX|0_S|4# zYQZ%t+;i-4>E9l8haYY%_E`h`#E%Pr`J)&Q_8 zGv`~uyPd$az9AP}PuL~fq-eDf1x;rLfb1^qWr4|UA9o0{rU)YPGM(}&o$@I<;Leo} zg5T!d;hM=Jp1za`l1Ps_Oj)t20Z>Ys#?f{da16NsRsw~rT6Z`llqQtC-XznoP_Z2g zG8Kc>A&s#E-=PZ=w94vzJ0-a7mVv3WbP&?E;LrfnEK6yTkEGN?u6=*VMy(`#wwIq` z+@_9wEV3=+F+@WqpoVCqAU?4Eo#p*EulZ6Z1Kg`E ze7EtdwdZn$vobF;6+zag5Jx-nqwbuiLcE{4mIEa!Q)pWdx<)LmDZmECL!bWI+jsW( zD_P9n?kdBon#OViU-c@@vPFzjA3W767JP=T@00qJ4YHn#wmZwL{WPe+&cXL5?#Vgt z{{c4KO}eOQvLLvVTa1I<%XFGYyW5t0^}&ZL@B0i&XoPe+9<@fODLg((Iz$CJPQ`Pq znt%Hp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LoQ4t@XY`x1N`W4zIXlBcYk^+_piTo m+Zy#ED^I%)cr!s@-8kUOZy0JOf4e3}^DenAm0R!w2l*RQCLv@1 literal 0 HcmV?d00001 diff --git a/src/test/resources/junit/tests/runner/testRunSuccessResultCanBeSerialised b/src/test/resources/junit/tests/runner/testRunSuccessResultCanBeSerialised new file mode 100644 index 0000000000000000000000000000000000000000..e5163d1e07b61e44926d536161b306aa6115b15d GIT binary patch literal 550 zcmaiwJxjwt7{{Najo4P9sMM*O2)>YffDTeBVoOwL#ZkD%OPg}N)XQB>MFbHX)Ugf) z{RUlK`~ogcegeT+Tpb*|ON7+P8}9v{-|zn84=@4-i#}_a9YH;AGC?V3W*rBDaEP0x zgHeNNw=U?u*Tpr+x($vPR|^}a+=?$K=dfmXP#;->d&F{l>IlX#!4M^=p!O<$RHoRCy2JpUD0h~b~U~$=7w)K5)uJ530Y1c6`v67 zaL=c~Qe!}!HuI@>ijS1_(D{77+{~Xzf(>aRca*m-DeM0iND8l_ubs^O=rIMl4VuHD zFp*AjO=e_t1;-(Wx%h(mg|*l0NWW6pliu?Qw#*nBD9P~RwK#f44=EKxI*{&ht|w`k QZZ=fLxu~BF)LiYt4+*rh$N&HU literal 0 HcmV?d00001 diff --git a/src/test/resources/org/junit/internal/arrayComparisonFailure_411 b/src/test/resources/org/junit/internal/arrayComparisonFailure_411 new file mode 100644 index 0000000000000000000000000000000000000000..11fe0c51d7b1e8c9fe888d2889e2ba1b5c766ba2 GIT binary patch literal 2078 zcmah~O>A355T55aC3W-Hq!ilV(9$%eDZC^|tw<9h8RJNnob-@TkSZZ7^G+n0f2x=hR8@VLWeV_M7>3 zXJ+sG4gH~l^S)}@TahQUEj-PY$E00SioIR--GC_(`rZl?GEyAO&&okx4GuNREDE`X zleI0@VzZKY&Dl~Ia;1guRh078VhsiwRj)1_9%>jhevuY(wkATISXX%%vL>R8b)l?l zCA{Whtl(*awh7wa3;n%ofAg^P${#rZbQ{UslE9VXrK`6-7`|$(o&Xxeb=B6YUbS7P|U&XC$DvFUGEqw zlDpg^rpLl42o#d#^-ApUfX*l+q+A@(-{BxqDT?9Si;`QJSz3Dd+yb!*@G1&;c@r78 zo(=5q4_{1Q`t`#crN80g(KV|?!8s@VM(opsr#OO+-*NK)C@9_GS z%`NWe4Sxj>Ov9PSJG4{JyG)oXAKcyD{a3?O70qhNre614zb+br8lNW5KO<-7zy0fz(HvMc$V*%y8aW&!FZ@41 z27KaGc>nHO4<-{B%h7P$41r|AWp0acfT@`wl%$r_B;^s`{JHq~PwdM+u&R&`v9gjD zgPlAL+L)4>i<866lRl59iyp{|*Do*4FQ3|s^r;;dUS7Jm9Fao-ca5Z%0dLY$+79^! z4zSde`?K3LM5Z-g@9idNb^8pOZhFM!cIHCbLW&Oq8fNxsq)N;j-8&RCJad4hUE<^I z=w_ORCJTy4O*==*Fo_WoqiGV>J^D2KNjugtbj=Aebo$>qcrcLP2@)qsOc*F?WBN3` zM%uG!4Crb?GIUx5F3{&05>tB&)_wY%CUI_$0g_WbPir$ICP>((EM}3vl~jv`C3ZA> y3##~#H@O=7{j0AZ-2C`utk5d-x0sAL7WruAXC8!)?tE4}^6784(uc*0HNbydu!(s9 literal 0 HcmV?d00001 diff --git a/src/test/resources/org/junit/internal/arrayComparisonFailure_412 b/src/test/resources/org/junit/internal/arrayComparisonFailure_412 new file mode 100644 index 0000000000000000000000000000000000000000..11fe0c51d7b1e8c9fe888d2889e2ba1b5c766ba2 GIT binary patch literal 2078 zcmah~O>A355T55aC3W-Hq!ilV(9$%eDZC^|tw<9h8RJNnob-@TkSZZ7^G+n0f2x=hR8@VLWeV_M7>3 zXJ+sG4gH~l^S)}@TahQUEj-PY$E00SioIR--GC_(`rZl?GEyAO&&okx4GuNREDE`X zleI0@VzZKY&Dl~Ia;1guRh078VhsiwRj)1_9%>jhevuY(wkATISXX%%vL>R8b)l?l zCA{Whtl(*awh7wa3;n%ofAg^P${#rZbQ{UslE9VXrK`6-7`|$(o&Xxeb=B6YUbS7P|U&XC$DvFUGEqw zlDpg^rpLl42o#d#^-ApUfX*l+q+A@(-{BxqDT?9Si;`QJSz3Dd+yb!*@G1&;c@r78 zo(=5q4_{1Q`t`#crN80g(KV|?!8s@VM(opsr#OO+-*NK)C@9_GS z%`NWe4Sxj>Ov9PSJG4{JyG)oXAKcyD{a3?O70qhNre614zb+br8lNW5KO<-7zy0fz(HvMc$V*%y8aW&!FZ@41 z27KaGc>nHO4<-{B%h7P$41r|AWp0acfT@`wl%$r_B;^s`{JHq~PwdM+u&R&`v9gjD zgPlAL+L)4>i<866lRl59iyp{|*Do*4FQ3|s^r;;dUS7Jm9Fao-ca5Z%0dLY$+79^! z4zSde`?K3LM5Z-g@9idNb^8pOZhFM!cIHCbLW&Oq8fNxsq)N;j-8&RCJad4hUE<^I z=w_ORCJTy4O*==*Fo_WoqiGV>J^D2KNjugtbj=Aebo$>qcrcLP2@)qsOc*F?WBN3` zM%uG!4Crb?GIUx5F3{&05>tB&)_wY%CUI_$0g_WbPir$ICP>((EM}3vl~jv`C3ZA> y3##~#H@O=7{j0AZ-2C`utk5d-x0sAL7WruAXC8!)?tE4}^6784(uc*0HNbydu!(s9 literal 0 HcmV?d00001 diff --git a/to-do.txt b/to-do.txt new file mode 100644 index 000000000000..4efa20f634a3 --- /dev/null +++ b/to-do.txt @@ -0,0 +1,27 @@ +* update documentation + * new cook's tour + * update Test Infected +* Should there be a "prefix" annotation for Suites? + * This would allow two Suites with different BeforeClass/AfterClass behaviors, + but the same component tests, to co-exist + +* update the build process + * update site for plug-in version? +* Ant + * Basic task +* support testing run once initialization code e.g. class Foo {{...}} +* Automatically add failing tests to the Known Defects section of the README.html + +* Create assume(that()) and assert(that()) + (what is a better name for the second one?) + +* Simplify implementation of equality, and organize AssertionTest + +* Theories class validation should be much better + +* Find a way to make Parameterized a single-class extension + +* If a suite() returns a JUnit4TestAdapter, allow Filters and Sorters to operate on + the adapted Runner. + +* Every time I add a Filter feature, I have to add an equivalent Sorter feature. Suspicious.