junit4-r4.13.2/000077500000000000000000000000001401177727100132075ustar00rootroot00000000000000junit4-r4.13.2/.gitattributes000066400000000000000000000017341401177727100161070ustar00rootroot00000000000000* text eol=lf *.gif binary *.GIF binary *.jar binary *.png binary *.jpg binary *.svg text eol=lf # These files do not have unix line endings. Do not normalize them for now. # Will fix these right before we cut JUnit 4.13. /src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java -text /src/main/java/org/junit/experimental/categories/ExcludeCategories.java -text /src/main/java/org/junit/experimental/categories/IncludeCategories.java -text /src/main/java/org/junit/internal/Classes.java -text /src/main/java/org/junit/runner/FilterFactories.java -text /src/main/java/org/junit/runner/FilterFactory.java -text /src/main/java/org/junit/runner/FilterFactoryParams.java -text /src/main/java/org/junit/runner/JUnitCommandLineParseResult.java -text /src/test/java/org/junit/experimental/categories/CategoryFilterFactoryTest.java -text /src/test/java/org/junit/runner/FilterFactoriesTest.java -text /src/test/java/org/junit/runner/JUnitCommandLineParseResultTest.java -text junit4-r4.13.2/.github/000077500000000000000000000000001401177727100145475ustar00rootroot00000000000000junit4-r4.13.2/.github/workflows/000077500000000000000000000000001401177727100166045ustar00rootroot00000000000000junit4-r4.13.2/.github/workflows/main.yml000066400000000000000000000027621401177727100202620ustar00rootroot00000000000000name: CI on: push: branches: - main pull_request: branches: - '*' jobs: build-and-verify: name: Build and verify (JDK ${{ matrix.java }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: java: [6, 8, 11, 15, 17-ea] steps: - uses: actions/checkout@v2 - name: Download Maven # Download with default JDK because OpenJDK 6 does not support TLS 1.2 run: ./mvnw --version - name: Set up JDK uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - name: Build and verify run: ./mvnw verify javadoc:javadoc site:site --batch-mode --errors --settings .github/workflows/settings.xml publish-snapshots: name: Publish snapshot artifacts if: github.event_name == 'push' && github.repository == 'junit-team/junit4' && github.ref == 'refs/heads/main' needs: build-and-verify runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Download Maven # Download with default JDK because OpenJDK 6 does not support TLS 1.2 run: ./mvnw --version - name: Set up JDK uses: actions/setup-java@v1 with: java-version: 6 - name: Publish snapshot artifacts env: OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} run: ./mvnw deploy --batch-mode --errors --activate-profiles generate-docs --settings .github/workflows/settings.xml junit4-r4.13.2/.github/workflows/settings.xml000066400000000000000000000013611401177727100211670ustar00rootroot00000000000000 central GCS Maven Central mirror https://maven-central.storage-download.googleapis.com/maven2/ google-maven-central junit-snapshot-repo ${env.OSSRH_USERNAME} ${env.OSSRH_PASSWORD} junit-releases-repo ${env.OSSRH_USERNAME} ${env.OSSRH_PASSWORD} junit4-r4.13.2/.gitignore000066400000000000000000000001541401177727100151770ustar00rootroot00000000000000MaxCore.ser bin junit4.* target MaxCore.max # IntelliJ .idea *.ipr *.iml *.iws out java.hprof.txt .DS_Store junit4-r4.13.2/BUILDING000066400000000000000000000006771401177727100143410ustar00rootroot00000000000000BUILDING FROM GITHUB: ===================== git clone https://github.com/junit-team/junit4.git cd junit4 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 junit4-r4.13.2/CODING_STYLE.txt000066400000000000000000000007401401177727100156740ustar00rootroot00000000000000JUnit 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. Be sure to set text file encoding to UTF-8 and line delimiters to UNIX style. Since not all code has been formatted yet, please format only code lines you changed to avoid extraneous changes. Legacy code (under junit.*) used the legacy guide specified in LEGACY_CODING_STYLE.txt in the project root. junit4-r4.13.2/CONTRIBUTING.md000066400000000000000000000046501401177727100154450ustar00rootroot00000000000000## 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). ## Coding Conventions ### Formatting See [CODING_STYLE.txt](CODING_STYLE.txt) for how we format our code. ## 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 `main`. 4. Ensure that you have a clean state by running `./mvnw 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 `./mvnw 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. ## Limitations The JUnit team is not accepting changes to the code under the following paths: * `src/main/java/junit` * `test/java/junit/tests/framework` * `test/java/junit/tests/extensions` The reasoning is that the JUnit team feels that our users should focus on using either the JUnit4 or JUnit5 APIs. The team is also reluctant to accept changes that only update code from one code style to another. Generally the code in JUnit was approved by at least one person, so two people agreed that the style was reasonable. To find other places where you can have an impact, please see the [Issues tagged "up-for-grabs"](https://github.com/junit-team/junit4/issues?q=is%3Aissue+is%3Aopen+label%3Aup-for-grabs). junit4-r4.13.2/KEYS000066400000000000000000000073711401177727100137150ustar00rootroot00000000000000This file contains the PGP key that is used to sign releases. Importing: `pgp < KEYS` or `gpg --import KEYS` Adding a key: `pgp -kxa >> KEYS`, or `(pgpk -ll && pgpk -xa ) >> KEYS`, or `(gpg --list-sigs && gpg --armor --export ) >> KEYS` ================================ pub rsa4096 2018-04-08 [SC] FF6E2C001948C5F2F38B0CC385911F425EC61B51 uid [ unknown] Open Source Development sig 3 85911F425EC61B51 2018-04-08 Open Source Development sub rsa4096 2018-04-08 [E] sig 85911F425EC61B51 2018-04-08 Open Source Development -----BEGIN PGP PUBLIC KEY BLOCK----- mQINBFrKW9IBEACkqUvM7hU1WqOOeb1gZ7pUsRliHuoUvYIrd+hdp+qhPmJ0NG0W YhZK5UtJBmqvtHKRkbwYxUuya9zlBmCfQFf0GpFKJ65JSrPSkZADI3aZ4aUkxIUw nIRoUHucmr10Xftpebr/zaJk5oR8RdaL5FapapmcZmAaHR9CDWB8XtI318u314jq M5rKatnAZMERoPugOvvuAOz4bfZKwdfCmZKfYUM/TMSrSinXrGExSW6z4RhtqmpC E5M/7OoVfvDynVJKqNazqgigpmMNhOyzAhQsiKh1K0akyxTZbjeZKsdYfhCXvq0q k9+KM/cTllQ54MPnFWiObLkHeK0Waw8bI/vAJ4h4x/XM9iGYpkXv7F2/FVsHQdPe YJcwD/CkD8KHyiPaRKMeApiUtZsdAHU0L4X/lNmcooea/7ipskruUgwcm+RdLhRZ P949t1e7nqDZfpEHy90NiFxmlRAPSNqBLwefxY/hwBgog2jabDALJVcLCMosFWPj MQhFlGSIODiVcW8folGIjzkyNZbNMWkwnl2QnWp/h2TAwYQJOMqcv2MG9o5pyzpx 97Iz1ngq1FlM/gJnGnNUydP2tAjT2L2U3MP1uX/EdRChdgPqdolqYhdFfwCr0Fpf W527bUZpReHCEiQ29ABSnQ711mO+d9+qM6edRyHUoBWz89IHt8sCunuvNwARAQAB tC1PcGVuIFNvdXJjZSBEZXZlbG9wbWVudCA8bWFpbEBtYXJjcGhpbGlwcC5kZT6J Ak4EEwEIADgWIQT/biwAGUjF8vOLDMOFkR9CXsYbUQUCWspb0gIbAwULCQgHAgYV CAkKCwIEFgIDAQIeAQIXgAAKCRCFkR9CXsYbUQyRD/9xm3BqdpWcRCE5UyB6nbwV 8TgzMmbOhpFhhcjzobly/pKAbcofKsjhreENJkfBVUo+zAFx21ToC5tbH20wRtIE vQVCP6sAIzhYWU1ohafqVFP4+PztNBuYTnS6vGvSwzp0IXLIIoxSxo0IOED9uUS9 DTxh1n9NnDLDe2pfjrXBblQtLSW3W5ISDoUvcoyO7Hk1OByW6MNsSoLvXIUNeVhB ju9TfYxFACJSWBhUxJfgip9Y2GrNBJaYGLZrTAoW1Lh1H1DfLV3wHDClQ1+H+oyx IOZULEGYY3MgZTd6Ner2yNAUCB7gVa50NiCZXCS74m+XzMrTEsdWjSMUaOe+dL0I 9MCrgi4ycUHWIfTKx9gGlIOo3hSDMN+8Nj33XPjLT8kcfoFeUX8jTOvC1HFfTuQJ x2t/dKHizdrS3F6A/JQa7v8GNTrZFnEXkwgRTf3ccLoo3gPwzNJeCm2xNjvne1VH fvxzwNmq8M05oicEigvEed2VMStMhvT7dSiMAf66rEJHjjaHAoNqbLDEATYrWUP2 I52txHSSxSJohxVP6Ec6dERnqqYi0mVyzBPo7mmFFBisq74w8RvZXyzvXE3BTiDL we1E/Z/AXbtJye9DickQ/G6RFtVLbUHQfzyRS/65JPtlH8rqJr58YWlylGImVLwE OsKNQrwLZ0UkfaWV7wqr3rkCDQRaylvSARAAnQG636wliEOLkXN662OZS6Qz2+cF ltCWboq9oX9FnA1PHnTY2cAtwS214RfWZxkjg6Stau+d1Wb8TsF/SUN3eKRSyrkA xlX0v552vj3xmmfNsslQX47e6aEWZ0du0M8jw7/f7Qxp0InkBfpQwjSg4ECoH4cA 6dOFJIdxBv8dgS4K90HNuIHa+QYfVSVMjGwOjD9St6Pwkbg1sLedITRo59Bbv0J1 4nE9LdWbCiwNrkDr24jTewdgrDaCpN6msUwcH1E0nYxuKAetHEi2OpgBhaY3RQ6Q PQB6NywvmD0xRllMqu4hSp70pHFtm8LvJdWOsJ5we3KijHuZzEbBVTTl+2DhNMI0 KMoh+P/OmyNOfWD8DL4NO3pVv+mPDZn82/eZ3XY1/oSQrpyJaCBjRKasVTtfiA/F gYqTml6qZMjy6iywg84rLezELgcxHHvjhAKd4CfxyuCCgnGT0iRLFZKw44ZmOUqP DkyvGRddIyHag1K7UaM/2UMn6iPMy7XWcaFiH5Huhz43SiOdsWGuwNk4dDxHdxmz Sjps0H5dkfCciOFhEc54AFcGEXCWHXuxVqIq/hwqTmVl1RY+PTcQUIOfx36WW1ix JQf8TpVxUbooK8vr1jOFF6khorDXoZDJNhI2VKomWp8Y38EPGyiUPZNcnmSiezx+ MoQwAbeqjFMKG7UAEQEAAYkCNgQYAQgAIBYhBP9uLAAZSMXy84sMw4WRH0JexhtR BQJaylvSAhsMAAoJEIWRH0JexhtR0LEP/RvYGlaokoosAYI5vNORAiYEc1Ow2McP I1ZafHhcVxZhlwF48dAC2bYcasDX/PbEdcD6pwo8ZU8eI8Ht0VpRQxeV/sP01m2Y EpAuyZ6jI7IQQCGcwQdN4qzQJxMAASl9JlplH2NniXV1/994FOtesT59ePMyexm5 7lzhYXP1PGcdt8dH37r6z3XQu0lHRG/KBn7YhyA3zwJcno324KdBRJiynlc7uqQq +ZptU9fR1+Nx0uoWZoFMsrQUmY34aAOPJu7jGMTG+VseMH6vDdNhhZs9JOlD/e/V aF7NyadjOUD4j/ud7c0z2EwqjDKMFTHGbIdawT/7jartT+9yGUO+EmScBMiMuJUT dCP4YDh3ExRdqefEBff3uE/rAP73ndNYdIVq9U0gY0uSNCD9JPfj4aCN52y9a2pS 7Dg7KB/Z8SH1R9IWP+t0HvVtAILdsLExNFTedJGHRh7uaC7pwRz01iivmtAKYICz ruqlJie/IdEFFK/sus6fZek29odTrQxx42HGHO5GCNyEdK9jKVAeuZ10vcaNbuBp iP7sf8/BsiEU4wHE8gjFeUPRiSjnERgXQwfJosLgf/K/SShQn2dCkYZRNF+SWJ6Z 2tQxcW5rpUjtclV/bRVkUX21EYfwA6SMB811mI7AVy8WPXCe8La72ukmaxEGbpJ8 mdzS2PJko7mm =l0XA -----END PGP PUBLIC KEY BLOCK----- junit4-r4.13.2/LEGACY_CODING_STYLE.txt000066400000000000000000000052371401177727100167260ustar00rootroot00000000000000================================== 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) junit4-r4.13.2/LICENSE-junit.txt000066400000000000000000000261601401177727100161660ustar00rootroot00000000000000JUnit 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. junit4-r4.13.2/NOTICE.txt000066400000000000000000000005171401177727100147340ustar00rootroot00000000000000 =================================================================================== == Notices and attributions required by libraries that the project depends on == =================================================================================== The JUnit depends on Java Hamcrest (http://hamcrest.org/JavaHamcrest/). junit4-r4.13.2/README.md000066400000000000000000000010141401177727100144620ustar00rootroot00000000000000# 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) [![CI Status](https://github.com/junit-team/junit4/workflows/CI/badge.svg)](https://github.com/junit-team/junit4/actions) junit4-r4.13.2/acknowledgements.txt000066400000000000000000000127561401177727100173150ustar00rootroot000000000000002006 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/junit4 junit4-r4.13.2/doc/000077500000000000000000000000001401177727100137545ustar00rootroot00000000000000junit4-r4.13.2/doc/ReleaseNotes4.10.html000066400000000000000000000067741401177727100175540ustar00rootroot00000000000000

Summary of Changes in version 4.10

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]
junit4-r4.13.2/doc/ReleaseNotes4.10.md000066400000000000000000000063141401177727100171760ustar00rootroot00000000000000## 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...r4.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] junit4-r4.13.2/doc/ReleaseNotes4.10.txt000066400000000000000000000000371401177727100174110ustar00rootroot00000000000000Please see ReleaseNotes4.10.md junit4-r4.13.2/doc/ReleaseNotes4.11.html000066400000000000000000000131221401177727100175360ustar00rootroot00000000000000

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.
junit4-r4.13.2/doc/ReleaseNotes4.11.md000066400000000000000000000114701401177727100171760ustar00rootroot00000000000000## 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. junit4-r4.13.2/doc/ReleaseNotes4.11.txt000066400000000000000000000000371401177727100174120ustar00rootroot00000000000000Please see ReleaseNotes4.11.md junit4-r4.13.2/doc/ReleaseNotes4.12.md000066400000000000000000001076731401177727100172120ustar00rootroot00000000000000## 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/junit4/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. A specified timeout of 0 will be interpreted as not set, however tests still launch from separate threads. This can be useful for disabling timeouts in environments where they are dynamically set based on some property. # 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. junit4-r4.13.2/doc/ReleaseNotes4.13.1.md000066400000000000000000000013331401177727100173340ustar00rootroot00000000000000## Summary of changes in version 4.13.1 # Rules ### Security fix: `TemporaryFolder` now limits access to temporary folders on Java 1.7 or later A local information disclosure vulnerability in `TemporaryFolder` has been fixed. See the published [security advisory](https://github.com/junit-team/junit4/security/advisories/GHSA-269g-pwp5-87pp) for details. # Test Runners ### [Pull request #1669:](https://github.com/junit-team/junit/pull/1669) Make `FrameworkField` constructor public Prior to this change, custom runners could make `FrameworkMethod` instances, but not `FrameworkField` instances. This small change allows for both now, because `FrameworkField`'s constructor has been promoted from package-private to public. junit4-r4.13.2/doc/ReleaseNotes4.13.2.md000066400000000000000000000045531401177727100173440ustar00rootroot00000000000000## Summary of changes in version 4.13.2 # Rules ### [Pull request #1687:](https://github.com/junit-team/junit/pull/1687) Mark ThreadGroups created by FailOnTimeout as daemon groups In JUnit 4.13 ([pull request #1517](https://github.com/junit-team/junit4/pull/1517)) an attempt was made to fix leakage of the `ThreadGroup` instances created when a test is run with a timeout. That change explicitly destroyed the `ThreadGroup` that was created for the time-limited test. Numerous people reported problems that were caused by explicitly destroying the `ThreadGroup`. In this change, the code was updated to call `ThreadGroup.setDaemon(true)` instead of destroying the ThreadGroup. ### [Pull request $1691:](https://github.com/junit-team/junit/pull/1691) Only create ThreadGroups if FailOnTimeout.lookForStuckThread is true. In JUnit 4.12 ([pull request #742](https://github.com/junit-team/junit4/pull/742)) the `Timeout` Rule was updated to optionally display the stacktrace of the thread that appears to be stuck (enabled on an opt-in basis by passing `true` to `Timeout.Builder.lookForStuckThread(boolean)`). When that change was made, time-limited tests were changed to start the new thread in a new `ThreadGroup`, even if the test did not call `lookForStuckThread()`. This subtle change in behavior resulted in visible behavior changes to some tests (for example, tests of code that uses `java.beans.ThreadGroupContext`). In this change, the code is updated to only create a new `ThreadGroup` if the caller calls `Timeout.Builder.lookForStuckThread(true)`. Tests with timeouts that do not make this call will behave as they did in JUnit 4.11 (and more similar to tests that do not have a timeout). This unfortunately could result in visible changes of tests written or updated since the 4.12 release. If this change adversely affects your tests, you can create the `Timeout` rule via the builder and call `Timeout.Builder.lookForStuckThread(true)`. # Exceptions ### [Pull request #1654:](https://github.com/junit-team/junit/pull/1654) Fix for issue #1192: NotSerializableException with AssumptionViolatedException This change fixes an issue where `AssumptionViolatedException` instances could not be serialized if they were created with a constructor that takes in an `org.hamcrest.Matcher` instance (these constructors are used if you use one of the `assumeThat()` methods in `org.junit.Assume`). junit4-r4.13.2/doc/ReleaseNotes4.13.md000066400000000000000000000566271401177727100172150ustar00rootroot00000000000000## Summary of changes in version 4.13 # Assertions ### [Pull request #1054:](https://github.com/junit-team/junit/pull/1054) Improved error message for `assertArrayEquals` when multi-dimensional arrays have different lengths Previously, JUnit's assertion error message would indicate only that some array lengths _x_ and _y_ were unequal, without indicating whether this pertained to the outer array or some nested array. Now, in case of a length mismatch between two nested arrays, JUnit will tell at which indices they reside. ### [Pull request #1154](https://github.com/junit-team/junit/pull/1154) and [#1504](https://github.com/junit-team/junit/pull/1504) Add `assertThrows` The `Assert` class now includes methods that can assert that a given function call (specified, for instance, as a lambda expression or method reference) results in a particular type of exception being thrown. In addition it returns the exception that was thrown, so that further assertions can be made (e.g. to verify that the message and cause are correct). ### [Pull request #1300:](https://github.com/junit-team/junit/pull/1300) Show contents of actual array when array lengths differ Previously, when comparing two arrays which differ in length, `assertArrayEquals()` would only report that they differ in length. Now, it does the usual array comparison even when arrays differ in length, producing a failure message which combines the difference in length and the first difference in content. Where the content is another array, it is described by its type and length. ### [Pull request #1315:](https://github.com/junit-team/junit4/pull/1315) `assertArrayEquals` shouldn't throw an NPE when test suites are compiled/run across versions of junit A redundant field, `fCause`, was removed on v4.12, and was seemingly harmless because `Throwable#initCause()` could directly initialize `cause` in the constructor. Unfortunately, this backwards incompatible change got aggravated when a test class, compiled with the latest (4.12+), ran with an older version that depended on fCause when building the assertion message[1](#1315-f1). This change adds back `fCause`, and overrides `getCause()` to handle forward compatibility[2](#1315-f2). To ensure serializability of further changes in `ArrayAssertionFailure` (until excising these fields by a major rev), a unit test now runs against v4.11, v4.12 failures, asserting around `#toString/getCause()`. [1] [Issue #1178](https://github.com/junit-team/junit4/issues/1178) details a particular case where gradle v2.2 is packaged with junit v4.11 and is used on running a test, generating test reports, despite specifying a particular version of junit (users would specify v4.12, or v4.+) in the test compile dependencies). [2] [Case](https://github.com/junit-team/junit4/pull/1315#issuecomment-222905229) if the test class is compiled with <= v4.11, where only `fCause` is initialized and not `Throwable#cause`, it can now fallback to the field, `fCause`, when building the message. ### [Pull request #1150:](https://github.com/junit-team/junit4/pull/1150) Deprecate `Assert#assertThat` The method `assertThat` is used for writing assertions with Hamcrest. Hamcrest is an independent assertion library and contains an own `assertThat` method in the class `org.hamcrest.MatcherAssert`. It is available both in the old Hamcrest 1.3 release and in the current Hamcrest 2.1. Therefore the JUnit team recommends to use Hamcrest's own `assertThat` directly. # Test Runners ### [Pull request #1037:](https://github.com/junit-team/junit/pull/1037) `BlockJUnit4ClassRunner#createTest` now accepts `FrameworkMethod` Subclasses of `BlockJUnit4ClassRunner` can now produce a custom test object based on the `FrameworkMethod` test being executed by implementing the new `createTest(FrameworkMethod)` method. The default implementation calls the existing `createTest()` method. ### [Pull request #1082](https://github.com/junit-team/junit/pull/1082): Ensure exceptions from `BlockJUnit4ClassRunner.methodBlock()` don't result in unrooted tests The introduction of the `runLeaf()` method in `BlockJUnit4ClassRunner` in JUnit 4.9 introduced a regression with regard to exception handling. Specifically, in JUnit 4.9 through 4.12 the invocation of `methodBlock()` is no longer executed within a try-catch block as was the case in previous versions of JUnit. Custom modifications to `methodBlock()` or the methods it invokes may in fact throw exceptions, and such exceptions cause the current test execution to abort immediately. As a result, the failing test method is unrooted in test reports, and subsequent test methods are never invoked. Furthermore, any `RunListener` registered with JUnit is not notified. As of JUnit 4.13, the invocation of `methodBlock()` is once again wrapped within a try-catch block. If an exception is _not_ thrown, the resulting `Statement` is passed to `runLeaf()`. If an exception _is_ thrown, it is wrapped in a `Fail` statement which is passed to `runLeaf()`. ### [Pull request #1286](https://github.com/junit-team/junit/pull/1286): Provide better feedback to the user in case of invalid test classes Only one exception per invalid test class is now thrown, rather than one per validation error. The message of the exception includes all of the validation errors. Example: org.junit.runners.InvalidTestClassError: Invalid test class 'com.example.MyTest': 1. Method staticAfterMethod() should not be static 2. Method staticBeforeMethod() should not be static is the exception thrown when running the following test class with any kind of `ParentRunner`: public class MyTest { @Before public static void staticBeforeMethod() { .. } @After public static void staticAfterMethod() { .. } @Test public void myTest() { .. } } Validation errors for the same test class now count only once in the failure count. Therefore, in the example above, `Result#getFailureCount` will return 1. ### [Pull request #1252](https://github.com/junit-team/junit4/pull/1252): Restore ability use ParentRunner lost in separate class loader `ParentRunner.getDescription()` now uses the class instance of the test class to create the description (previously the class instance was loaded using the current classloader). ### [Pull request #1377](https://github.com/junit-team/junit4/pull/1377): Description produced by Request.classes() shouldn't be null When obtaining a `Runner` via [Request.classes(Class... classes)](http://junit.org/junit4/javadoc/4.12/org/junit/runner/Request.html#classes(java.lang.Class...)), that Runner's `Description` will now print "classes" for the root item. This replaces the misleading output of String "null". ### [Issue #1290](https://github.com/junit-team/junit4/issues/1290): Tests expecting AssumptionViolatedException are now correctly marked as passed @Test(expected = AssumptionViolatedException.class) public void shouldThrowAssumptionViolatedException() { throw new AssumptionViolatedException("expected"); } This test would previously be marked as skipped; now will be marked as passed. ### [Pull request #1465](https://github.com/junit-team/junit/pull/1465): Provide helpful message if parameter cannot be set. JUnit throws an exception with a message like Cannot set parameter 'name'. Ensure that the the field 'name' is public. if a field of a parameterized test is annotated `@Parameter`, but its visibility is not public. Before an IllegalAccessException was thrown with a message like "Class ... can not access a member of class X with modifiers private". ### [Issue #1329](https://github.com/junit-team/junit4/issus/1329): Support assumptions in `@Parameters` method No test is run when an assumption in the `@Parameters` method fails. The test result for this test class contains one assumption failure and run count is zero. ### [Pull request #1449](https://github.com/junit-team/junit/pull/1449): Parameterized runner reuses TestClass instance Reduce memory consumption of parameterized tests by not creating a new instance of `TestClass` for every test. ### [Pull request #1130](https://github.com/junit-team/junit/pull/1130): Add Ordering, Orderable and @OrderWith Test classes can now be annotated with `@OrderWith` to specify that the tests should execute in a particular order. All runners extending `ParentRunner` support `@OrderWith`. Runners can also be ordered using `Request.orderWith(Ordering)` Classes annotated with `@RunWith(Suite.class)` can also be ordered with `@OrderWith`. Note that if this is done, nested classes annotated with `@FixMethodOrder` will not be reordered (i.e. the `@FixMethodOrder` annotation is always respected). Having a test class annotated with both `@OrderWith` and `@FixMethodOrder` will result in a validation error (see [pull request #1638](https://github.com/junit-team/junit4/pull/1638)). ### [Pull request #1408](https://github.com/junit-team/junit/pull/1408): Suites don't have to be public Classes annotated with `@RunWith(Suite.class)` do not need to be public. This fixes a regression bug in JUnit 4.12. Suites didn't had to be public before 4.12. ### [Pull request #1638](https://github.com/junit-team/junit4/pull/1638): Never reorder classes annotated with @FixMethodOrder Changing the order of a test run using `Request.sortWith()` no longer changes the order of test classes annotated with `@FixMethodOrder`. The same holds true when you reorder tests with `Request.orderWith()` (`orderWith()` was introduced in [Pull request #1130](https://github.com/junit-team/junit/pull/1130)). This was done because usually `@FixMethodOrder` is added to a class because the tests in the class they only pass if run in a specific order. Test suites annotated with `@OrderWith` will also respect the `@FixMethodOrder` annotation. Having a test class annotated with both `@OrderWith` and `@FixMethodOrder` will result in a validation error. # Rules ### [Pull request #1044:](https://github.com/junit-team/junit/pull/1044) Strict verification of resource deletion in `TemporaryFolder` rule Previously `TemporaryFolder` rule did not fail the test if some temporary resources could not be deleted. With this change a new `assuredDeletion` parameter is introduced which will fail the test with an `AssertionError`, if resource deletion fails. The default behavior of `TemporaryFolder` is unchanged. This feature must be enabled by creating a `TemporaryFolder` using the `TemporaryFolder.builder()` method: ```java @Rule public TemporaryFolder folder = TemporaryFolder.builder().assureDeletion().build(); ``` ### [Issue #1100:](https://github.com/junit-team/junit/issues/1110) StopWatch does not need to be abstract. Previously `StopWatch` was an abstract class, which means it cannot be used without extending it or using an anonymous class. The abstract modifier has been removed and StopWatch can be used easily now. ### [Issue #1157:](https://github.com/junit-team/junit/issues/1157) TestName: Make 'name' field volatile The `name` field in the `TestName` rule was updated to be volatile. This should ensure that the name is published even when tests are running in parallel. ### [Issue #1223:](https://github.com/junit-team/junit/issues/1223) TemporaryFolder doesn't work for parallel test execution in several JVMs Previously `TemporaryFolder` rule silently succeeded if it failed to create a fresh temporary directory. With this change it will notice the failure, retry with a new name, and ultimately throw an `IOException` if all such attempts fail. ### [Pull request #1305:](https://github.com/junit-team/junit/pull/1305) Add `ErrorCollector.checkThrows` The `ErrorCollector` class now has a `checkThrows` method that can assert that a given function call (specified, for instance, as a lambda expression or method reference) results in a particular type of exception being thrown. ### [Issue #1303:](https://github.com/junit-team/junit/issues/1303) Prevent following symbolic links when deleting temporary directories Previously, `TemporaryFolder` would follow symbolic links; now it just deletes them. Following symbolic links when removing files can lead to the removal of files outside the directory structure rooted in the temporary folder, and it can lead to unbounded recursion if a symbolic link points to a directory where the link is directly reachable from. ### [Issue #1295:](https://github.com/junit-team/junit/issues/1295) Javadoc for RuleChain contains errors Removed error from RuleChain Javadoc and clarified how it works with existing rules. Removed `static` modifier, added missing closing parenthesis of method calls and added clarification. ### [Pull request #1313](https://github.com/junit-team/junit4/pull/1313): `RuleChain.around()` rejects null arguments `RuleChain.around()` now implements a fail-fast strategy which also allows for better feedback to the final user, as the stacktrace will point to the exact line where the null rule is declared. ### [Pull request #1397](https://github.com/junit-team/junit4/pull/1397): Change generics on `ExpectedException.expectCause()` The signature of `ExpectedException.expectCause()` would not allow the caller to pass in a `Matcher` (which is returned by `CoreMatchers.notNullValue()`). This was fixed by changing the method to take in a `Matcher` (ideally, the method should take in `Matcher` but there was concern that changing the parameter type to `Matcher` would break some callers). ### [Pull request #1443](https://github.com/junit-team/junit4/pull/1443): `ExpectedException.isAnyExceptionExpected()` is now public The method `ExpectedException.isAnyExceptionExpected()` returns `true` if there is at least one expectation present for the `ExpectedException` rule. ### [Pull request #1395](https://github.com/junit-team/junit4/pull/1395): Wrap assumption violations in ErrorCollector Both `ErrorCollector.addError()` and `ErrorCollector.checkSucceeds()` now wrap `AssumptionViolatedException`. In addition, `ErrorCollector.addError()` will throw a `NullPointerException` if you pass in a `null` value. ### [Pull request #1402](https://github.com/junit-team/junit4/pull/1402): TemporaryFolder.newFolder(String) supports paths with slashes There was a regression in JUnit 4.12 where `TemporaryFolder.newFolder(String)` no longer supported passing in strings with separator characters. This has been fixed. he overload of newFolder() that supports passing in multiple strings still does not allow path separators. ### [Pull requests #1406 (part 1)](https://github.com/junit-team/junit4/pull/1406) and [#1568](https://github.com/junit-team/junit4/pull/1568): Improve error message when TemporaryFolder.newFolder(String) fails When `newFolder(String path)` was not able to create the folder then it always failed with the error message "a folder with the name '``' already exists" although the reason for the failure could be something else. This message is now only used if the folder really exists. The message is "a file with the path '``' exists" if the whole path or a part of the path points to a file. In all other cases it fails now with the message "could not create a folder with the path '``'" ### [Pull request #1406 (part 2)](https://github.com/junit-team/junit4/pull/1406): TemporaryFolder.newFolder(String...) supports path separator You can now pass paths with path separators to `TemporaryFolder.newFolder(String...)`. E.g. tempFolder.newFolder("temp1", "temp2", "temp3/temp4") It creates a folder `temp1/temp2/temp3/temp4`. ### [Pull request #1406 (part 3)](https://github.com/junit-team/junit4/pull/1406): TemporaryFolder.newFolder(String...) fails for empty array When you call tempFolder.newFolder(new String[]) then it throws an `IllegalArgumentException` instead of returning an already existing folder. ### [Pull request #1335](https://github.com/junit-team/junit4/pull/1335): Fix ExternalResource: the test failure could be lost When both the test failed and closing the resource failed, only the exception coming from the `after()` method was propagated, as per semantics of the try-finally (see also http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2). The new behavior is compatible with @After method semantics, as implemented in [RunAfters](https://github.com/junit-team/junit4/blob/HEAD/src/main/java/org/junit/internal/runners/statements/RunAfters.java). ### [Pull request #1435](https://github.com/junit-team/junit4/pull/1435): @BeforeParam/@AfterParam method annotations for Parameterized tests. This allows having preparation and/or cleanup in tests for specific parameter values. ### [Pull request #1460](https://github.com/junit-team/junit4/pull/1460): Handle assumption violations in the @Parameters method for Parameterized tests. This allows skipping the whole test class when its assumptions are not met. ### [Pull request #1445](https://github.com/junit-team/junit4/pull/1445) and [Pull request #1335](https://github.com/junit-team/junit4/pull/1501): Declarative ordering of rules. The order in which rules are executed is specified by the annotation attribute: `@Rule(order = N)`, deprecating `RuleChain`. This may be used for avoiding some common pitfalls with `TestWatcher, `ErrorCollector` and `ExpectedException` for example. The Javadoc of `TestWatcher` was retrofitted accordingly. ### [Pull request #1517](https://github.com/junit-team/junit4/pull/1517): Timeout rule destroys its ThreadGroups at the end The `ThreadGroup` created for handling the timeout of tests is now destroyed, so the main thread group no longer keeps a reference to all timeout groups created during the tests. This caused the `threadGroup` to remain in memory, and all of its context along with it. ### [Pull request #1633](https://github.com/junit-team/junit4/pull/1633): Deprecate ExpectedException.none() The method Assert.assertThrows provides a nicer way for verifying exceptions. In addition the use of ExpectedException is error-prone when used with other rules like TestWatcher because the order of rules is important in that case. ### [Pull request #1413](https://github.com/junit-team/junit4/pull/1413): Ignore bridge methods when scanning for annotated methods In a setup with a class hierarchy for test classes the order of rules (from methods), before methods, after methods and others depends on the class that contains these methods. Compilers can add bridge methods to child classes and therefore the order of the aforementioned methods can change in older JUnit releases. This is now fixed because bridge methods are ignored when scanning for annotated methods. ### [Pull request #1612](https://github.com/junit-team/junit4/pull/1612): Make @ValidateWith only applicable to annotation types `@Target(ANNOTATION_TYPE)` has been added to `@ValidateWith` since it's only designed to be applied to another annotation. # Run Listener ### [Pull request #1118:](https://github.com/junit-team/junit4/pull/1118) Add suite start/finish events to listener The `RunListener` class now has `fireTestSuiteStarted` and `fireTestSuiteFinished` methods that notify when test suites are about to be started/finished. # Exception Testing ### [Pull request #1359:](https://github.com/junit-team/junit4/pull/1359) Fixes how `MultipleFailureException` stack traces are printed Previously, calling `MultipleFailureException.printStackTrace()` only printed the stack trace for the `MultipleFailureException` itself. After this change, the stack trace for each exception caught in the `MultipleFailureException` is printed. ### [Pull request #1376:](https://github.com/junit-team/junit4/pull/1376) Initializing MultipleFailureException with an empty list will now fail the test Previously, initializing `MultipleFailureException` with an empty list of contained Exceptions and throwing it in a test case wouldn't actually fail the test. Now an `IllegalArgumentException` will be raised in this situation and thus also fail the test. ### [Pull request #1371:](https://github.com/junit-team/junit4/pull/1371) Update MultipleFailureException.assertEmpty() to wrap assumption failure `MultipleFailureException` will now wrap `MultipleFailureException` with `TestCouldNotBeSkippedException`. Previously, if you passed `MultipleFailureException` one `MultipleFailureException`--and no other exceptions-- then the test would be skipped, otherwise it would fail. With the new behavior, it will always fail. ### [Issue #1290:](https://github.com/junit-team/junit4/issues/1290) `@Test(expected = AssumptionViolatedException.class)` passes for AssumptionViolatedException Tests annotated with `@test(expected = AssumptionViolatedException.class)` which throw AssumptionViolatedException had been marked as skipped. Now the are marked as successful tests. # JUnit 3 Changes ### [Pull request #1227:](https://github.com/junit-team/junit/pull/1227) Behave better if the `SecurityManager` denies access to `junit.properties` Previously, running tests with a `SecurityManager` would cause the test runner itself to throw an `AccessControlException` if the security policy didn't want it reading from `~/junit.properties`. This will now be treated the same as if the file does not exist. # Misc ### [Pull request #1571:](https://github.com/junit-team/junit4/pull/1571) Set "junit" as "Automatic-Module-Name" For existing releases of JUnit the `Automatic-Module-Name` was derived from the name of the jar. In most cases it is already the name "junit". JUnit 4.13 explicitly sets the module name to "junit" so that it is independent from the jar's name. ### [Pull request #1028:](https://github.com/junit-team/junit4/pull/1028) Trim stack trace JUnit's command-line runner (`JUnitCore`) prints smaller stack traces. It skips all stack trace elements that come before the test method so that it starts at the test method. E.g. the output for the example from [Getting started](https://github.com/junit-team/junit4/wiki/Getting-started) page is now .E Time: 0,006 There was 1 failure: 1) evaluatesExpression(CalculatorTest) java.lang.AssertionError: expected:<6> but was:<-6> at org.junit.Assert.fail(Assert.java:89) at org.junit.Assert.failNotEquals(Assert.java:835) at org.junit.Assert.assertEquals(Assert.java:647) at org.junit.Assert.assertEquals(Assert.java:633) at CalculatorTest.evaluatesExpression(CalculatorTest.java:9) FAILURES!!! Tests run: 1, Failures: 1 ### [Pull request #1403:](https://github.com/junit-team/junit4/pull/1403) Restore CategoryFilter constructor The constructor `CategoryFilter(Class includedCategory, Class excludedCategory)` has been removed in JUnit 4.12. It is now available again. ### [Pull request #1530:](https://github.com/junit-team/junit4/pull/1530) Add Result#getAssumptionFailureCount Add method `getAssumptionFailureCount()` to `Result` which returns the number of assumption failures. ### [Pull request #1292:](https://github.com/junit-team/junit4/pull/1292) Fix ResultMatchers#hasFailureContaining `ResultMatchers.hasFailureContaining()` should return `false` when the given `PrintableResult` has no failures. ### [Pull request #1380:](https://github.com/junit-team/junit4/pull/1380) Fix Assume#assumeNotNull `Assume.assumeNotNull` should throw AssumptionViolatedException when called with a `null` array. ### [Pull request #1557:](https://github.com/junit-team/junit4/pull/1380) MaxCore always closes stream of history file MaxCore didn't close the output stream of the history file when write failed. Now it does. ### Signing The 4.13 release is signed with a new key (id 5EC61B51): https://github.com/junit-team/junit4/blob/8c0df64ff17fead54c304a8b189da839084925c2/KEYS junit4-r4.13.2/doc/ReleaseNotes4.4.html000066400000000000000000000276651401177727100175010ustar00rootroot00000000000000

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. 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:

    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.

junit4-r4.13.2/doc/ReleaseNotes4.4.md000066400000000000000000000266231401177727100171260ustar00rootroot00000000000000## 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. junit4-r4.13.2/doc/ReleaseNotes4.4.txt000066400000000000000000000000361401177727100173330ustar00rootroot00000000000000Please see ReleaseNotes4.4.md junit4-r4.13.2/doc/ReleaseNotes4.5.html000066400000000000000000000360231401177727100174660ustar00rootroot00000000000000

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. 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:

    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.

junit4-r4.13.2/doc/ReleaseNotes4.5.md000066400000000000000000000066011401177727100171210ustar00rootroot00000000000000## 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 junit4-r4.13.2/doc/ReleaseNotes4.5.txt000066400000000000000000000000361401177727100173340ustar00rootroot00000000000000Please see ReleaseNotes4.5.md junit4-r4.13.2/doc/ReleaseNotes4.6.html000066400000000000000000000066071401177727100174740ustar00rootroot00000000000000

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)
junit4-r4.13.2/doc/ReleaseNotes4.6.md000066400000000000000000000057321401177727100171260ustar00rootroot00000000000000## 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) junit4-r4.13.2/doc/ReleaseNotes4.6.txt000066400000000000000000000000361401177727100173350ustar00rootroot00000000000000Please see ReleaseNotes4.6.md junit4-r4.13.2/doc/ReleaseNotes4.7.html000066400000000000000000000133211401177727100174640ustar00rootroot00000000000000

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
junit4-r4.13.2/doc/ReleaseNotes4.7.md000066400000000000000000000123051401177727100171210ustar00rootroot00000000000000## 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 junit4-r4.13.2/doc/ReleaseNotes4.7.txt000066400000000000000000000000361401177727100173360ustar00rootroot00000000000000Please see ReleaseNotes4.7.md junit4-r4.13.2/doc/ReleaseNotes4.8.1.html000066400000000000000000000003201401177727100176170ustar00rootroot00000000000000

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.
junit4-r4.13.2/doc/ReleaseNotes4.8.1.md000066400000000000000000000002621401177727100172600ustar00rootroot00000000000000## 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.junit4-r4.13.2/doc/ReleaseNotes4.8.1.txt000066400000000000000000000000401401177727100174710ustar00rootroot00000000000000Please see ReleaseNotes4.8.1.md junit4-r4.13.2/doc/ReleaseNotes4.8.2.html000066400000000000000000000003331401177727100176240ustar00rootroot00000000000000

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
junit4-r4.13.2/doc/ReleaseNotes4.8.2.md000066400000000000000000000003001401177727100172520ustar00rootroot00000000000000## 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 junit4-r4.13.2/doc/ReleaseNotes4.8.2.txt000066400000000000000000000000401401177727100174720ustar00rootroot00000000000000Please see ReleaseNotes4.8.2.md junit4-r4.13.2/doc/ReleaseNotes4.8.html000066400000000000000000000030111401177727100174600ustar00rootroot00000000000000

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
junit4-r4.13.2/doc/ReleaseNotes4.8.md000066400000000000000000000025631401177727100171270ustar00rootroot00000000000000## 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 junit4-r4.13.2/doc/ReleaseNotes4.8.txt000066400000000000000000000000361401177727100173370ustar00rootroot00000000000000Please see ReleaseNotes4.8.md junit4-r4.13.2/doc/ReleaseNotes4.9.1.md000066400000000000000000000012031401177727100172550ustar00rootroot00000000000000## 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. junit4-r4.13.2/doc/ReleaseNotes4.9.1.txt000066400000000000000000000000401401177727100174720ustar00rootroot00000000000000Please see ReleaseNotes4.9.1.md junit4-r4.13.2/doc/ReleaseNotes4.9.html000066400000000000000000000066171401177727100175000ustar00rootroot00000000000000

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
junit4-r4.13.2/doc/ReleaseNotes4.9.md000066400000000000000000000057161401177727100171330ustar00rootroot00000000000000## 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 junit4-r4.13.2/doc/ReleaseNotes4.9.txt000066400000000000000000000000361401177727100173400ustar00rootroot00000000000000Please see ReleaseNotes4.9.md junit4-r4.13.2/doc/building-junit.txt000066400000000000000000000111751401177727100174460ustar00rootroot00000000000000Steps to build junit: - Must be manual - Write release notes - Not too tedious: - Push to github (junit-team) - Run the ./mvnw clean install - If not done, update $M2_HOME/settings.xml - 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) $ ./mvnw -Pjunit-release clean deploy - (to cut a release of the current targetted version) $ ./mvnw -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) $ ./mvnw -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: $ ./mvnw -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 $ ./mvnw -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 =================================================================================== junit4-r4.13.2/doc/cookstour/000077500000000000000000000000001401177727100160045ustar00rootroot00000000000000junit4-r4.13.2/doc/cookstour/Image1.gif000066400000000000000000000034341401177727100176020ustar00rootroot00000000000000GIF89a\,\@H*\ȰÇ#JHŋ3jȱǏ CI$H&S Dː,"f5sĉSAϝ12QDnL qAP&5*UUju׮`e#YN*0So8]q.+]t-CWzM,qŐFxLAWbya ~ q4ӨS^ͺװc˞MM֍7BkҜٓ8qDžLaGOdSޞݺS5Nӫ_~b|r |Vjf]wzcUa(g? GOU!}^^r!_r`h{0(h8<@)DtEdkK&bsH:TC9gB' b%:]fk eP>1\|5RfgzdT%gjh`1&AFk) hD>*^@*^U_i ^vږ\W*5]vUd'[zJ봓V/[fa;fjg-נfJEj+k,lK 7f* qGVx1gb1pQnHOM_OLi.K 5yh&lYcs8 %9L2+=͝QeU\]}X͗VUi_ s~MN:ob6pznoM]}o}hZ51{*ޅ*k-Qއ+8k(ު@2+( bVbGu.W妋Ny7KTۏ79tY_A?k 6^cϵ}F]}wDqi FS(Ëɞߴ$vctnNjS#A.9ˁ+!BH `H8̡w@H@;junit4-r4.13.2/doc/cookstour/Image2.gif000066400000000000000000000046721401177727100176100ustar00rootroot00000000000000GIF89a,@H*\ȰÇ#JHŋ3jȱǏ CIɓ("HRʖ0c$2!.q@<YsD3*tiǦNJuŪ$X+WZzvزbӚ],۵oEKU~Ew^~+ -x$VE]LS]2ZC+<0ң=sVͨQNm3?ݶݧɾNȓ+_μr!W y:4#[w7 /L铑j,tz%/ +\Ͼ׽Pս_~t &F(VhfaZxQ9AvK'h%"D Ha(c)<@I7hؒJƤbh9I֓S6ԁ(%pK&vژY@VF&cj~&9cVus̙F衈&Z\oadCH,"i)~#Umi}o*D>F\f]Zވ k; 6F+VkfۨjR-J E{฿.DOP첺}/HT:|0H ;~r rV %Cp<Mʵq0,&NԲYyXk^_w&3lzEtc"ugf'jz֜֙5yu}N".ZY*jfzqHK3m#VWM\]W}kv٩G+)"3'wrJ9YjktoXyܼK%;nidMOzeFfGjjz=ۭz/o H^ YLsdر3rTґEE b$TTAn'I{ (]*W 78/qP0a 9H0 hۏzB谈1Dt5%O_;ĉL$W_KEuq[U(Fy0xZ~63ťcH!phx#8qyd)@B*"G R!E,򒐄4){yI5oq$ F~1FO 4R,JSڔ2+$7B J$hˤ5S DT]3= $ &9)(R5aӦٚiaK;i4ɞF 05><\<~~3f?M CyѳER&JУ写Kin43 C͓l)6ڣFIԢ:=RԦ:uq̀JXͪVգqJdϺJֲլ}hs#g\U~֣!xB=B Wv/wym4Rv]r[;㱊LYS_T_hYqgi DszNa@'RZS[ah*.ͭnY ҂NsmXl0V-55mtre%lc:XFw!o%r>7}-q8?=ۃ\pRԹU`5WM_y˳M0t+7{ GLZ;junit4-r4.13.2/doc/cookstour/Image3.gif000066400000000000000000000056021401177727100176030ustar00rootroot00000000000000GIF89aE,E@H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗$P&͛8sO>jshСT:ϓOuJ2*UVj1+ת1f*!ٲ%ώe(ХmV)ݤE]H߿ LaHy 4Φ#+~8reƓ%CmE8ҡS=xQO3_^ٲK9${Ɖ#_{}^tֳޮ;wY|vSܷ@߃-| W_|7`~&_} oE%Z݆qa ~(b RșeI&-X+p4bZ\ը<@)DiH&L6$EE)TVyؓXx_ٌY6Zlz1%\f:ך8y=!IVwAjbgRcs~_P"OxN^(\hhXgF^eQifl娞vzggKզ*X8D$"u$hl[[IכWT` ˟˟[Y:T6lu͆X0tFJkvv/h5hf;20,4l8<@-DmtY.ѷݼ4,5Vڗɚs B>=dg3iv@rmdh*5\o]Jr~<ƹkiHR]{]l(!1>\%v:!^5.wH{ٳLqT(N|qm]5萣Ѓ }8qNݱB=#!Ro]7ܽ=߷?~>Uב݇arN?| v-V֡#Ru:  )p^zPJ(. ^V e0( וsUkC]JdNE/B"ik(Ɗf_6]]2W|#FMIȂa!?HRhCmp!RG;fRN$(&RL*WV򕰌,gIZ̥.w^ 0ILLz %2IedZ.A%Fs1?mufCmnO^4NQ8Murg"1]R G&}l&B ̅2T1#Y E=ٷd A!лnf~3)&:R%H.Yh(ݧ8y29zXHzS I:ݒy״'9ES1)渶eu[6ǖIA5RMVIt+]%7:ΫrPVJ!.];=ۊԗZer-\7}骓 IeW]5V4SUMcmij}vIdcRTf kZ^5m{}e:rUA\ ik(dn@ =no(;F^.r0M$` cAAJpYꅯ|_l$kGYEV 28pCvdﵯ VF0`FnHnc1 -z7 /N=2Dˁf0|w t?+FEDIt.[֗$8r 0(U@:@s|Lg!Á̮Byx3L8)f+_b07p|7? U(drtil5+ BmNzѩF t-zՊ. J EaAF1w`{,`΂e?涺gYq53c}o~;Ƿ -Aڷ\.p?[F%N!fKpI<&gO9vT^򕻼0GesbMdMݴŭ-?ri.C.E-Ao:-uwҲĺuޥzQNhOpZ@;junit4-r4.13.2/doc/cookstour/Image4.gif000066400000000000000000000071561401177727100176120ustar00rootroot00000000000000GIF89a,@H*\ȰÇ#JHŋ3jȱǏ CIɓ(E"Hɒʖ0c|M6s9Ц@uSh˛2*tӠOJMtӪV&ŪU&׮`O~gO Ylƅ[-\aWl߿&}[Pr. EƎgF!v3Vʠ1zq4o\˚nWv}3IӨO-q7oʇ Nȓ \uX$H }uձS>=s~]uc'>|o\pkK|zy@ؠ 8{=!o-gb(b,_4&c8&X4GT!"z&=9VZ9Eݕ @.FYeEHQ7am"ݑ THbb Ng{g|I栂B)|*YC馜v駠*ꨤ(t5P?jawĥ{i5W뮼+찢;+1VDCױ;,ZDmsV;Qq-Dоljne.acy.KFf1kB%gEpiY&/(-S\qCY7ށeRL,CY˔{il؟>见Ik. 2j(](&э(A~zi0Gs[g.uc-vY \JͶU6r E*|7~Zƃ5b!'Rx^;q7+3H3Z84 Q+hLt+b> {}n{*ҬY+ƀ4V0][w 3G/Wog/U?,_k,b8*?[6ER ӟmVr$ ׺כfc*٥)*޹b.2@PX S~?!6dzx+( aZVbģ8i! wFiQ+L!A1 NUXƫq߳ƙbfVFb H5Bыȳ ^2 c%PTS\&dgZT串l"bN f/u[%&]Mu,ӆ UKM?Kʖb*4!yhi{iuNSB<'t'HOgLO A:։D;OlM>f:Ohs ysW_A/Iґg2C%Rt=0MZL[:ӗ4ũMsӝ4GdT*T?R]Yȥ 9Nm]T8;VժW#VzT3FM*19Ӭg,GUj f[KJWɕEϫISH5>O39m ,7ω.gšǚXr:rJk-28r +YlwVŭXoKzթ5$><_jAw7Uz,ͪvz xKMz^ ZVE}qY)߰ ׽e@IR14DtC&14p`S\ r!77ʴnf*8ʥN5j:5]Z֢Ng̲ xε98zIftb'^԰6[wej'rT{ޯ6 ]mf| dl `Y?wcK6r;-%JDK5x3X wvy2GW P9@Gι=+ZyKdՓџuHC,/ȋ,MƄ|.9yהTؓwT]x_(nw2E\iYʛ]B(Ϲ˪RΘ9z?Uҷ\yEwy|Dy#;De_'>b368Mh%v]|3LUcY?謉YűWP{ =y?O58E%nmhLx\"3)MM8Drrc JѣHo]`iDIB@AUVb*`f Kvزhn5 YZ];jݵQ9`SMJ <K*ЮW!/dɔ/[Jgg<6iϛQk^}:t֬Mfo\  N|x]ȓԭ"УK>9ũt!СOӫ_Ͼ㗧N_9sݯWaw!w5PwF&Xᅈav!"X(zHb,>b0b4XG:R=*ȣaBIdHLP86H%V^颖3ee^~Pb^DfhyTWŵipŔJxCwBp%Z[rmYWɒpqFjDq7ގNyynwJy2Ȕ9ؗ)K}1V*무@+d)RYWX}"ZYnu,Eqb-т+~+Wv-rGgnm9/_tv ɟ:i?Z߿&pB'6 GHKg2oGY{ Ǭ)\1O@-DmH'L7PG-TWmu \7]_ܴd%mؒ]Mc]u[UMXyA|Fm[o8Vnef)ކo9;j_Kys .;q~oGp/K,ꦯ]춭}|qCk]؃܇|}O=~;}~'z=1GzYӊ pe*)c ۪s e~ϒmJIrIrW@#-5$HqP13]Nw, Q@1sʡwHX[4"惱I[gbU7d4z^h~ɢE j[HrUч%jD?w95nJx.SdF$!u*fce^ÚGڈdFG2/RHjAЀILSkĩDKzɴSbDu ʚ.R-*zԞ!g@תֶvj\Ň(ʫWկ}k`*X%bX•&Id+ɞY{EB́a %i֜X< Jf4-{#*n70|]n>qNb1oHJ(O'2 S%7y/ejyU›SX_c^3*T1zLq 5LʍX13V'&XwZT:gn&A:h~WG4<mrUf xGHArA 2ϦOm&ѽre UQ. Wņ1.V\BК7=#?ܪ&8iK1x]}otHP D]@M`a:#M`[ek6O8*p|י^酴!l}Ǚ?p1uM\/uiJ+I8˃[bG/Ϲma~Z$րo`AwXAk;B縇D#7T7]#"H]qk;f#l,uEYwd[cxn9GWɬ_l|5IShGOқOWֻgOϽweu!b:2vU\_q:gumM{k:Oߝ~qqE&1~XBV5{q*q2l}rlb,0(X}XׇPm#i{")6,G%h,.y%XSW(.XX^b{X$LrH!#U-JdI&mHgugKVsVCETM(CI!fmf=@\hSfnMHIhU7h7&SiXIk8g؅>BrvvxRRM$SBt8X*xn{|phhрGX9hX&hȇgcצ~(wa7N(xƘȌ5h&׈`ָӍ4ٸqaH3Ĥi4@F);v`W^"7rqr,Grڵt2G/CsBv_;bYPw['Vt@;ut!)s Ci-x\ yĒɇsw呫8b$qweP䤔OÔCc &RYezh 7_mij 7ۄc8^ v^z9!|UCb'5NYzE3ebf<%Y%9zy%9uId|LXƕSfo BUfn՚ qI׉gaCP "Q}cSUAbٗ٣wVril|Ne8JAU-fٕSG/f)?xB?#W؈(Qew蝹@ e0hiҟf@(%k#(Ƞ8yTY h6eh# %Aw7r@"Cgvz+ZP:(t1ZiM7ש]ȣ+iuyɡf f!zy urZoҏ:I49Tp˷Eg:4HwuJZ50kJxuK:9t6;{-sx 1jsag6=tjJ&ɺ1v7:7[VkSg;[KX[${u h=F*ktIv߫cM4m59yic+Gt%k[(G;鋿 c!aKʽ>(ZIW:zZ?fxKL x˕,nteZ׹)x" [v! qn[,|¹e[}kywE|{@\v,JlI<~JOZ&i*`Zі˲&ۂ 㶨 b Nȓ+_μУ-"aճk%uOzGАJo/ZW.ǸU\* FsIN'Ao$E4bUK5Uf̤ _`FGIweP/ Cq\ ;\91_GWWVbr7t̯ 2EhD6zэpcz&:Fk<񏀤BRt ! "EāV2'>IF+KqM &&Ld3 L#)VNV^n#2bcU0s!%44MTș6nz 8IrJ4:d4s`$I$==u;ZԠNA)\!Wc B;/T^cX.Q_ }?Fzʕ.sҕڒ#-) ӚhSaZ,s@ PJTڴ@Ȅ2PfK&@浗G%ȉլzUq]*ºM|g]ZggVouw\ JWEuv+^( `D1pM &֧tl"Z͢綃Z/W˜SNB\Оt\ ?10a(jjv8$̲U.S3\$t)DR(|Knƥ])πbH?h^z6=k_OgD['ٕ%H}-7T`d00Qyw9eigzJ׸ID(%JVmaFB"z0`gR5jE&3-16\Dn<gա -`ꦼ)*KXe.[>RLޡ+fA^&wmtT{iE~$t)q; A5xVOLa.3'tcS ʰ.Tr U8G'@;ȸRWI\6A>DgG)pDżoEVRj(yfkTeVJKm;ޅ-_z6&=`سI{pX3iTm2J]v* |߻oVnӒؤ-*]2 ,`8CRZ ׸3q)[,Y\[xM]Ο.ثЇkr_"h(Y>u1)C`GNŖr:nPsC܍]pGpm3^SH)<w=B5 ujV*bUj|= Ƴ{WE(x1L{hG-wOO4nn{1{kO A81:|I?L n_HJGEUDkG$s?Xzg>Bz.s0fb26pUs:Er(<\61}J^=t+!'BzXyBq5uRet(vH(waׄN+DXtVx!l&pZXv*zv]#zrcdR6b2q2SUmV~${h\ako&{\{fVcxk7b6NtX88 xY\刈vd(8g(||EP8*G؊䊸f5|E(vu勿8ShMh^}mا}co~F"\HfFRYRjxwuErH>ܷ3suZpGEj1TtKvfAv'X] "moeji>ŦJ1Q+VHI8ҕ\ʥJTwFiiz"Uǵ,dpP-D?ɖy)'z1Hq*qoX\WsL(kD`⧒5]׉'pI+QJu;5 /fIºh9>>9teȘ';t+&JM#gTUǹMMv5VgG{ŁQPJ`M[hjlnprICNF,H[哌9X'\晥Rp̪p> r> ~ zZwnt.n~߷nNyLP.Մ_.͖^rc:{ZmuJdk^njʕEy֯nE, C^訬ߜ.]-aWua.^{.B1^r>Bn&~yj.N='B)) XY]΢6j8d]SRڂel'oҘ{amBNyu;T_r*XM*:O>GP FE w=Bt)/{2؜>!?,fV x ߒdb^B\MW_(O3]z?mȟis榿4ٵ|ݘ.̺oH6M}>_ƿpd vGRAb|.Oh9@Ik˜d@H I@@ DPB "P@C-^(bF= d H$E<92ʕ*KTR̖"]e͚8}DPE 51Rj| ԦQ^u$˟!s 5fL $ tٵceU ؟m5h#D}'b#Ry,ܑo%PƇ-YV# 9mسm~+: Z{VM0hE̲mKVܛ 7$^49߀6,5_Ǟ}sKgi=t絨Ǘwgwޫ  J]υmKh9#@s? 4@-ʺ.DL`#-EpK\­4XoF n!>LjB r#,2B* (G38Sgc6R---M3Qt +1AT5,TP;PI#K2CG,),QLOB+TDROkTUQMUVMպ$Sc4)[CUW,,XwYeevYgFu5vQrZZV@6ܢ%YsE\8]3znAWbK"__&68aX>9sJ^+NZw+B~y矿 zj^9{76d~|8}g}O[''4ٶ|vFD(=+E_ȤVu? "ɫҵAuq'Y*x1O/kVrժ b:b!Nbݰ/!a<)f9#lV %mUf.w ;+Ұ. sXj'H$YK\!WF2ΰT\,aYdR8"vqrg0.2VZDR'7Dc8#ፎYb+2ٳ뜣yDqb"HTTpeOr'[e&i9Ζlc-iY:6-v{g2 UY)gL(jb `44Ac HlX p5i5QR8)Jәq AOZ4t*K CTժW*+Uvի_H Ք&F)XպVխ\XCW-[W.uU XnE yΰlaZC~lf5Eֳ'B'VTGXe *4he*ˌ%#>VMjK%еgmjUZ7%n?O1\-m[Ҷb.Ke䣬MdO:˶w;UD!K_޷hziREa sMԍmE95NpthƤ%IVR]׃ OҹTtQi=6K7gB=el,B6MLY2FLL,5m;%MP6Ӛ9ю|QgܧZe=;t@̞[=]ܨ72 x$Md3)ɑgRdM}㌬2́&AQUM:3CmuڸqEdZIdkTըJUXNySVF)PdXU鷋r{k\L?'GMbI4zz {bf2Nٚ_NS~{+uE>*Ӊ;Bz nA"E>r.Bvqw'RUrW+֗9o>tN(/Cv5O_z!&uSGzYw]zY,golѾvTm{vcRx~3|!._0!?y ~|Өyw^}-zҗ{G}Izַ>z}%{~ǽ=~?|?L'~5Eq7w~/Q_[_>ܭz[>kLj Wݗ_Oxmoqzu3f$Bs1 @jzO[ /谜1l@ Os@?2} |˴YKDcCE|6F L$9JĿNECbPDE++ULWyxbc#F9aefKUŠCv3ӨS^} Y˞z#lȣs}tߨ-N&㪅#_q9sУ-kb7],cn]矦W^׷)_{y׭O_u }iV\ w w`LV\b U!_RR`V!Z!U`#bT'/6(4h8<@)Di$O $J6L2٤QNieNVQV%mcfif\gIR \zeWjʄ&eI%li'~Z'S'N6ꨞWbBt* \@&Ijڪ VdZyj`j*I쯻1[ҚQ6e^:ezK-_j[jZroVluz,{&;yC 2> ?gCGM(SVWuR/[dmhlpqqm4(RxzS7F%NG&CG^my8ބƉ霑謓:{[c6{onGW.VCY3>=pav N~Oͷ@4|sP>MP@Iy GHYڵH0lBÈ V)m N"D%J`_HDbE ؕʉSC,6 f:˰-bYZ(ç]Y$@|gLUp Hr3-dio|W˺s*hstIt=~!רdiܙ΂/ʍq!(Ƥ}4$I-Rߢb"kh2R f K%򈋼#\%3"`,<st[!qStxGJ e#Y6FPᐓg1 J)k:ui6k?C:9=r(1s>ifc٩w-hJъZͨF7юz HGJҒ& JWR񩴥0-)R4w/Mw Қ@OԢnt3R+-#TǑBK^UY56[XUfcMhʠբiJo[\srsukRz½1KX&`el_*X6bVm%kA~l,IK?Ȟ=hMRvHl #z |[ք kFmY.\Aׁ]qGx]ݪVBw\VFr^ƼQ/Y սzdJ_<6\k>kEr PA/¡y  4X;1HTUA1ad] ĭ\@L"HNy7Q*Qґ 9e-ybXlMU~&5bVH:5gMϵ$fL3vΐLÆ QRh6عϓFfMPOT^9K7rVNzd575ć1|Ƶ^O4YY3Le:_oly{[j]H]YΘ >9I/THjU՚=opvRd6ݬpW.00[xi|zӀhO|ݥd ͎Lq ,O^xO6by3Zi{,De]I/ol\0GS{޸>A]gx?J?gz]zVc4wj+a\wB#t̨9=@<';|}jn}=۩jN{OGZA|7O^cǖ5E7nT5o{_>/ͪ9%^ͮxeKgCi%JoG?YUr3thO џZg_y3y[-=7JrD/:g~(wtk7KZgx(owo X|˧|ȁ'| X$x=~&؁+8,h|284X6x8:<؃>@B8DXFxH0Lxc6քPKTXcS^QZaO7[cd`E`e؃KiXm\\rX/!_lhEz؇*~\X^aޕb؈X%y5eemȉ艛U(dhiHcA f\́#a_!Յ 3`SRhWƈ8>X3Q?XxUWwh؎%(EXWaH > yht(Dc9hƑ(9XS `_+Y9\.2IT-)($yI69; A4 [GaE= PQoxV1Cؔ^`Od99Y*r5#lɒiIr9ab9sx1vz) kA[Xi]iu Qpi6ًYyb9c\ycH?YZ2J)m)`4ٙ_ ^Vٗ9Rُy~9x$51ɗ&q ҩW)ə5`9[Y\I i剞bY)i)^ɓX[@9ՙ JjI٩j a Jb YJʞʠ'JJ) !*#1aX/7 3 =z`ߩ=C*AڝJLڤNPR:TZVzXZ\ڥ^`ڝO/ e.ZB0j:k:fpڦiJxgPtʀ}&rq:wlgCwq~x!qӦC)f[nڨƤ:P@䩑:B*Qrjvǩw&1AfC0h*hb)TB L*wrA(5lsyؤ*Rdpj}{zgfʬ tJj ÚZ:I0"0vǭ{Jj111W/ u'rg/ʮRDs3~l]G)g;sb(C-+kZ_NRMy+ y kwF0ۧlZHgj:tBw|MG2G3iOP+1qm227'm+t-)8v˱o]dHFOo{;tlg3_gt}B~۵.1ktCF~;rv1Kf$[|rbm [۸po}a,[&Jlj;pu}{o_W$C~gf<˹wp[[vu'ku~K;xt K;g GpkSðKIz&Kokt컹ڹEѫ ̽zEeGmK},+J{ow9,E:'>B,yJFܰë-QsfMf<簥gX Z%q1$+Aw+(e*ÎjGPL@,Ċh|\mS CZUɣ*'gQdww!g6ʣFʫ71ǤTo JUnit: A Cooks 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 doesnt 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 arent 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 dont 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 isnt sufficient for testing. Telling me that your program works now doesnt help me, because it doesnt assure me that your program will work one minute from now after I integrate, and it doesnt 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 developers 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 isnt 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 wouldnt 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 cant 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 algorithms 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 didnt 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 wouldnt have to write them. Tests are interesting when they fail, especially if we didnt expect them to fail. Whats 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 doesnt 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 dont 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 methods name. We can use this feature to implement a pluggable selector in Java. As an aside, we usually dont 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 Dont 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 doesnt 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 cooks 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, lets 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 couldnt 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. junit4-r4.13.2/doc/markdown.sh000066400000000000000000000000731401177727100161320ustar00rootroot00000000000000~/bin/Markdown.pl ReleaseNotes4.8.txt >ReleaseNotes4.8.htmljunit4-r4.13.2/doc/testinfected/000077500000000000000000000000001401177727100164355ustar00rootroot00000000000000junit4-r4.13.2/doc/testinfected/IMG00001.GIF000066400000000000000000000144321401177727100177650ustar00rootroot00000000000000GIF89a6@ @ @@@@@``@``@@@@ @ @ @ @@ @ @ ` `@ ` ` @ @ @ @ @@@@@@ @ @@ @ @@@@@@@@@@`@`@@`@`@@@@@@@@@@@@@@@@@@@@``@``` ` @` ` `@`@@`@`@````@``````@````@````@````@``@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@!,6 H*\ȰÇ#JHŋ3jܨmBIɓ(S\ɲ˗0cʜI͛8s#H[@ JѣH*]ʴӧPJJիXV֯`ÊKٳhri+۷pʝKݻx˷߿ L6@IpA,˘3k̹|dd^ͺװ5@nEwz;dGN?2\ܶ=sZ྅ $atC"OJ}{ѥwع[+>p~whށ&zIރ={BQ8}֘~q 蘀 #Ɨ "`QDآ^(uoq_@^%~G"PQ/PPiLaޙs9`hhݏkQiy5z0ʘWI!rv1ʦi饖MiTC][ !YZJfJ&͉*j`i~:afhߛ!gRsNNV[`*,VKBVlҚv+:`\{XJ*k;zz7ߍHwn"lvwܱG̱sz,sn͜-K/wDmt_BL7PG=RWmXg58n`-]mhSepǍurmxcEw|{-x'xԇ/㐃ԕn]#5y35F~_gκS#c^Fz4N:V:o<̧ީ i+:~:Л?߻Zϭ??>.u_7:)P~ l'/;UP~d` |A9p~`1H児۠٣ gBrp4/ nЁ+ PzU_8D0[H/H@6bx7vqpK`iІZc =Y3|G_{!X;mr̤&Mzi$(GIʭLNV,|,gyXl-s^.싾 0L.L2f:Ќ4IjF1^ Nl׸ 8IrL:yNd#鉋)*m̧>Osk 7驛~MBuO݋O֋(D'*ъR$&tEz A5D,A3$Җ0m Iд(hPѐ&MLJ~j&NwzԂ="6XISeCt(5ݡ rӁɚ%XVsڢ˵`]{ ,xƱ Ko⽎n 0ʖN/Ή#{|Ҧ-gFHzr~*& 4aSϺs.|*w4ßCr*fڮlѿY/q3/oj??@bM7WB$0ؠBRXbrءRוz$p+آ/3X7☣;أ?XU'YG"K2dBVESRYWbPR%_cf%q *"k٦ohT^Yw≤Qљ{:է"hfBj*2(SRh)E2)ꑨꡧJjGZu'z.:"엹I*F2`-i-DNA {mr.8{бF4{.11" ˭[ܰ)PkPmCk˱ɶzl <2|̥z\ ~w'9vE D(`6<3F)P4̙v| H|Y9`sz㜊 oB!qv̘J҇~sr!OMs4x&$Τ}Hlu&Ѕ\TM_Lp&Tb \I0}la"{++pbYA8)Y)*QD-^ĘQF3OG%MDRJ-[9L5męSC#wTP6{,TRMuUTU-BUVEvVX_ɞEVmAkݾ+m\u{W^eCXy F B隃9dq'0Sq?n 0;tk1ȔBH#/"H%l(I&')Ē+䒾-/$ӱ1D0`M7߄3N9礳N;3O=O?4PAd05C4QEeQG4RI'RK/4SM70'TQG%TSOE5UUWeUW_5VYgV[ouSCd&\6Xa%XcUW@EYg6Zi-U٪6[mh ׅ|\sE7QMN\U7^yXvr7!x_+l&`7faMةbW/3fjcG&`}KfyOVJdgBMkghaNJf&ޛ٠fY*iBrjaZǥj65&hivZlFmmn;o ooɖk/YpFqE·~p/m6s?=t?WiP(u{?~goM/ly^'?~ /}tr義Ђ"va>PyD2h:Ё{adЄLa:Li^g(CHPz,uV-@ :цcbiA7QQ2{%Ģ Hc 7D&285U+Ilg`AmSaC!F8bE1fԸcGA^hm$QT%I,2fH7qԹgOG4ْhQ/i& OOF:jå$պ Jg2MXlYgNZM[oƕ;\Ie~Mo_-paÇ'Vx^]G<\1gn2A=ZagͧQs3iׯa56Wzcֽڿ˛xq}W,ϡCOãgמ{zn?^tw3'_kGٺ}}RO}]6  ,LPl!Ы( - 5= E,\M?s)Eb2FqQyB'Qk+߄$R% nB{),?//Ĭ*,3r0+)*(I6鬓=!3R3JTQA-H9%K3 UTN'RuRNtS2 QieSqEWUWeZ5-tVO{S`O]T^M/~%6Zi]fu?l_5kMem)+r\l˭yWmE7uU߅%1%X^bθaNz I.QNYYɍaxcpYy矁瘉fmn駡Zꩩ+F)˽X.{N[V;YM\ wǻޖ!\)1WI{I0>뜞|p}E(T+9%1C/|[=@/Qw` 텯W \`+_KGkx_! 5ABP S?|! ]ZJ8|aǹ/;T h{5t! DNOQ(Abш9>xB/qIXdXDn H@po"/b+U\hiϏģ!4r\$)=)y u}Lcb8ޑd(1yJFN҃BԊ5x2nRq$,'@)fЎ}< ^0mt#YJZҘd LiZll {xZ.Qa&]p~whށ&zIރ={BQ8}֘~q 蘀 #Ɨ "`QDآ^(uoq_@^%~G"PQ/PPiLaޙs9`hhݏkQiy5z0ʘWI!rv1ʦi饖MiTC][ !YZJfJ&͉*j`i~:afhߛ!gRsNNV[`*,VKBVlҚv+:`\{XJ*k;zz7ߍHwn"lvwܱG̱sz,sn͜-K/wDmt_BL7PG=RWmXg58n`-]mhSepǍurmxcEw|{-x'xԇ/㐃ԕn]#5y35F~_gκS#c^Fz4N:V:o<̧ީ i+:~:Л?߻Zϭ??>.u_7:)P~ l'/;UP~d` |A9p~`1H児۠٣ gBrp4/ nЁ+ PzU_8D0[H/H@6bx7vqpK`iІZc =Y3|G_{!X;mr̤&Mzi$(GIʭLNV,|,gyXl-s^.싾 0L.L2f:Ќ4IjF1^ Nl׸ 8IrL:yNd#鉋)*m̧>Osk 7驛~MBuOti$&tEZͨA*-"h4JҒ-(<RtCIEC2Sk6(ͩNҫT-/eZQس,ANԚ4)4**.SGjҴ^G*VU$5mHZV6pUVrUF֏)UނUdb `kVug=aظ:'h ʩjEXאSi`&5mI ־8[+EQ(yE8%i AkXYK^h =5%8$mE[l%,qKMs׻SK Pwc ^vEq_8=}|gasaįZ[^I2]ζ .YEn \ر$P)dTHLK7NzZ^ūL*ۄM*촬V_U,^-[6N;3,R7pnɒzMB 5=2#ΐv3Ii44-wNӞ5(A-RgԦN5 ml,h „ 2l!Ĉ'Rh"ƌ7r옱 =,i$ʔ*Wlȁ.gҬi&Μ:'РBSfѤJ2mJӨRRj*CZZ+ؙX0X6,ڴj 铬Yen5;W-\ 7/k,޼t&1Ɛ Sly["8g_.mrf'nbҰOӮ6hͬ?/;§⎫z7ޑAC=9n-b;9o7oᄄO>t (txx.D : J8!Zx!j!z!!!u]G8)"-"18#5x#9#=#%Zu"Ey$I*$M(dUD:9%UZy%Y%URj%a9f\B(&mfJ%uy'Hy'S} z(I~h&J:)2e(j)RIrz*z:Ѩ(B:+*QC+~',Ɏ9,ŚtJ[%:[jFQܚ{nBP;*ۢ>k)"D0;D$1+pCx)1rjBS\Zl%r3̩38 -3ӳm3ADp-4֪f$AROo=5٩>}m^ Y6Zom,6U}7 >8~8+8;8KFrr YrB0Ry?CvWD魻zy.`_ /_^+];\KoZ[OYkV{mKFŞDõM}uƕ^9tG;QY?.w c," v#AL!# K@ͤ51zRh ѧB p#Ck(}q QRA7IDob~A]ڲș[f9h۵EMΛ_&[wSW'ͼ`/Gճ8TWcn{_.oiT9B_;ހ}>R a^~݄-C'V\7]s",$f*gMX vfV|-RhBiED %PdT9eXxe\ҷe`ed:6fhYlp)tix|矀*( fx&袌6裐F*餔Vj饘fա*ꨤjꩨꪬ꫰*무j뭮zj +k챳j6F+*[d--ߊږkz;қn v mSWؾ.,* ꮸ믩BL.+k2lmx.|q6/1 L4O7lr+'ײB/wsrPT GLߨ/Nӄ?Noyފ~{3N;G0E~ˮZ7\n{K_{?;k >ߚ>u/|旳٘'玾çKUڧ= uMl]>ɏ~\9mx[8?0~ˠ6:wΓY w/p[lH#_Sh|]4jX*6CZ {K!ט8-krW'zc&D0Z(GgXVl 5>rڣRXF:򑐌Cm̤&7Nz (GIRL*)>&,gIZ%)Y,$ 0Ibe\`"Ќ4YLe Œ̦6nnϚA7Irs8vJO zДIX -z Mh' ~Jə D#2n顾dD'ю޳HGJҒ(-)HzPz0='HyQ8Lo@Py_fsͩRZ D$IQ5zT&Xj-wLUUJֲr}IM[:Vj 5l+\WD*ULs-#E%jCYJ~e_+d'ͤ,\fU=+SU]ig{ZBHO!"XV nNQܺg yQG{Y:>Y–.G{#Mo[j.N[X.MKUlg`AmSaC!F8bE1fԸcGA^hmTeKDhr`˙!qԹgO?n$GQ&ETiSOڊi3P7fպkW_Z%YeYf^ZS-XoƕUl6wջo_|SR)3\Ç'V-I!G:αzwޯg_?mǗz}{׿p}񃏿 ˿ p%i! ) 1P 9Lim!Q" Dn"{$15#TS7dtO=ųK1qSsTRW<YCFGYMPXQԂ"a Z=Usز҄YavKYVZq}=W7UKuscSuJ7s6{ö]veQUt]`W~ex)N_Θĉ+ۇǭXٌd`|=f$|YiqYg<猷y{[裑NZ饙n駛YꅗWӖAZ뭹[챹\L[mDx[nܞn;ռot[ 2O\q_!W)<-\[A]I/O751o%a]iq]61-.'tBor%e^uuȡGų/v@w%eiH[2}7w(Xcߖg?X,;UP%9Ū ā(A B0 9ATUw`,  ł!zC, IC#Lb _8,D%TJ#ρAd%1d$#hF(QBtcTq`dH1K wHB(F>fІptA+1٢YH/R,$ CM1T# ILna%=GEr$J\*r,-Q 'URp$ULLrHl ?SfSCjL=6|T7IaRdb#3|:DϢٓ§~_2BPXԴPnRz<{QnG3:,I9T*eKRts2M)gStq:O SoB%QfT.mSUNUUIm]WVUk3Yњ;junit4-r4.13.2/doc/testinfected/IMG00003.GIF000066400000000000000000000135501401177727100177670ustar00rootroot00000000000000GIF89a @ @ @@@@@``@``@@@@ @ @ @ @@ @ @ ` `@ ` ` @ @ @ @ @@@@@@ @ @@ @ @@@@@@@@@@`@`@@`@`@@@@@@@@@@@@@@@@@@@@``@``` ` @` ` `@`@@`@`@````@``````@````@````@````@``@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@!,  H*\ȰÇ#JHŋ3jȱǏɓ(S\ɲ˗0cʜI͛8sɳϟ@ F$I[H*]ʴӧPJJիXjʵׯ`ÊK֢#]˶۷pʝKݮh ߿ LÈ+^̸ǐ#KL˘3/FW)'zIͨS^ͺװc˞Q|Q6 N1E&G_i27mZtسkν wa:K}:~;.98߯xԼ ږ6^ӕ^o!'!{EXe_T(!%R'}vZ`ƈᄈG$SC"YbR*u^m,2HaQ%tby%_&e|Jcj衫ԙKG nv4'{N _}qjd6(D"fI9zYN8 ka2*jbjκ}kkbdž+nm l(knjV;jz:Hc#j:J^Kb)W n ®sD$lc,,R0p1|xV<3_ -t@-b7O?7ӲI TW we\w`bmhZp-tvx|߀.uw'G.ڎOngVw砛4n騧ꬷ.n{-o'7G/WozޢCu/o==@o>/oRQ+ H<_1'H [ڇAD9IB'9KDĒ6,, Mx07DɀDCȇ??ЈD! whD%3ԉ }(RQKa#Xb-O™o `˨'qe<h;QgTDARqL#P9H::" ߉\&C-Na x?"$b wQ e*[YHZVё&u)HR\fA ?ҏN\f&ge3yLҚה0OYYrtf.)(]ҁf8YH;2D$2 Ov^9>QNeJҔ?jP>6ԛL>I(.󛉬'? ̀Ft(4ѓVad&ϙЌ\g2IcRӥ0iK Ln̦:sL󧳼iHsGVJt3hcF.ԨiFGʑ6Le fsԔNMk9Rvħ-9ymzҗ4? bխjVjRXNL(.ؿs]C#GBդIXJ=/UyWzv%NkZӪVBe!YZUlINBMjڤ6K)[ UmwQԵ=dMyVwiqңlTFUjj[L*1`K[eŮAڵgwc_SuL2[J0ʽ6NU1_ Nt,GJؖp0- .i-&dB*>)ArI"%`3u|crflCu$YL:x̽<π ЈNɧ?O{'MJ[Z&\~!MF .ӌT Ƥ~wN %{Puj5!li^!ӳ2Lj_x1j][6C#L2/%c T/eykb[px P}Aky9ٚ+.}o%p@VЂfsܣst1}jzG -iU0Ta ԙ| _[ T+]Tw)aԘiN߄ȶ4? 6tbD *XqE)ZF&4$J*1v cK/At&I#qc͜3agK<{NtjTS 4x BX&Bc S(Z5]tۛoֵ -]y%J_98dқyu2`Ub#wy21ŋxE}4cJuiل3vbu&;eOJmzo{PөW偔3ozxɗ7yͳW^<)W+x޽;/@ J+;% -02>.E 3$H+绯K|e+۰iܑ}q?SGerqKjњ|,&|6$l'!!.G,I##tO˗,.7k7 <\H"I'{B =51AOH\NMC-%JA1uT7J:D/sISCTdX{N0TQA00 t 6+ػX/iӫ\}ZvŔ N0ljU|HZ"1]lD]g9lm5PjQkך_lWy-6^a̯L2CR+4,8muՔ+ 9QIWڏ\MUNW=Oh?EM%Z^Q#Ur_ gyi}i^*Nau`}^ȖNgFvn1w؍{ڬkY>o}5wnQ޻l^~V\-ۚM[HURL4N_u=yv׉EA>s]5\!+w{h$xWsߞɚ@/z볇_}?۟/x0@zⷢ $.R] дp-z: 8YJ'X5_Hn:ܜt79Md[#CH*V'J RZTy5.eR xMk4U:X8kbvE)Y_JԄ"͈B8lix*.97<WA:p'|ʑ7\ #G7qa^s9ysAЉ^,΋ml,h D!Ĉ'Rh"ƌ7r#Ȑ"G,*S\%̗/ND&Dp2t8p!>M-j(ҤJ2m:Rg̨2RU3hOy Ʉ` JpӴjײm-܆AҭjwUgRzЫ_yk0Ċ#Zݘf kM˖j1ТGv2xr6ksج%sҺw;lw'<;9MUmnެ3'ϩ(Ǔ//.zNq7o>_]E$w9 *z9ҁVD`wYEXj[=-۴q")-"18#5x#9#=#A 9d^ן45$QJ9%UZy%Yj%]z%a9&e j9w q9'uy'y'}' :(z(*(7`}H:)Zz)j)z):*z**q8+ + ;,X,*k:,-ZZj-Թ-Q{yz\ߢ.ԨvnNkًܱ 'kޭ>??W??(2| #( RT;junit4-r4.13.2/doc/testinfected/logo.gif000066400000000000000000000017041401177727100200660ustar00rootroot00000000000000GIF89a& ! ,&@HD#B(1 b(ѠE C,Ñ(KrHE/3tQI(mn̙Seŏ?<9TC'4h͖JD0hTX{N%!ή jҊ)wz'Χ3R-JnۥbE.W{;գU~D;q@;junit4-r4.13.2/doc/testinfected/testing.htm000066400000000000000000000753671401177727100206460ustar00rootroot00000000000000 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. Code which exercises the objects in the fixture.
  3. Code which verifies the result.
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 assertXXXX 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 overriding 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. define how to run a test suite.
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 implementation 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. Beck, K. Smalltalk Best Practice Patterns, Prentice Hall, 1996

    junit4-r4.13.2/epl-v10.html000066400000000000000000000305351401177727100152670ustar00rootroot00000000000000 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.

    junit4-r4.13.2/pom.xml000066400000000000000000000646121401177727100145350ustar00rootroot00000000000000 4.0.0 junit junit 4.13.2 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 team@junit.org https://github.com/junit-team/junit4/graphs/contributors developers 3.0.4 scm:git:git://github.com/junit-team/junit4.git scm:git:git@github.com:junit-team/junit4.git https://github.com/junit-team/junit4 r4.13.2 github https://github.com/junit-team/junit4/issues github https://github.com/junit-team/junit4/actions 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 1.4 2.6 2.10.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 ${enforcerPluginVersion} 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 ${javadocPluginVersion} ${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/ *.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 ${jarPluginVersion} false true junit 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 ${javadocPluginVersion} 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 java9 [1.9,12) 1.6 maven-javadoc-plugin 1.6 maven-javadoc-plugin 1.6 java12 [12,) 1.7 3.0.0-M3 3.2.0 3.2.0 maven-javadoc-plugin 1.7 false maven-compiler-plugin -Xdoclint:none maven-javadoc-plugin 1.7 false junit4-r4.13.2/src/000077500000000000000000000000001401177727100137765ustar00rootroot00000000000000junit4-r4.13.2/src/main/000077500000000000000000000000001401177727100147225ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/000077500000000000000000000000001401177727100156435ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/junit/000077500000000000000000000000001401177727100167745ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/junit/extensions/000077500000000000000000000000001401177727100211735ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/junit/extensions/ActiveTestSuite.java000066400000000000000000000033671401177727100251340ustar00rootroot00000000000000package 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 } } } public synchronized void runFinished() { fActiveTestDeathCount++; notifyAll(); } }junit4-r4.13.2/src/main/java/junit/extensions/RepeatedTest.java000066400000000000000000000015671401177727100244400ustar00rootroot00000000000000package 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)"; } }junit4-r4.13.2/src/main/java/junit/extensions/TestDecorator.java000066400000000000000000000016501401177727100246220ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/junit/extensions/TestSetup.java000066400000000000000000000020411401177727100237730ustar00rootroot00000000000000package 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 { } }junit4-r4.13.2/src/main/java/junit/extensions/package-info.java000066400000000000000000000001241401177727100243570ustar00rootroot00000000000000/** * Provides extended functionality for JUnit v3.x. */ package junit.extensions;junit4-r4.13.2/src/main/java/junit/framework/000077500000000000000000000000001401177727100207715ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/junit/framework/Assert.java000066400000000000000000000251101401177727100230740ustar00rootroot00000000000000package 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. */ 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 AssertionFailedError. */ public static 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. */ public static void assertFalse(String message, boolean condition) { assertTrue(message, !condition); } /** * Asserts that a condition is false. If it isn't it throws * an AssertionFailedError. */ public static void assertFalse(boolean condition) { assertFalse(null, condition); } /** * Fails a test with the given message. */ public static void fail(String message) { if (message == null) { throw new AssertionFailedError(); } throw new AssertionFailedError(message); } /** * Fails a test with no message. */ public static void fail() { fail(null); } /** * 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) { 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. */ public static void assertEquals(Object expected, Object actual) { assertEquals(null, expected, actual); } /** * Asserts that two Strings are equal. */ public static 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. */ public static 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. */ public static 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, Double.valueOf(expected), Double.valueOf(actual)); } } /** * 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) { 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. */ public static 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, Float.valueOf(expected), Float.valueOf(actual)); } } /** * 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) { assertEquals(null, 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) { assertEquals(message, Long.valueOf(expected), Long.valueOf(actual)); } /** * Asserts that two longs are equal. */ public static 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. */ public static void assertEquals(String message, boolean expected, boolean actual) { assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual)); } /** * Asserts that two booleans are equal. */ public static 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. */ public static void assertEquals(String message, byte expected, byte actual) { assertEquals(message, Byte.valueOf(expected), Byte.valueOf(actual)); } /** * Asserts that two bytes are equal. */ public static 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. */ public static void assertEquals(String message, char expected, char actual) { assertEquals(message, Character.valueOf(expected), Character.valueOf(actual)); } /** * Asserts that two chars are equal. */ public static 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. */ public static void assertEquals(String message, short expected, short actual) { assertEquals(message, Short.valueOf(expected), Short.valueOf(actual)); } /** * Asserts that two shorts are equal. */ public static 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. */ public static void assertEquals(String message, int expected, int actual) { assertEquals(message, Integer.valueOf(expected), Integer.valueOf(actual)); } /** * Asserts that two ints are equal. */ public static void assertEquals(int expected, int actual) { assertEquals(null, expected, actual); } /** * Asserts that an object isn't null. */ public static 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. */ public static 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 */ public static 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. */ public static 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. */ 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 AssertionFailedError is thrown. */ 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 AssertionFailedError is thrown with the * given message. */ public static 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. */ public static void assertNotSame(Object expected, Object actual) { assertNotSame(null, expected, actual); } public static void failSame(String message) { String formatted = (message != null) ? message + " " : ""; fail(formatted + "expected not same"); } public static void failNotSame(String message, Object expected, Object actual) { String formatted = (message != null) ? message + " " : ""; fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); } public static 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 + ">"; } } junit4-r4.13.2/src/main/java/junit/framework/AssertionFailedError.java000066400000000000000000000014641401177727100257270ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/junit/framework/ComparisonCompactor.java000066400000000000000000000051611401177727100256210ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/junit/framework/ComparisonFailure.java000066400000000000000000000026301401177727100252570ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/junit/framework/JUnit4TestAdapter.java000066400000000000000000000057541401177727100251250ustar00rootroot00000000000000package 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.Orderer; import org.junit.runner.manipulation.InvalidOrderingException; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Orderable; import org.junit.runner.manipulation.Sorter; /** * The JUnit4TestAdapter enables running JUnit-4-style tests using a JUnit-3-style test runner. * *

    To use it, add the following to a test class: *

          public static Test suite() {
            return new JUnit4TestAdapter(YourJUnit4TestClass.class);
          }
    
    */ public class JUnit4TestAdapter implements Test, Filterable, Orderable, 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); } /** * {@inheritDoc} * * @since 4.13 */ public void order(Orderer orderer) throws InvalidOrderingException { orderer.apply(fRunner); } }junit4-r4.13.2/src/main/java/junit/framework/JUnit4TestAdapterCache.java000066400000000000000000000047341401177727100260460ustar00rootroot00000000000000package 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; } } }junit4-r4.13.2/src/main/java/junit/framework/JUnit4TestCaseFacade.java000066400000000000000000000012731401177727100254740ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/junit/framework/Protectable.java000066400000000000000000000004121401177727100240750ustar00rootroot00000000000000package junit.framework; /** * A Protectable can be run and can throw a Throwable. * * @see TestResult */ public interface Protectable { /** * Run the following method protected. */ public abstract void protect() throws Throwable; } junit4-r4.13.2/src/main/java/junit/framework/Test.java000066400000000000000000000006171401177727100225570ustar00rootroot00000000000000package 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); }junit4-r4.13.2/src/main/java/junit/framework/TestCase.java000066400000000000000000000360161401177727100233550ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/junit/framework/TestFailure.java000066400000000000000000000031351401177727100240650ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/junit/framework/TestListener.java000066400000000000000000000007021401177727100242600ustar00rootroot00000000000000package 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); }junit4-r4.13.2/src/main/java/junit/framework/TestResult.java000066400000000000000000000111411401177727100237500ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/junit/framework/TestSuite.java000066400000000000000000000214651401177727100235750ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/junit/framework/package-info.java000066400000000000000000000001051401177727100241540ustar00rootroot00000000000000/** * Provides JUnit v3.x core classes. */ package junit.framework;junit4-r4.13.2/src/main/java/junit/runner/000077500000000000000000000000001401177727100203055ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/junit/runner/BaseTestRunner.java000066400000000000000000000230441401177727100240570ustar00rootroot00000000000000package 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) { } catch (SecurityException 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); } } junit4-r4.13.2/src/main/java/junit/runner/TestRunListener.java000066400000000000000000000011711401177727100242620ustar00rootroot00000000000000package 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*/ int STATUS_ERROR = 1; int STATUS_FAILURE = 2; void testRunStarted(String testSuiteName, int testCount); void testRunEnded(long elapsedTime); void testRunStopped(long elapsedTime); void testStarted(String testName); void testEnded(String testName); void testFailed(int status, String testName, String trace); } junit4-r4.13.2/src/main/java/junit/runner/Version.java000066400000000000000000000004421401177727100225750ustar00rootroot00000000000000package 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.2-SNAPSHOT"; } public static void main(String[] args) { System.out.println(id()); } } junit4-r4.13.2/src/main/java/junit/runner/Version.java.template000066400000000000000000000004341401177727100244100ustar00rootroot00000000000000package 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()); } } junit4-r4.13.2/src/main/java/junit/runner/package-info.java000066400000000000000000000001021401177727100234650ustar00rootroot00000000000000/** * Provides JUnit v3.x test runners. */ package junit.runner;junit4-r4.13.2/src/main/java/junit/textui/000077500000000000000000000000001401177727100203165ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/junit/textui/ResultPrinter.java000066400000000000000000000077411401177727100240140ustar00rootroot00000000000000package 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; } } } junit4-r4.13.2/src/main/java/junit/textui/TestRunner.java000066400000000000000000000133601401177727100232750ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/junit/textui/package-info.java000066400000000000000000000001321401177727100235010ustar00rootroot00000000000000/** * Provides JUnit v3.x command line based tool to run tests. */ package junit.textui;junit4-r4.13.2/src/main/java/org/000077500000000000000000000000001401177727100164325ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/000077500000000000000000000000001401177727100175635ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/After.java000066400000000000000000000024121401177727100214660ustar00rootroot00000000000000package 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 { } junit4-r4.13.2/src/main/java/org/junit/AfterClass.java000066400000000000000000000026401401177727100224570ustar00rootroot00000000000000package 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 { } junit4-r4.13.2/src/main/java/org/junit/Assert.java000066400000000000000000001172051401177727100216750ustar00rootroot00000000000000package 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, Float.valueOf(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 (equalsRegardingNull(expectedString, actualString)) { return formatted + "expected: " + formatClassAndValue(expected, expectedString) + " but was: " + formatClassAndValue(actual, actualString); } else { return formatted + "expected:<" + expectedString + "> but was:<" + actualString + ">"; } } private static String formatClass(Class value) { String className = value.getCanonicalName(); return className == null ? value.getName() : className; } 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 * @deprecated use {@code org.hamcrest.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 * @deprecated use {@code org.hamcrest.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, 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 assertThrows(Class expectedThrowable, ThrowingRunnable runnable) { return assertThrows(null, 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 message the identifying message for the {@link AssertionError} (null * okay) * @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 assertThrows(String message, Class expectedThrowable, ThrowingRunnable runnable) { try { runnable.run(); } catch (Throwable actualThrown) { if (expectedThrowable.isInstance(actualThrown)) { @SuppressWarnings("unchecked") T retVal = (T) actualThrown; return retVal; } else { String expected = formatClass(expectedThrowable); Class actualThrowable = actualThrown.getClass(); String actual = formatClass(actualThrowable); if (expected.equals(actual)) { // There must be multiple class loaders. Add the identity hash code so the message // doesn't say "expected: java.lang.String ..." expected += "@" + Integer.toHexString(System.identityHashCode(expectedThrowable)); actual += "@" + Integer.toHexString(System.identityHashCode(actualThrowable)); } String mismatchMessage = buildPrefix(message) + format("unexpected exception type thrown;", expected, actual); // The AssertionError(String, Throwable) ctor is only available on JDK7. AssertionError assertionError = new AssertionError(mismatchMessage); assertionError.initCause(actualThrown); throw assertionError; } } String notThrownMessage = buildPrefix(message) + String .format("expected %s to be thrown, but nothing was thrown", formatClass(expectedThrowable)); throw new AssertionError(notThrownMessage); } private static String buildPrefix(String message) { return message != null && message.length() != 0 ? message + ": " : ""; } } junit4-r4.13.2/src/main/java/org/junit/Assume.java000066400000000000000000000140261401177727100216660ustar00rootroot00000000000000package 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) { assumeThat(b, is(false)); } /** * 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 a {@code null} array or one or more {@code null} elements in {@code objects}, * the test will halt and be ignored. */ public static void assumeNotNull(Object... objects) { assumeThat(objects, notNullValue()); 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 */ 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 */ 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()); } } junit4-r4.13.2/src/main/java/org/junit/AssumptionViolatedException.java000066400000000000000000000026341401177727100261440ustar00rootroot00000000000000package 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. */ 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. */ 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 message, Throwable t) { super(message, t); } } junit4-r4.13.2/src/main/java/org/junit/Before.java000066400000000000000000000021361401177727100216320ustar00rootroot00000000000000package 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 { } junit4-r4.13.2/src/main/java/org/junit/BeforeClass.java000066400000000000000000000021431401177727100226160ustar00rootroot00000000000000package 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 { } junit4-r4.13.2/src/main/java/org/junit/ClassRule.java000066400000000000000000000076311401177727100223320ustar00rootroot00000000000000package 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 * after Rules defined by methods, i.e. the Statements returned by the former will * be executed around those returned by the latter. * *

    Usage

    *

    * 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}. * *

    Ordering

    *

    * You can use {@link #order()} if you want to have control over the order in * which the Rules are applied. * *

     * public class ThreeClassRules {
     *     @ClassRule(order = 0)
     *     public static LoggingRule outer = new LoggingRule("outer rule");
     *
     *     @ClassRule(order = 1)
     *     public static LoggingRule middle = new LoggingRule("middle rule");
     *
     *     @ClassRule(order = 2)
     *     public static LoggingRule inner = new LoggingRule("inner rule");
     *
     *     // ...
     * }
     * 
    * * @since 4.9 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface ClassRule { /** * Specifies the order in which rules are applied. The rules with a higher value are inner. * * @since 4.13 */ int order() default Rule.DEFAULT_ORDER; } junit4-r4.13.2/src/main/java/org/junit/ComparisonFailure.java000066400000000000000000000137001401177727100240510ustar00rootroot00000000000000package 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; } } } } junit4-r4.13.2/src/main/java/org/junit/FixMethodOrder.java000066400000000000000000000026421401177727100233150ustar00rootroot00000000000000package 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; } junit4-r4.13.2/src/main/java/org/junit/Ignore.java000066400000000000000000000026561401177727100216620ustar00rootroot00000000000000package 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 ""; } junit4-r4.13.2/src/main/java/org/junit/Rule.java000066400000000000000000000063561401177727100213470ustar00rootroot00000000000000package 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 methods first, then fields. * 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 * after Rules defined by methods, i.e. the Statements returned by the former will * be executed around those returned by the latter. * *

    Usage

    *

    * 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}. * *

    Ordering

    *

    * You can use {@link #order()} if you want to have control over the order in * which the Rules are applied. * *

     * public class ThreeRules {
     *     @Rule(order = 0)
     *     public LoggingRule outer = new LoggingRule("outer rule");
     *
     *     @Rule(order = 1)
     *     public LoggingRule middle = new LoggingRule("middle rule");
     *
     *     @Rule(order = 2)
     *     public LoggingRule inner = new LoggingRule("inner rule");
     *
     *     // ...
     * }
     * 
    * * @since 4.7 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Rule { int DEFAULT_ORDER = -1; /** * Specifies the order in which rules are applied. The rules with a higher value are inner. * * @since 4.13 */ int order() default DEFAULT_ORDER; } junit4-r4.13.2/src/main/java/org/junit/Test.java000066400000000000000000000114701401177727100213500ustar00rootroot00000000000000package org.junit; import org.junit.function.ThrowingRunnable; 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 for * exception testing and for limiting test execution time. * *

    Exception Testing

    *

    * The parameter 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);
     *    }
     * 
    * * Using the parameter expected for exception testing comes with * some limitations: only the exception's type can be checked and it is not * possible to precisely specify the code that throws the exception. Therefore * JUnit 4 has improved its support for exception testing with * {@link Assert#assertThrows(Class, ThrowingRunnable)} and the * {@link org.junit.rules.ExpectedException ExpectedException} rule. * With assertThrows the code that throws the exception can be * precisely specified. If the exception's message or one of its properties * should be verified, the ExpectedException rule can be used. Further * information about exception testing can be found at the * JUnit Wiki. * *

    Timeout

    *

    * The 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; } junit4-r4.13.2/src/main/java/org/junit/TestCouldNotBeSkippedException.java000066400000000000000000000013131401177727100264610ustar00rootroot00000000000000package org.junit; /** * Indicates that a test that indicated that it should be skipped could not be skipped. * This can be thrown if a test uses the methods in {@link Assume} to indicate that * it should be skipped, but before processing of the test was completed, other failures * occured. * * @see org.junit.Assume * @since 4.13 */ public class TestCouldNotBeSkippedException extends RuntimeException { private static final long serialVersionUID = 1L; /** Creates an instance using the given assumption failure. */ public TestCouldNotBeSkippedException(org.junit.internal.AssumptionViolatedException cause) { super("Test could not be skipped due to other failures", cause); } } junit4-r4.13.2/src/main/java/org/junit/experimental/000077500000000000000000000000001401177727100222605ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/ParallelComputer.java000066400000000000000000000041671401177727100264060ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/experimental/categories/000077500000000000000000000000001401177727100244055ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/categories/Categories.java000066400000000000000000000333061401177727100273420ustar00rootroot00000000000000package org.junit.experimental.categories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; 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) { return new CategoryFilter(matchAny, 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) { return new CategoryFilter(true, null, matchAny, 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); } @Deprecated public CategoryFilter(Class includedCategory, Class excludedCategory) { includedAny = true; excludedAny = true; included = nullableClassToSet(includedCategory); excluded = nullableClassToSet(excludedCategory); } protected CategoryFilter(boolean matchAnyIncludes, Set> includes, boolean matchAnyExcludes, Set> excludes) { includedAny = matchAnyIncludes; excludedAny = matchAnyExcludes; included = copyAndRefine(includes); excluded = copyAndRefine(excludes); } private CategoryFilter(boolean matchAnyIncludes, Class[] inclusions, boolean matchAnyExcludes, Class[] exclusions) { includedAny = matchAnyIncludes; excludedAny = matchAnyExcludes; included = createSet(inclusions); excluded = createSet(exclusions); } /** * @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 LinkedHashSet>(); if (classes != null) { c.addAll(classes); } c.remove(null); return c; } } 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[] classes) { // Not throwing a NPE if t is null is a bad idea, but it's the behavior from JUnit 4.12 // for include(boolean, Class...) and exclude(boolean, Class...) if (classes == null || classes.length == 0) { return Collections.emptySet(); } for (Class category : classes) { if (category == null) { throw new NullPointerException("has null category"); } } return classes.length == 1 ? Collections.>singleton(classes[0]) : new LinkedHashSet>(Arrays.asList(classes)); } private static Set> nullableClassToSet(Class nullableClass) { // Not throwing a NPE if t is null is a bad idea, but it's the behavior from JUnit 4.11 // for CategoryFilter(Class includedCategory, Class excludedCategory) return nullableClass == null ? Collections.>emptySet() : Collections.>singleton(nullableClass); } } junit4-r4.13.2/src/main/java/org/junit/experimental/categories/Category.java000066400000000000000000000020121401177727100270200ustar00rootroot00000000000000package 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(); }junit4-r4.13.2/src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java000066400000000000000000000034071401177727100315270ustar00rootroot00000000000000package 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(",")) { /* * Load the category class using the context class loader. * If there is no context class loader, use the class loader for this class. */ Class categoryClass = Classes.getClass(category, getClass()); categoryClasses.add(categoryClass); } return categoryClasses; } } junit4-r4.13.2/src/main/java/org/junit/experimental/categories/CategoryValidator.java000066400000000000000000000042101401177727100306700ustar00rootroot00000000000000package 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)); } } junit4-r4.13.2/src/main/java/org/junit/experimental/categories/ExcludeCategories.java000066400000000000000000000030121401177727100306430ustar00rootroot00000000000000package 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(); } } } junit4-r4.13.2/src/main/java/org/junit/experimental/categories/IncludeCategories.java000066400000000000000000000030061401177727100306400ustar00rootroot00000000000000package 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(); } } } junit4-r4.13.2/src/main/java/org/junit/experimental/max/000077500000000000000000000000001401177727100230455ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java000066400000000000000000000005071401177727100307250ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/org/junit/experimental/max/MaxCore.java000066400000000000000000000144151401177727100252530ustar00rootroot00000000000000package 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); } } } }junit4-r4.13.2/src/main/java/org/junit/experimental/max/MaxHistory.java000066400000000000000000000126141401177727100260230ustar00rootroot00000000000000package 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 = null; try { stream = new ObjectOutputStream(new FileOutputStream(fHistoryStore)); stream.writeObject(this); } finally { if (stream != null) { 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(); } } junit4-r4.13.2/src/main/java/org/junit/experimental/results/000077500000000000000000000000001401177727100237615ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/results/FailureList.java000066400000000000000000000013511401177727100270470ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/experimental/results/PrintableResult.java000066400000000000000000000034401401177727100277440ustar00rootroot00000000000000package 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(); } /** * Returns the failures in this result. * * @since 4.13 */ public List failures() { return result.getFailures(); } @Override public String toString() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); new TextListener(new PrintStream(stream)).testRunFinished(result); return stream.toString(); } }junit4-r4.13.2/src/main/java/org/junit/experimental/results/ResultMatchers.java000066400000000000000000000060441401177727100275750ustar00rootroot00000000000000package 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 exactly one failure matching the given matcher. * * @since 4.13 */ public static Matcher hasSingleFailureMatching(final Matcher matcher) { return new TypeSafeMatcher() { @Override public boolean matchesSafely(PrintableResult item) { return item.failureCount() == 1 && matcher.matches(item.failures().get(0).getException()); } public void describeTo(Description description) { description.appendText("has failure with exception matching "); matcher.describeTo(description); } }; } /** * 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 TypeSafeMatcher() { @Override public boolean matchesSafely(PrintableResult item) { return item.failureCount() > 0 && item.toString().contains(string); } public void describeTo(Description description) { description.appendText("has failure containing " + string); } }; } } junit4-r4.13.2/src/main/java/org/junit/experimental/runners/000077500000000000000000000000001401177727100237545ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/runners/Enclosed.java000066400000000000000000000027501401177727100263570ustar00rootroot00000000000000package 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()]); } } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/000077500000000000000000000000001401177727100241025ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/theories/DataPoint.java000066400000000000000000000041041401177727100266270ustar00rootroot00000000000000package 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 {}; }junit4-r4.13.2/src/main/java/org/junit/experimental/theories/DataPoints.java000066400000000000000000000047741401177727100270270ustar00rootroot00000000000000package 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 {}; } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/FromDataPoints.java000066400000000000000000000037261401177727100276470ustar00rootroot00000000000000package 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(); } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/ParameterSignature.java000066400000000000000000000110211401177727100305420ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/experimental/theories/ParameterSupplier.java000066400000000000000000000031721401177727100304140ustar00rootroot00000000000000package 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; } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/ParametersSuppliedBy.java000066400000000000000000000026671401177727100310640ustar00rootroot00000000000000package 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 hierarchy 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(); } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/PotentialAssignment.java000066400000000000000000000031041401177727100307330ustar00rootroot00000000000000package 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; }junit4-r4.13.2/src/main/java/org/junit/experimental/theories/Theories.java000066400000000000000000000313501401177727100265310ustar00rootroot00000000000000package 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); } /** @since 4.13 */ protected Theories(TestClass testClass) throws InitializationError { super(testClass); } @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()) { @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++; } } } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/Theory.java000066400000000000000000000010201401177727100262100ustar00rootroot00000000000000package 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; }junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internal/000077500000000000000000000000001401177727100257165ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java000066400000000000000000000171541401177727100323400ustar00rootroot00000000000000package 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); } }junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internal/Assignments.java000066400000000000000000000125331401177727100310600ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internal/BooleanSupplier.java000066400000000000000000000011131401177727100316600ustar00rootroot00000000000000package 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)); } } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internal/EnumSupplier.java000066400000000000000000000015631401177727100312160ustar00rootroot00000000000000package 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; } } ParameterizedAssertionError.java000066400000000000000000000027201401177727100342010ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internalpackage 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]"; } } }SpecificDataPointsSupplier.java000066400000000000000000000065231401177727100337500ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/theories/internalpackage 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; } } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/suppliers/000077500000000000000000000000001401177727100261305ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/experimental/theories/suppliers/TestedOn.java000066400000000000000000000017511401177727100305240ustar00rootroot00000000000000package 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(); } junit4-r4.13.2/src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java000066400000000000000000000015531401177727100322500ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/function/000077500000000000000000000000001401177727100214105ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/function/ThrowingRunnable.java000066400000000000000000000006731401177727100255510ustar00rootroot00000000000000package org.junit.function; /** * This interface facilitates the use of * {@link org.junit.Assert#assertThrows(Class, ThrowingRunnable)} from Java 8. It allows method * references to void methods (that declare checked exceptions) to be passed directly into * {@code assertThrows} * without wrapping. It is not meant to be implemented directly. * * @since 4.13 */ public interface ThrowingRunnable { void run() throws Throwable; } junit4-r4.13.2/src/main/java/org/junit/internal/000077500000000000000000000000001401177727100213775ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/ArrayComparisonFailure.java000066400000000000000000000040151401177727100266630ustar00rootroot00000000000000package 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(); } } junit4-r4.13.2/src/main/java/org/junit/internal/AssumptionViolatedException.java000066400000000000000000000116411401177727100277560ustar00rootroot00000000000000package org.junit.internal; import java.io.IOException; import java.io.ObjectOutputStream; 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); } } } /** * Override default Java object serialization to correctly deal with potentially unserializable matchers or values. * By not implementing readObject, we assure ourselves of backwards compatibility and compatibility with the * standard way of Java serialization. * * @param objectOutputStream The outputStream to write our representation to * @throws IOException When serialization fails */ private void writeObject(ObjectOutputStream objectOutputStream) throws IOException { ObjectOutputStream.PutField putField = objectOutputStream.putFields(); putField.put("fAssumption", fAssumption); putField.put("fValueMatcher", fValueMatcher); // We have to wrap the matcher into a serializable form. putField.put("fMatcher", SerializableMatcherDescription.asSerializableMatcher(fMatcher)); // We have to wrap the value inside a non-String class (instead of serializing the String value directly) as // A Description will handle a String and non-String object differently (1st is surrounded by '"' while the // latter will be surrounded by '<' '>'. Wrapping it makes sure that the description of a serialized and // non-serialized instance produce the exact same description putField.put("fValue", SerializableValueDescription.asSerializableValue(fValue)); objectOutputStream.writeFields(); } } junit4-r4.13.2/src/main/java/org/junit/internal/Checks.java000066400000000000000000000021051401177727100234400ustar00rootroot00000000000000package org.junit.internal; /** @since 4.13 */ public final class Checks { private Checks() {} /** * Checks that the given value is not {@code null}. * * @param value object reference to check * @return the passed-in value, if not {@code null} * @throws NullPointerException if {@code value} is {@code null} */ public static T notNull(T value) { if (value == null) { throw new NullPointerException(); } return value; } /** * Checks that the given value is not {@code null}, using the given message * as the exception message if an exception is thrown. * * @param value object reference to check * @param message message to use if {@code value} is {@code null} * @return the passed-in value, if not {@code null} * @throws NullPointerException if {@code value} is {@code null} */ public static T notNull(T value, String message) { if (value == null) { throw new NullPointerException(message); } return value; } } junit4-r4.13.2/src/main/java/org/junit/internal/Classes.java000066400000000000000000000027301401177727100236410ustar00rootroot00000000000000package 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. * If the current thread does not have a class loader, falls back to the class loader for * {@link Classes}. * * @param className Name of the class. * @throws ClassNotFoundException */ public static Class getClass(String className) throws ClassNotFoundException { return getClass(className, Classes.class); } /** * Returns Class.forName for {@code className} using the current thread's class loader. * If the current thread does not have a class loader, falls back to the class loader for the * passed-in class. * * @param className Name of the class. * @param callingClass Class that is requesting a the class * @throws ClassNotFoundException * @since 4.13 */ public static Class getClass(String className, Class callingClass) throws ClassNotFoundException { ClassLoader classLoader = currentThread().getContextClassLoader(); return Class.forName(className, true, classLoader == null ? callingClass.getClassLoader() : classLoader); } } junit4-r4.13.2/src/main/java/org/junit/internal/ComparisonCriteria.java000066400000000000000000000117521401177727100260450ustar00rootroot00000000000000package 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); } junit4-r4.13.2/src/main/java/org/junit/internal/ExactComparisonCriteria.java000066400000000000000000000004071401177727100270250ustar00rootroot00000000000000package org.junit.internal; import org.junit.Assert; public class ExactComparisonCriteria extends ComparisonCriteria { @Override protected void assertElementsEqual(Object expected, Object actual) { Assert.assertEquals(expected, actual); } } junit4-r4.13.2/src/main/java/org/junit/internal/InexactComparisonCriteria.java000066400000000000000000000012111401177727100273460ustar00rootroot00000000000000package 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); } } }junit4-r4.13.2/src/main/java/org/junit/internal/JUnitSystem.java000066400000000000000000000003361401177727100245020ustar00rootroot00000000000000package 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(); } junit4-r4.13.2/src/main/java/org/junit/internal/MethodSorter.java000066400000000000000000000045621401177727100246700ustar00rootroot00000000000000package 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(); } } junit4-r4.13.2/src/main/java/org/junit/internal/RealSystem.java000066400000000000000000000005031401177727100243300ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/internal/SerializableMatcherDescription.java000066400000000000000000000035561401177727100303710ustar00rootroot00000000000000package org.junit.internal; import java.io.Serializable; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; /** * This class exists solely to provide a serializable description of a matcher to be serialized as a field in * {@link AssumptionViolatedException}. Being a {@link Throwable}, it is required to be {@link Serializable}, but most * implementations of {@link Matcher} are not. This class works around that limitation as * {@link AssumptionViolatedException} only every uses the description of the {@link Matcher}, while still retaining * backwards compatibility with classes compiled against its class signature before 4.14 and/or deserialization of * previously serialized instances. */ class SerializableMatcherDescription extends BaseMatcher implements Serializable { private final String matcherDescription; private SerializableMatcherDescription(Matcher matcher) { matcherDescription = StringDescription.asString(matcher); } public boolean matches(Object o) { throw new UnsupportedOperationException("This Matcher implementation only captures the description"); } public void describeTo(Description description) { description.appendText(matcherDescription); } /** * Factory method that checks to see if the matcher is already serializable. * @param matcher the matcher to make serializable * @return The provided matcher if it is null or already serializable, * the SerializableMatcherDescription representation of it if it is not. */ static Matcher asSerializableMatcher(Matcher matcher) { if (matcher == null || matcher instanceof Serializable) { return matcher; } else { return new SerializableMatcherDescription(matcher); } } } junit4-r4.13.2/src/main/java/org/junit/internal/SerializableValueDescription.java000066400000000000000000000027031401177727100300530ustar00rootroot00000000000000package org.junit.internal; import java.io.Serializable; /** * This class exists solely to provide a serializable description of a value to be serialized as a field in * {@link AssumptionViolatedException}. Being a {@link Throwable}, it is required to be {@link Serializable}, but a * value of type Object provides no guarantee to be serializable. This class works around that limitation as * {@link AssumptionViolatedException} only every uses the string representation of the value, while still retaining * backwards compatibility with classes compiled against its class signature before 4.14 and/or deserialization of * previously serialized instances. */ class SerializableValueDescription implements Serializable { private final String value; private SerializableValueDescription(Object value) { this.value = String.valueOf(value); } /** * Factory method that checks to see if the value is already serializable. * @param value the value to make serializable * @return The provided value if it is null or already serializable, * the SerializableValueDescription representation of it if it is not. */ static Object asSerializableValue(Object value) { if (value == null || value instanceof Serializable) { return value; } else { return new SerializableValueDescription(value); } } @Override public String toString() { return value; } } junit4-r4.13.2/src/main/java/org/junit/internal/TextListener.java000066400000000000000000000053231401177727100246770ustar00rootroot00000000000000package 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.getTrimmedTrace()); } 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); } } junit4-r4.13.2/src/main/java/org/junit/internal/Throwables.java000066400000000000000000000230451401177727100243600ustar00rootroot00000000000000package org.junit.internal; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.Method; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * 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(); } /** * Gets a trimmed version of the stack trace of the given exception. Stack trace * elements that are below the test method are filtered out. * * @return a trimmed stack trace, or the original trace if trimming wasn't possible */ public static String getTrimmedStackTrace(Throwable exception) { List trimmedStackTraceLines = getTrimmedStackTraceLines(exception); if (trimmedStackTraceLines.isEmpty()) { return getFullStackTrace(exception); } StringBuilder result = new StringBuilder(exception.toString()); appendStackTraceLines(trimmedStackTraceLines, result); appendStackTraceLines(getCauseStackTraceLines(exception), result); return result.toString(); } private static List getTrimmedStackTraceLines(Throwable exception) { List stackTraceElements = Arrays.asList(exception.getStackTrace()); int linesToInclude = stackTraceElements.size(); State state = State.PROCESSING_OTHER_CODE; for (StackTraceElement stackTraceElement : asReversedList(stackTraceElements)) { state = state.processStackTraceElement(stackTraceElement); if (state == State.DONE) { List trimmedLines = new ArrayList(linesToInclude + 2); trimmedLines.add(""); for (StackTraceElement each : stackTraceElements.subList(0, linesToInclude)) { trimmedLines.add("\tat " + each); } if (exception.getCause() != null) { trimmedLines.add("\t... " + (stackTraceElements.size() - trimmedLines.size()) + " trimmed"); } return trimmedLines; } linesToInclude--; } return Collections.emptyList(); } private static final Method getSuppressed = initGetSuppressed(); private static Method initGetSuppressed() { try { return Throwable.class.getMethod("getSuppressed"); } catch (Throwable e) { return null; } } private static boolean hasSuppressed(Throwable exception) { if (getSuppressed == null) { return false; } try { Throwable[] suppressed = (Throwable[]) getSuppressed.invoke(exception); return suppressed.length != 0; } catch (Throwable e) { return false; } } private static List getCauseStackTraceLines(Throwable exception) { if (exception.getCause() != null || hasSuppressed(exception)) { String fullTrace = getFullStackTrace(exception); BufferedReader reader = new BufferedReader( new StringReader(fullTrace.substring(exception.toString().length()))); List causedByLines = new ArrayList(); try { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("Caused by: ") || line.trim().startsWith("Suppressed: ")) { causedByLines.add(line); while ((line = reader.readLine()) != null) { causedByLines.add(line); } return causedByLines; } } } catch (IOException e) { // We should never get here, because we are reading from a StringReader } } return Collections.emptyList(); } private static String getFullStackTrace(Throwable exception) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); exception.printStackTrace(writer); return stringWriter.toString(); } private static void appendStackTraceLines( List stackTraceLines, StringBuilder destBuilder) { for (String stackTraceLine : stackTraceLines) { destBuilder.append(String.format("%s%n", stackTraceLine)); } } private static List asReversedList(final List list) { return new AbstractList() { @Override public T get(int index) { return list.get(list.size() - index - 1); } @Override public int size() { return list.size(); } }; } private enum State { PROCESSING_OTHER_CODE { @Override public State processLine(String methodName) { if (isTestFrameworkMethod(methodName)) { return PROCESSING_TEST_FRAMEWORK_CODE; } return this; } }, PROCESSING_TEST_FRAMEWORK_CODE { @Override public State processLine(String methodName) { if (isReflectionMethod(methodName)) { return PROCESSING_REFLECTION_CODE; } else if (isTestFrameworkMethod(methodName)) { return this; } return PROCESSING_OTHER_CODE; } }, PROCESSING_REFLECTION_CODE { @Override public State processLine(String methodName) { if (isReflectionMethod(methodName)) { return this; } else if (isTestFrameworkMethod(methodName)) { // This is here to handle TestCase.runBare() calling TestCase.runTest(). return PROCESSING_TEST_FRAMEWORK_CODE; } return DONE; } }, DONE { @Override public State processLine(String methodName) { return this; } }; /** Processes a stack trace element method name, possibly moving to a new state. */ protected abstract State processLine(String methodName); /** Processes a stack trace element, possibly moving to a new state. */ public final State processStackTraceElement(StackTraceElement element) { return processLine(element.getClassName() + "." + element.getMethodName() + "()"); } } private static final String[] TEST_FRAMEWORK_METHOD_NAME_PREFIXES = { "org.junit.runner.", "org.junit.runners.", "org.junit.experimental.runners.", "org.junit.internal.", "junit.extensions", "junit.framework", "junit.runner", "junit.textui", }; private static final String[] TEST_FRAMEWORK_TEST_METHOD_NAME_PREFIXES = { "org.junit.internal.StackTracesTest", }; private static boolean isTestFrameworkMethod(String methodName) { return isMatchingMethod(methodName, TEST_FRAMEWORK_METHOD_NAME_PREFIXES) && !isMatchingMethod(methodName, TEST_FRAMEWORK_TEST_METHOD_NAME_PREFIXES); } private static final String[] REFLECTION_METHOD_NAME_PREFIXES = { "sun.reflect.", "java.lang.reflect.", "jdk.internal.reflect.", "org.junit.rules.RunRules.(", "org.junit.rules.RunRules.applyAll(", // calls TestRules "org.junit.runners.RuleContainer.apply(", // calls MethodRules & TestRules "junit.framework.TestCase.runBare(", // runBare() directly calls setUp() and tearDown() }; private static boolean isReflectionMethod(String methodName) { return isMatchingMethod(methodName, REFLECTION_METHOD_NAME_PREFIXES); } private static boolean isMatchingMethod(String methodName, String[] methodNamePrefixes) { for (String methodNamePrefix : methodNamePrefixes) { if (methodName.startsWith(methodNamePrefix)) { return true; } } return false; } } junit4-r4.13.2/src/main/java/org/junit/internal/builders/000077500000000000000000000000001401177727100232105ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java000066400000000000000000000032761401177727100321520ustar00rootroot00000000000000package 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; /** * @since 4.13 */ public AllDefaultPossibilitiesBuilder() { canUseSuiteMethod = true; } /** * @deprecated used {@link #AllDefaultPossibilitiesBuilder()}. */ @Deprecated 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(); } }junit4-r4.13.2/src/main/java/org/junit/internal/builders/AnnotatedBuilder.java000066400000000000000000000102531401177727100273000ustar00rootroot00000000000000package 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)); } } } }junit4-r4.13.2/src/main/java/org/junit/internal/builders/IgnoredBuilder.java000066400000000000000000000006401401177727100267510ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/internal/builders/IgnoredClassRunner.java000066400000000000000000000010661401177727100276250ustar00rootroot00000000000000package 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); } }junit4-r4.13.2/src/main/java/org/junit/internal/builders/JUnit3Builder.java000066400000000000000000000010641401177727100264770ustar00rootroot00000000000000package 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); } }junit4-r4.13.2/src/main/java/org/junit/internal/builders/JUnit4Builder.java000066400000000000000000000005151401177727100265000ustar00rootroot00000000000000package org.junit.internal.builders; import org.junit.runner.Runner; import org.junit.runners.JUnit4; import org.junit.runners.model.RunnerBuilder; public class JUnit4Builder extends RunnerBuilder { @Override public Runner runnerForClass(Class testClass) throws Throwable { return new JUnit4(testClass); } } junit4-r4.13.2/src/main/java/org/junit/internal/builders/NullBuilder.java000066400000000000000000000004231401177727100262730ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java000066400000000000000000000011751401177727100276200ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/internal/management/000077500000000000000000000000001401177727100235135ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/management/FakeRuntimeMXBean.java000066400000000000000000000006131401177727100276230ustar00rootroot00000000000000package org.junit.internal.management; import java.util.Collections; import java.util.List; /** * No-op implementation of RuntimeMXBean when the platform doesn't provide it. */ class FakeRuntimeMXBean implements RuntimeMXBean { /** * {@inheritDoc} * *

    Always returns an empty list. */ public List getInputArguments() { return Collections.emptyList(); } } junit4-r4.13.2/src/main/java/org/junit/internal/management/FakeThreadMXBean.java000066400000000000000000000010011401177727100273770ustar00rootroot00000000000000package org.junit.internal.management; /** * No-op implementation of ThreadMXBean when the platform doesn't provide it. */ final class FakeThreadMXBean implements ThreadMXBean { /** * {@inheritDoc} * *

    Always throws an {@link UnsupportedOperationException} */ public long getThreadCpuTime(long id) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * *

    Always returns false. */ public boolean isThreadCpuTimeSupported() { return false; } } junit4-r4.13.2/src/main/java/org/junit/internal/management/ManagementFactory.java000066400000000000000000000044771401177727100277760ustar00rootroot00000000000000package org.junit.internal.management; import org.junit.internal.Classes; import java.lang.reflect.InvocationTargetException; /** * Reflective wrapper around {@link java.lang.management.ManagementFactory} */ public class ManagementFactory { private static final class FactoryHolder { private static final Class MANAGEMENT_FACTORY_CLASS; static { Class managementFactoryClass = null; try { managementFactoryClass = Classes.getClass("java.lang.management.ManagementFactory"); } catch (ClassNotFoundException e) { // do nothing, managementFactoryClass will be none on failure } MANAGEMENT_FACTORY_CLASS = managementFactoryClass; } static Object getBeanObject(String methodName) { if (MANAGEMENT_FACTORY_CLASS != null) { try { return MANAGEMENT_FACTORY_CLASS.getMethod(methodName).invoke(null); } catch (IllegalAccessException e) { // fallthrough } catch (IllegalArgumentException e) { // fallthrough } catch (InvocationTargetException e) { // fallthrough } catch (NoSuchMethodException e) { // fallthrough } catch (SecurityException e) { // fallthrough } } return null; } } private static final class RuntimeHolder { private static final RuntimeMXBean RUNTIME_MX_BEAN = getBean(FactoryHolder.getBeanObject("getRuntimeMXBean")); private static final RuntimeMXBean getBean(Object runtimeMxBean) { return runtimeMxBean != null ? new ReflectiveRuntimeMXBean(runtimeMxBean) : new FakeRuntimeMXBean(); } } private static final class ThreadHolder { private static final ThreadMXBean THREAD_MX_BEAN = getBean(FactoryHolder.getBeanObject("getThreadMXBean")); private static final ThreadMXBean getBean(Object threadMxBean) { return threadMxBean != null ? new ReflectiveThreadMXBean(threadMxBean) : new FakeThreadMXBean(); } } /** * @see java.lang.management.ManagementFactory#getRuntimeMXBean() */ public static RuntimeMXBean getRuntimeMXBean() { return RuntimeHolder.RUNTIME_MX_BEAN; } /** * @see java.lang.management.ManagementFactory#getThreadMXBean() */ public static ThreadMXBean getThreadMXBean() { return ThreadHolder.THREAD_MX_BEAN; } } junit4-r4.13.2/src/main/java/org/junit/internal/management/ReflectiveRuntimeMXBean.java000066400000000000000000000034361401177727100310530ustar00rootroot00000000000000package org.junit.internal.management; import org.junit.internal.Classes; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; /** * Implementation of {@link RuntimeMXBean} using the JVM reflectively. */ final class ReflectiveRuntimeMXBean implements RuntimeMXBean { private final Object runtimeMxBean; private static final class Holder { private static final Method getInputArgumentsMethod; static { Method inputArguments = null; try { Class threadMXBeanClass = Classes.getClass("java.lang.management.RuntimeMXBean"); inputArguments = threadMXBeanClass.getMethod("getInputArguments"); } catch (ClassNotFoundException e) { // do nothing, input arguments will be null on failure } catch (NoSuchMethodException e) { // do nothing, input arguments will be null on failure } catch (SecurityException e) { // do nothing, input arguments will be null on failure } getInputArgumentsMethod = inputArguments; } } ReflectiveRuntimeMXBean(Object runtimeMxBean) { super(); this.runtimeMxBean = runtimeMxBean; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public List getInputArguments() { if (Holder.getInputArgumentsMethod != null) { try { return (List) Holder.getInputArgumentsMethod.invoke(runtimeMxBean); } catch (ClassCastException e) { // no multi-catch with source level 6 // fallthrough } catch (IllegalAccessException e) { // fallthrough } catch (IllegalArgumentException e) { // fallthrough } catch (InvocationTargetException e) { // fallthrough } } return Collections.emptyList(); } } junit4-r4.13.2/src/main/java/org/junit/internal/management/ReflectiveThreadMXBean.java000066400000000000000000000053031401177727100306320ustar00rootroot00000000000000package org.junit.internal.management; import org.junit.internal.Classes; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Implementation of {@link ThreadMXBean} using the JVM reflectively. */ final class ReflectiveThreadMXBean implements ThreadMXBean { private final Object threadMxBean; private static final class Holder { static final Method getThreadCpuTimeMethod; static final Method isThreadCpuTimeSupportedMethod; private static final String FAILURE_MESSAGE = "Unable to access ThreadMXBean"; static { Method threadCpuTime = null; Method threadCpuTimeSupported = null; try { Class threadMXBeanClass = Classes.getClass("java.lang.management.ThreadMXBean"); threadCpuTime = threadMXBeanClass.getMethod("getThreadCpuTime", long.class); threadCpuTimeSupported = threadMXBeanClass.getMethod("isThreadCpuTimeSupported"); } catch (ClassNotFoundException e) { // do nothing, the methods will be null on failure } catch (NoSuchMethodException e) { // do nothing, the methods will be null on failure } catch (SecurityException e) { // do nothing, the methods will be null on failure } getThreadCpuTimeMethod = threadCpuTime; isThreadCpuTimeSupportedMethod = threadCpuTimeSupported; } } ReflectiveThreadMXBean(Object threadMxBean) { super(); this.threadMxBean = threadMxBean; } /** * {@inheritDoc} */ public long getThreadCpuTime(long id) { if (Holder.getThreadCpuTimeMethod != null) { Exception error = null; try { return (Long) Holder.getThreadCpuTimeMethod.invoke(threadMxBean, id); } catch (ClassCastException e) { error = e; // fallthrough } catch (IllegalAccessException e) { error = e; // fallthrough } catch (IllegalArgumentException e) { error = e; // fallthrough } catch (InvocationTargetException e) { error = e; // fallthrough } throw new UnsupportedOperationException(Holder.FAILURE_MESSAGE, error); } throw new UnsupportedOperationException(Holder.FAILURE_MESSAGE); } /** * {@inheritDoc} */ public boolean isThreadCpuTimeSupported() { if (Holder.isThreadCpuTimeSupportedMethod != null) { try { return (Boolean) Holder.isThreadCpuTimeSupportedMethod.invoke(threadMxBean); } catch (ClassCastException e) { // fallthrough } catch (IllegalAccessException e) { // fallthrough } catch (IllegalArgumentException e) { // fallthrough } catch (InvocationTargetException e) { // fallthrough } } return false; } } junit4-r4.13.2/src/main/java/org/junit/internal/management/RuntimeMXBean.java000066400000000000000000000004301401177727100270310ustar00rootroot00000000000000package org.junit.internal.management; import java.util.List; /** * Wrapper for {@link java.lang.management.RuntimeMXBean}. */ public interface RuntimeMXBean { /** * @see java.lang.management.RuntimeMXBean#getInputArguments() */ List getInputArguments(); } junit4-r4.13.2/src/main/java/org/junit/internal/management/ThreadMXBean.java000066400000000000000000000005701401177727100266220ustar00rootroot00000000000000package org.junit.internal.management; /** * Wrapper for {@link java.lang.management.ThreadMXBean}. */ public interface ThreadMXBean { /** * @see java.lang.management.ThreadMXBean#getThreadCpuTime(long) */ long getThreadCpuTime(long id); /** * @see java.lang.management.ThreadMXBean#isThreadCpuTimeSupported() */ boolean isThreadCpuTimeSupported(); } junit4-r4.13.2/src/main/java/org/junit/internal/matchers/000077500000000000000000000000001401177727100232055ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java000066400000000000000000000030741401177727100311570ustar00rootroot00000000000000package 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. */ 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); } } junit4-r4.13.2/src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java000066400000000000000000000030001401177727100302550ustar00rootroot00000000000000package 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 */ 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); } }junit4-r4.13.2/src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java000066400000000000000000000020631401177727100306110ustar00rootroot00000000000000package 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); } }junit4-r4.13.2/src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java000066400000000000000000000037621401177727100271040ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/org/junit/internal/requests/000077500000000000000000000000001401177727100232525ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/requests/ClassRequest.java000066400000000000000000000033211401177727100265320ustar00rootroot00000000000000package org.junit.internal.requests; import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; import org.junit.internal.builders.SuiteMethodBuilder; import org.junit.runner.Runner; import org.junit.runners.model.RunnerBuilder; public class ClassRequest extends MemoizingRequest { /* * 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; public ClassRequest(Class testClass, boolean canUseSuiteMethod) { this.fTestClass = testClass; this.canUseSuiteMethod = canUseSuiteMethod; } public ClassRequest(Class testClass) { this(testClass, true); } @Override protected Runner createRunner() { return new CustomAllDefaultPossibilitiesBuilder().safeRunnerForClass(fTestClass); } private class CustomAllDefaultPossibilitiesBuilder extends AllDefaultPossibilitiesBuilder { @Override protected RunnerBuilder suiteMethodBuilder() { return new CustomSuiteMethodBuilder(); } } /* * Customization of {@link SuiteMethodBuilder} that prevents use of the * suite method when creating a runner for fTestClass when canUseSuiteMethod * is false. */ private class CustomSuiteMethodBuilder extends SuiteMethodBuilder { @Override public Runner runnerForClass(Class testClass) throws Throwable { if (testClass == fTestClass && !canUseSuiteMethod) { return null; } return super.runnerForClass(testClass); } } }junit4-r4.13.2/src/main/java/org/junit/internal/requests/FilterRequest.java000066400000000000000000000026121401177727100267140ustar00rootroot00000000000000package 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()))); } } }junit4-r4.13.2/src/main/java/org/junit/internal/requests/MemoizingRequest.java000066400000000000000000000014751401177727100274330ustar00rootroot00000000000000package org.junit.internal.requests; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.junit.runner.Request; import org.junit.runner.Runner; abstract class MemoizingRequest extends Request { private final Lock runnerLock = new ReentrantLock(); private volatile Runner runner; @Override public final Runner getRunner() { if (runner == null) { runnerLock.lock(); try { if (runner == null) { runner = createRunner(); } } finally { runnerLock.unlock(); } } return runner; } /** Creates the {@link Runner} to return from {@link #getRunner()}. Called at most once. */ protected abstract Runner createRunner(); } junit4-r4.13.2/src/main/java/org/junit/internal/requests/OrderingRequest.java000066400000000000000000000015341401177727100272420ustar00rootroot00000000000000package 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.InvalidOrderingException; import org.junit.runner.manipulation.Ordering; /** @since 4.13 */ public class OrderingRequest extends MemoizingRequest { private final Request request; private final Ordering ordering; public OrderingRequest(Request request, Ordering ordering) { this.request = request; this.ordering = ordering; } @Override protected Runner createRunner() { Runner runner = request.getRunner(); try { ordering.apply(runner); } catch (InvalidOrderingException e) { return new ErrorReportingRunner(ordering.getClass(), e); } return runner; } } junit4-r4.13.2/src/main/java/org/junit/internal/requests/SortingRequest.java000066400000000000000000000012461401177727100271160ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/internal/requests/package-info.java000066400000000000000000000001761401177727100264450ustar00rootroot00000000000000/** * Provides implementations of {@link org.junit.runner.Request}. * * @since 4.0 */ package org.junit.internal.requests;junit4-r4.13.2/src/main/java/org/junit/internal/runners/000077500000000000000000000000001401177727100230735ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/runners/ClassRoadie.java000066400000000000000000000046371401177727100261410ustar00rootroot00000000000000package 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 } } } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/ErrorReportingRunner.java000066400000000000000000000060221401177727100301130ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/FailedBefore.java000066400000000000000000000006461401177727100262530ustar00rootroot00000000000000package 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; }junit4-r4.13.2/src/main/java/org/junit/internal/runners/InitializationError.java000066400000000000000000000016431401177727100277430ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java000066400000000000000000000147251401177727100273330ustar00rootroot00000000000000package org.junit.internal.runners; import java.lang.annotation.Annotation; import java.lang.reflect.Method; 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.Orderer; import org.junit.runner.manipulation.InvalidOrderingException; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Orderable; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; public class JUnit38ClassRunner extends Runner implements Filterable, Orderable { 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); } } /** * {@inheritDoc} * * @since 4.13 */ public void order(Orderer orderer) throws InvalidOrderingException { if (getTest() instanceof Orderable) { Orderable adapter = (Orderable) getTest(); adapter.order(orderer); } } private void setTest(Test test) { this.test = test; } private Test getTest() { return test; } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/JUnit4ClassRunner.java000066400000000000000000000113611401177727100272350ustar00rootroot00000000000000package 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; } }junit4-r4.13.2/src/main/java/org/junit/internal/runners/MethodRoadie.java000066400000000000000000000127521401177727100263110ustar00rootroot00000000000000package 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)); } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/MethodValidator.java000066400000000000000000000062431401177727100270310ustar00rootroot00000000000000package 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")); } } } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/SuiteMethod.java000066400000000000000000000023031401177727100261660ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/TestClass.java000066400000000000000000000064031401177727100256460ustar00rootroot00000000000000package 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(); } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/TestMethod.java000066400000000000000000000037151401177727100260240ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/model/000077500000000000000000000000001401177727100241735ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/runners/model/EachTestNotifier.java000066400000000000000000000045251401177727100302440ustar00rootroot00000000000000package 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); } }junit4-r4.13.2/src/main/java/org/junit/internal/runners/model/MultipleFailureException.java000066400000000000000000000005031401177727100320160ustar00rootroot00000000000000package 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); } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/model/ReflectiveCallable.java000066400000000000000000000010411401177727100305420ustar00rootroot00000000000000package 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; }junit4-r4.13.2/src/main/java/org/junit/internal/runners/package-info.java000066400000000000000000000001731401177727100262630ustar00rootroot00000000000000/** * Provides implementations of {@link org.junit.runner.Runner} * * @since 4.0 */ package org.junit.internal.runners;junit4-r4.13.2/src/main/java/org/junit/internal/runners/rules/000077500000000000000000000000001401177727100242255ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/runners/rules/RuleMemberValidator.java000066400000000000000000000250501401177727100307770ustar00rootroot00000000000000package 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.")); } } } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/rules/ValidationError.java000066400000000000000000000007261401177727100302010ustar00rootroot00000000000000package 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)); } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/000077500000000000000000000000001401177727100252625ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/ExpectException.java000066400000000000000000000023311401177727100312330ustar00rootroot00000000000000package 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) { if (!expected.isAssignableFrom(e.getClass())) { 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()); } } }junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/Fail.java000066400000000000000000000004671401177727100270070ustar00rootroot00000000000000package 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; } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java000066400000000000000000000277121401177727100306550ustar00rootroot00000000000000package org.junit.internal.runners.statements; 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.internal.management.ManagementFactory; import org.junit.internal.management.ThreadMXBean; 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 = threadGroupForNewThread(); 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; } } private ThreadGroup threadGroupForNewThread() { if (!lookForStuckThread) { // Use the default ThreadGroup (usually the one from the current // thread). return null; } // Create the thread in a new ThreadGroup, so if the time-limited thread // becomes stuck, getStuckThread() can find the thread likely to be the // culprit. ThreadGroup threadGroup = new ThreadGroup("FailOnTimeoutGroup"); if (!threadGroup.isDaemon()) { // Mark the new ThreadGroup as a daemon thread group, so it will be // destroyed after the time-limited thread completes. By ensuring the // ThreadGroup is destroyed, any data associated with the ThreadGroup // (ex: via java.beans.ThreadGroupContext) is destroyed. try { threadGroup.setDaemon(true); } catch (SecurityException e) { // Swallow the exception to keep the same behavior as in JUnit 4.12. } } return threadGroup; } /** * 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(); } } } junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/InvokeMethod.java000066400000000000000000000010121401177727100305130ustar00rootroot00000000000000package 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); } }junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/RunAfters.java000066400000000000000000000023761401177727100300460ustar00rootroot00000000000000package 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 { invokeMethod(each); } catch (Throwable e) { errors.add(e); } } } MultipleFailureException.assertEmpty(errors); } /** * @since 4.13 */ protected void invokeMethod(FrameworkMethod method) throws Throwable { method.invokeExplosively(target); } }junit4-r4.13.2/src/main/java/org/junit/internal/runners/statements/RunBefores.java000066400000000000000000000015231401177727100302000ustar00rootroot00000000000000package 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) { invokeMethod(before); } next.evaluate(); } /** * @since 4.13 */ protected void invokeMethod(FrameworkMethod method) throws Throwable { method.invokeExplosively(target); } }junit4-r4.13.2/src/main/java/org/junit/matchers/000077500000000000000000000000001401177727100213715ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/matchers/JUnitMatchers.java000066400000000000000000000103241401177727100247540ustar00rootroot00000000000000package 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 */ 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); } } junit4-r4.13.2/src/main/java/org/junit/matchers/package-info.java000066400000000000000000000003741401177727100245640ustar00rootroot00000000000000/** * 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;junit4-r4.13.2/src/main/java/org/junit/package-info.java000066400000000000000000000002171401177727100227520ustar00rootroot00000000000000/** * Provides JUnit core classes and annotations. * * Corresponds to junit.framework in Junit 3.x. * * @since 4.0 */ package org.junit;junit4-r4.13.2/src/main/java/org/junit/rules/000077500000000000000000000000001401177727100207155ustar00rootroot00000000000000junit4-r4.13.2/src/main/java/org/junit/rules/DisableOnDebug.java000066400000000000000000000100071401177727100243650ustar00rootroot00000000000000package org.junit.rules; import java.util.List; import org.junit.internal.management.ManagementFactory; import org.junit.internal.management.RuntimeMXBean; 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: *