├── .gitignore ├── .idea ├── copyright │ └── profiles_settings.xml ├── runConfigurations │ ├── All_Tests.xml │ ├── build_hamcrest_1_3__junit_4_12.xml │ └── build_hamcrest_2_0_0_0__junit_4_12.xml └── scopes │ └── scope_settings.xml ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── publish-release ├── settings.gradle ├── src ├── main │ └── java │ │ └── org │ │ └── hamcrest │ │ └── junit │ │ ├── ErrorCollector.java │ │ ├── ExpectedException.java │ │ ├── ExpectedExceptionMatcherBuilder.java │ │ ├── JUnitMatchers.java │ │ ├── MatcherAssert.java │ │ ├── MatcherAssume.java │ │ └── internal │ │ ├── Matching.java │ │ ├── MismatchAction.java │ │ ├── StacktracePrintingMatcher.java │ │ ├── ThrowableCauseMatcher.java │ │ └── ThrowableMessageMatcher.java └── test │ └── java │ └── org │ └── hamcrest │ └── junit │ ├── AssertionTest.java │ ├── AssumptionTest.java │ ├── AssumptionViolatedExceptionTest.java │ ├── EventCollector.java │ ├── ExpectedExceptionTest.java │ └── internal │ └── StacktracePrintingMatcherTest.java └── tag-release /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | *.iml 3 | .idea/*.xml 4 | .idea/libraries/ 5 | .idea/.name 6 | .gradle/ 7 | out/ 8 | *.class 9 | *.jar 10 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 11 | hs_err_pid* 12 | 13 | gradle.properties 14 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/runConfigurations/All_Tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 19 | 20 | 21 | 22 | 23 | 24 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /.idea/runConfigurations/build_hamcrest_1_3__junit_4_12.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/runConfigurations/build_hamcrest_2_0_0_0__junit_4_12.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/scopes/scope_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - openjdk7 5 | - oraclejdk7 6 | - oraclejdk8 7 | 8 | script: 9 | - gradle clean test jar 10 | 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Hamcrest-JUnit 2 | 3 | Eclipse Public License - v 1.0 4 | 5 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 6 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 7 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 8 | 9 | 1. DEFINITIONS 10 | 11 | "Contribution" means: 12 | 13 | a) in the case of the initial Contributor, the initial code and 14 | documentation distributed under this Agreement, and 15 | b) in the case of each subsequent Contributor: 16 | 17 | i) changes to the Program, and 18 | 19 | ii) additions to the Program; 20 | 21 | where such changes and/or additions to the Program originate from and are 22 | distributed by that particular Contributor. A Contribution 'originates' from a 23 | Contributor if it was added to the Program by such Contributor itself or anyone 24 | acting on such Contributor's behalf. Contributions do not include additions to 25 | the Program which: (i) are separate modules of software distributed in 26 | conjunction with the Program under their own license agreement, and (ii) are 27 | not derivative works of the Program. 28 | 29 | "Contributor" means any person or entity that distributes the Program. 30 | 31 | "Licensed Patents " mean patent claims licensable by a Contributor which are 32 | necessarily infringed by the use or sale of its Contribution alone or when 33 | combined with the Program. 34 | 35 | "Program" means the Contributions distributed in accordance with this Agreement. 36 | 37 | "Recipient" means anyone who receives the Program under this Agreement, 38 | including all Contributors. 39 | 40 | 2. GRANT OF RIGHTS 41 | 42 | a) Subject to the terms of this Agreement, each Contributor hereby grants 43 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 44 | reproduce, prepare derivative works of, publicly display, publicly perform, 45 | distribute and sublicense the Contribution of such Contributor, if any, and 46 | such derivative works, in source code and object code form. 47 | 48 | b) Subject to the terms of this Agreement, each Contributor hereby grants 49 | Recipient a non-exclusive, worldwide, royalty-free patent license under 50 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 51 | transfer the Contribution of such Contributor, if any, in source code and 52 | object code form. This patent license shall apply to the combination of the 53 | Contribution and the Program if, at the time the Contribution is added by the 54 | Contributor, such addition of the Contribution causes such combination to be 55 | covered by the Licensed Patents. The patent license shall not apply to any 56 | other combinations which include the Contribution. No hardware per se is 57 | licensed hereunder. 58 | 59 | c) Recipient understands that although each Contributor grants the 60 | licenses to its Contributions set forth herein, no assurances are provided by 61 | any Contributor that the Program does not infringe the patent or other 62 | intellectual property rights of any other entity. Each Contributor disclaims 63 | any liability to Recipient for claims brought by any other entity based on 64 | infringement of intellectual property rights or otherwise. As a condition to 65 | exercising the rights and licenses granted hereunder, each Recipient hereby 66 | assumes sole responsibility to secure any other intellectual property rights 67 | needed, if any. For example, if a third party patent license is required to 68 | allow Recipient to distribute the Program, it is Recipient's responsibility to 69 | acquire that license before distributing the Program. 70 | 71 | d) Each Contributor represents that to its knowledge it has sufficient 72 | copyright rights in its Contribution, if any, to grant the copyright license 73 | set forth in this Agreement. 74 | 75 | 3. REQUIREMENTS 76 | 77 | A Contributor may choose to distribute the Program in object code form under 78 | its own license agreement, provided that: 79 | 80 | a) it complies with the terms and conditions of this Agreement; and 81 | 82 | b) its license agreement: 83 | 84 | i) effectively disclaims on behalf of all Contributors all warranties and 85 | conditions, express and implied, including warranties or conditions of title 86 | and non-infringement, and implied warranties or conditions of merchantability 87 | and fitness for a particular purpose; 88 | 89 | ii) effectively excludes on behalf of all Contributors all liability for 90 | damages, including direct, indirect, special, incidental and consequential 91 | damages, such as lost profits; 92 | 93 | iii) states that any provisions which differ from this Agreement are 94 | offered by that Contributor alone and not by any other party; and 95 | 96 | iv) states that source code for the Program is available from such 97 | Contributor, and informs licensees how to obtain it in a reasonable manner on 98 | or through a medium customarily used for software exchange. 99 | 100 | When the Program is made available in source code form: 101 | 102 | a) it must be made available under this Agreement; and 103 | 104 | b) a copy of this Agreement must be included with each copy of the 105 | Program. 106 | 107 | Contributors may not remove or alter any copyright notices contained within the 108 | Program. 109 | 110 | Each Contributor must identify itself as the originator of its Contribution, if 111 | any, in a manner that reasonably allows subsequent Recipients to identify the 112 | originator of the Contribution. 113 | 114 | 4. COMMERCIAL DISTRIBUTION 115 | 116 | Commercial distributors of software may accept certain responsibilities with 117 | respect to end users, business partners and the like. While this license is 118 | intended to facilitate the commercial use of the Program, the Contributor who 119 | includes the Program in a commercial product offering should do so in a manner 120 | which does not create potential liability for other Contributors. Therefore, if 121 | a Contributor includes the Program in a commercial product offering, such 122 | Contributor ("Commercial Contributor") hereby agrees to defend and indemnify 123 | every other Contributor ("Indemnified Contributor") against any losses, damages 124 | and costs (collectively "Losses") arising from claims, lawsuits and other legal 125 | actions brought by a third party against the Indemnified Contributor to the 126 | extent caused by the acts or omissions of such Commercial Contributor in 127 | connection with its distribution of the Program in a commercial product 128 | offering. The obligations in this section do not apply to any claims or Losses 129 | relating to any actual or alleged intellectual property infringement. In order 130 | to qualify, an Indemnified Contributor must: a) promptly notify the Commercial 131 | Contributor in writing of such claim, and b) allow the Commercial Contributor 132 | to control, and cooperate with the Commercial Contributor in, the defense and 133 | any related settlement negotiations. The Indemnified Contributor may 134 | participate in any such claim at its own expense. 135 | 136 | For example, a Contributor might include the Program in a commercial product 137 | offering, Product X. That Contributor is then a Commercial Contributor. If that 138 | Commercial Contributor then makes performance claims, or offers warranties 139 | related to Product X, those performance claims and warranties are such 140 | Commercial Contributor's responsibility alone. Under this section, the 141 | Commercial Contributor would have to defend claims against the other 142 | Contributors related to those performance claims and warranties, and if a court 143 | requires any other Contributor to pay any damages as a result, the Commercial 144 | Contributor must pay those damages. 145 | 146 | 5. NO WARRANTY 147 | 148 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN 149 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR 150 | IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, 151 | NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each 152 | Recipient is solely responsible for determining the appropriateness of using 153 | and distributing the Program and assumes all risks associated with its exercise 154 | of rights under this Agreement, including but not limited to the risks and 155 | costs of program errors, compliance with applicable laws, damage to or loss of 156 | data, programs or equipment, and unavailability or interruption of operations. 157 | 158 | 6. DISCLAIMER OF LIABILITY 159 | 160 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 161 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 162 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST 163 | PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 164 | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY 165 | WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS 166 | GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under applicable 171 | law, it shall not affect the validity or enforceability of the remainder of the 172 | terms of this Agreement, and without further action by the parties hereto, such 173 | provision shall be reformed to the minimum extent necessary to make such 174 | provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any 177 | entity (including a cross-claim or counterclaim in a lawsuit) alleging that the 178 | Program itself (excluding combinations of the Program with other software or 179 | hardware) infringes such Recipient's patent(s), then such Recipient's rights 180 | granted under Section 2(b) shall terminate as of the date such litigation is 181 | filed. 182 | 183 | All Recipient's rights under this Agreement shall terminate if it fails to 184 | comply with any of the material terms or conditions of this Agreement and does 185 | not cure such failure in a reasonable period of time after becoming aware of 186 | such noncompliance. If all Recipient's rights under this Agreement terminate, 187 | Recipient agrees to cease use and distribution of the Program as soon as 188 | reasonably practicable. However, Recipient's obligations under this Agreement 189 | and any licenses granted by Recipient relating to the Program shall continue 190 | and survive. 191 | 192 | Everyone is permitted to copy and distribute copies of this Agreement, but in 193 | order to avoid inconsistency the Agreement is copyrighted and may only be 194 | modified in the following manner. The Agreement Steward reserves the right to 195 | publish new versions (including revisions) of this Agreement from time to time. 196 | No one other than the Agreement Steward has the right to modify this Agreement. 197 | The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to 198 | serve as the Agreement Steward to a suitable separate entity. Each new version 199 | of the Agreement will be given a distinguishing version number. The Program 200 | (including Contributions) may always be distributed subject to the version of 201 | the Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly stated 204 | in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to 205 | the intellectual property of any Contributor under this Agreement, whether 206 | expressly, by implication, estoppel or otherwise. All rights in the Program not 207 | expressly granted under this Agreement are reserved. 208 | 209 | This Agreement is governed by the laws of the State of New York and the 210 | intellectual property laws of the United States of America. No party to this 211 | Agreement will bring a legal action under this Agreement more than one year 212 | after the cause of action arose. Each party waives its rights to a jury trial 213 | in any resulting litigation. 214 | 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | hamcrest-junit 2 | ============== 3 | 4 | Integration between Hamcrest and JUnit 5 | 6 | See https://github.com/hamcrest/JavaHamcrest/issues/92 7 | 8 | The Travis CI build is here: https://travis-ci.org/hamcrest/hamcrest-junit. [![Build Status](https://travis-ci.org/hamcrest/hamcrest-junit.svg?branch=master)](https://travis-ci.org/hamcrest/hamcrest-junit) 9 | 10 | Compatibility 11 | ------------- 12 | 13 | Recommended/compatible version of hamcrest-junit per Hamcrest and JUnit version: 14 | 15 | | | **JUnit 4.12** | 16 | |----------------------|---------------:| 17 | | **Hamcrest 1.3** | 1.0.0.1 | 18 | | **Hamcrest 2.0.0.0** | 2.0.0.0 | 19 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'maven' 3 | apply plugin: 'signing' 4 | 5 | archivesBaseName = "hamcrest-junit" 6 | group = "org.hamcrest" 7 | version = hasProperty("-version") ? property("-version") : "SNAPSHOT" 8 | 9 | def junit = System.getenv("junit") ?: 'junit:junit:4.12' 10 | def hamcrest = System.getenv("hamcrest") ?: 'org.hamcrest:java-hamcrest:2.0.0.0' 11 | 12 | sourceCompatibility = "1.7" 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | compile (junit) { transitive = false } 20 | compile (hamcrest) { transitive = false } 21 | } 22 | 23 | test { 24 | filter { 25 | includeTestsMatching "*Test" 26 | } 27 | } 28 | 29 | jar { 30 | manifest { 31 | attributes 'Implementation-Title': 'hamcrest-junit', 32 | 'Implementation-Vendor': 'hamcrest.org', 33 | 'Implementation-Version': version 34 | } 35 | } 36 | 37 | task sourcesJar(type: Jar) { 38 | classifier = 'sources' 39 | from sourceSets.main.allSource 40 | } 41 | 42 | task javadocJar(type: Jar, dependsOn: javadoc) { 43 | classifier = 'javadoc' 44 | from javadoc 45 | } 46 | 47 | artifacts { 48 | archives jar, sourcesJar, javadocJar 49 | } 50 | 51 | 52 | signing { 53 | required { gradle.taskGraph.hasTask("uploadArchives") } 54 | sign configurations.archives 55 | } 56 | 57 | String publishUsername = hasProperty("ossrhUsername") ? property("ossrhUsername") : "" 58 | String publishPassword = hasProperty("ossrhPassword") ? property("ossrhPassword") : "" 59 | 60 | uploadArchives { 61 | repositories.mavenDeployer { 62 | beforeDeployment { deployment -> signing.signPom(deployment) } 63 | 64 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 65 | authentication(userName: publishUsername, password: publishPassword) 66 | } 67 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 68 | authentication(userName: publishUsername, password: publishPassword) 69 | } 70 | 71 | pom.project { 72 | name 'Hamcrest JUnit' 73 | packaging 'jar' 74 | description 'Classes to use Hamcrest matchers within JUnit tests' 75 | url 'https://github.com/hamcrest/hamcrest-junit' 76 | 77 | scm { 78 | connection 'git@github.com:hamcrest/hamcrest-junit.git' 79 | url 'https://github.com/hamcrest/hamcrest-junit' 80 | } 81 | 82 | licenses { 83 | license { 84 | name 'Eclipse Public License - v 1.0' 85 | url 'http://opensource.org/licenses/EPL-1.0' 86 | } 87 | } 88 | 89 | developers { 90 | developer { 91 | id 'npryce' 92 | name 'Nat Pryce' 93 | } 94 | developer { 95 | id 'sf105' 96 | name 'Steve Freeman' 97 | } 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hamcrest/hamcrest-junit/5e02d55230b560f255433bcc490afaeda9e1a043/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jun 01 17:51:01 CEST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /publish-release: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | required_javac_version=1.7.0 5 | 6 | javac_version=`javac -version 2>&1 | cut -c 7-` 7 | case ${javac_version} in 8 | ${required_javac_version}_*) 9 | echo building with java ${javac_version} 10 | ;; 11 | *) 12 | echo ERROR found Java ${javac_version}, requires ${required_javac_version} 13 | exit 1 14 | ;; 15 | esac 16 | 17 | version=`git describe --always --tags --match 'v*' --dirty="_patched" | cut -c 2-` 18 | `dirname $0`/gradlew -P-version=$version clean uploadArchives "$@" 19 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'hamcrest-junit' 2 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/ErrorCollector.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import static org.hamcrest.junit.MatcherAssert.assertThat; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.concurrent.Callable; 8 | 9 | import org.hamcrest.Matcher; 10 | import org.junit.rules.Verifier; 11 | import org.junit.runners.model.MultipleFailureException; 12 | 13 | /** 14 | * The ErrorCollector rule allows execution of a test to continue after the 15 | * first problem is found (for example, to collect _all_ the incorrect rows in a 16 | * table, and report them all at once): 17 | * 18 | *
19 |  * public static class UsesErrorCollectorTwice {
20 |  * 	@Rule
21 |  * 	public ErrorCollector collector= new ErrorCollector();
22 |  *
23 |  * @Test
24 |  * public void example() {
25 |  *      collector.addError(new Throwable("first thing went wrong"));
26 |  *      collector.addError(new Throwable("second thing went wrong"));
27 |  *      collector.checkThat(getResult(), not(containsString("ERROR!")));
28 |  *      // all lines will run, and then a combined failure logged at the end.
29 |  *     }
30 |  * }
31 |  * 
32 | * 33 | * @since 4.7 34 | */ 35 | public class ErrorCollector extends Verifier { 36 | private List errors = new ArrayList(); 37 | 38 | @Override 39 | protected void verify() throws Throwable { 40 | MultipleFailureException.assertEmpty(errors); 41 | } 42 | 43 | /** 44 | * Adds a Throwable to the table. Execution continues, but the test will fail at the end. 45 | */ 46 | public void addError(Throwable error) { 47 | errors.add(error); 48 | } 49 | 50 | /** 51 | * Adds a failure to the table if {@code matcher} does not match {@code value}. 52 | * Execution continues, but the test will fail at the end if the match fails. 53 | */ 54 | public void checkThat(final T value, final Matcher matcher) { 55 | checkThat("", value, matcher); 56 | } 57 | 58 | /** 59 | * Adds a failure with the given {@code reason} 60 | * to the table if {@code matcher} does not match {@code value}. 61 | * Execution continues, but the test will fail at the end if the match fails. 62 | */ 63 | public void checkThat(final String reason, final T value, final Matcher matcher) { 64 | checkSucceeds(new Callable() { 65 | public Object call() throws Exception { 66 | assertThat(reason, value, matcher); 67 | return value; 68 | } 69 | }); 70 | } 71 | 72 | /** 73 | * Adds to the table the exception, if any, thrown from {@code callable}. 74 | * Execution continues, but the test will fail at the end if 75 | * {@code callable} threw an exception. 76 | */ 77 | public T checkSucceeds(Callable callable) { 78 | try { 79 | return callable.call(); 80 | } catch (Throwable e) { 81 | addError(e); 82 | return null; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/ExpectedException.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import static java.lang.String.format; 4 | import static org.hamcrest.CoreMatchers.containsString; 5 | import static org.hamcrest.CoreMatchers.instanceOf; 6 | import static org.junit.Assert.fail; 7 | import static org.hamcrest.junit.MatcherAssert.assertThat; 8 | import static org.hamcrest.junit.internal.ThrowableCauseMatcher.hasCause; 9 | import static org.hamcrest.junit.internal.ThrowableMessageMatcher.hasMessage; 10 | 11 | import org.hamcrest.Matcher; 12 | import org.hamcrest.StringDescription; 13 | import org.junit.AssumptionViolatedException; 14 | import org.junit.rules.TestRule; 15 | import org.junit.runners.model.Statement; 16 | 17 | /** 18 | * The {@code ExpectedException} rule allows you to verify that your code 19 | * throws a specific exception. 20 | * 21 | *

Usage

22 | * 23 | *
 public class SimpleExpectedExceptionTest {
 24 |  *     @Rule
 25 |  *     public ExpectedException thrown= ExpectedException.none();
 26 |  *
 27 |  *     @Test
 28 |  *     public void throwsNothing() {
 29 |  *         // no exception expected, none thrown: passes.
 30 |  *     }
 31 |  *
 32 |  *     @Test
 33 |  *     public void throwsExceptionWithSpecificType() {
 34 |  *         thrown.expect(NullPointerException.class);
 35 |  *         throw new NullPointerException();
 36 |  *     }
 37 |  * }
38 | * 39 | *

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

47 | * Instead of specifying the exception's type you can characterize the 48 | * expected exception based on other criterias, too: 49 | * 50 | *

    51 | *
  • The exception's message contains a specific text: {@link #expectMessage(String)}
  • 52 | *
  • The exception's message complies with a Hamcrest matcher: {@link #expectMessage(Matcher)}
  • 53 | *
  • The exception's cause complies with a Hamcrest matcher: {@link #expectCause(Matcher)}
  • 54 | *
  • The exception itself complies with a Hamcrest matcher: {@link #expect(Matcher)}
  • 55 | *
56 | * 57 | *

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

 @Test
 61 |  * public void throwsException() {
 62 |  *     thrown.expect(NullPointerException.class);
 63 |  *     thrown.expectMessage("happened");
 64 |  *     throw new NullPointerException("What happened?");
 65 |  * }
66 | * 67 | *

AssumptionViolatedExceptions

68 | *

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

 @Test
 77 |  * public void ignoredBecauseOfFailedAssumption() {
 78 |  *     assumeTrue(false); // throws AssumptionViolatedException
 79 |  *     thrown.expect(NullPointerException.class);
 80 |  * }
81 | * 82 | *

AssertionErrors

83 | * 84 | *

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

 @Test
 91 |  * public void throwsUnhandled() {
 92 |  *     assertTrue(false); // throws AssertionError
 93 |  *     thrown.expect(NullPointerException.class);
 94 |  * }
95 | * 96 | *

Missing Exceptions

97 | *

98 | * By default missing exceptions are reported with an error message 99 | * like "Expected test to throw an instance of foo". You can configure a different 100 | * message by means of {@link #reportMissingExceptionWithMessage(String)}. You 101 | * can use a {@code %s} placeholder for the description of the expected 102 | * exception. E.g. "Test doesn't throw %s." will fail with the error message 103 | * "Test doesn't throw an instance of foo.". 104 | * 105 | * @since 4.7 106 | */ 107 | public class ExpectedException implements TestRule { 108 | /** 109 | * Returns a {@linkplain TestRule rule} that expects no exception to 110 | * be thrown (identical to behavior without this rule). 111 | */ 112 | public static ExpectedException none() { 113 | return new ExpectedException(); 114 | } 115 | 116 | private final ExpectedExceptionMatcherBuilder matcherBuilder = new ExpectedExceptionMatcherBuilder(); 117 | 118 | private String missingExceptionMessage= "Expected test to throw %s"; 119 | 120 | private ExpectedException() { 121 | } 122 | 123 | /** 124 | * This method does nothing. Don't use it. 125 | * @deprecated AssertionErrors are handled by default since JUnit 4.12. Just 126 | * like in JUnit <= 4.10. 127 | */ 128 | @Deprecated 129 | public ExpectedException handleAssertionErrors() { 130 | return this; 131 | } 132 | 133 | /** 134 | * This method does nothing. Don't use it. 135 | * @deprecated AssumptionViolatedExceptions are handled by default since 136 | * JUnit 4.12. Just like in JUnit <= 4.10. 137 | */ 138 | @Deprecated 139 | public ExpectedException handleAssumptionViolatedExceptions() { 140 | return this; 141 | } 142 | 143 | /** 144 | * Specifies the failure message for tests that are expected to throw 145 | * an exception but do not throw any. You can use a {@code %s} placeholder for 146 | * the description of the expected exception. E.g. "Test doesn't throw %s." 147 | * will fail with the error message 148 | * "Test doesn't throw an instance of foo.". 149 | * 150 | * @param message exception detail message 151 | * @return the rule itself 152 | */ 153 | public ExpectedException reportMissingExceptionWithMessage(String message) { 154 | missingExceptionMessage = message; 155 | return this; 156 | } 157 | 158 | public Statement apply(Statement base, 159 | org.junit.runner.Description description) { 160 | return new ExpectedExceptionStatement(base); 161 | } 162 | 163 | /** 164 | * Verify that your code throws an exception that is matched by 165 | * a Hamcrest matcher. 166 | *

 @Test
167 |      * public void throwsExceptionThatCompliesWithMatcher() {
168 |      *     NullPointerException e = new NullPointerException();
169 |      *     thrown.expect(is(e));
170 |      *     throw e;
171 |      * }
172 | */ 173 | public void expect(Matcher matcher) { 174 | matcherBuilder.add(matcher); 175 | } 176 | 177 | /** 178 | * Verify that your code throws an exception that is an 179 | * instance of specific {@code type}. 180 | *
 @Test
181 |      * public void throwsExceptionWithSpecificType() {
182 |      *     thrown.expect(NullPointerException.class);
183 |      *     throw new NullPointerException();
184 |      * }
185 | */ 186 | public void expect(Class type) { 187 | expect(instanceOf(type)); 188 | } 189 | 190 | /** 191 | * Verify that your code throws an exception whose message contains 192 | * a specific text. 193 | *
 @Test
194 |      * public void throwsExceptionWhoseMessageContainsSpecificText() {
195 |      *     thrown.expectMessage("happened");
196 |      *     throw new NullPointerException("What happened?");
197 |      * }
198 | */ 199 | public void expectMessage(String substring) { 200 | expectMessage(containsString(substring)); 201 | } 202 | 203 | /** 204 | * Verify that your code throws an exception whose message is matched 205 | * by a Hamcrest matcher. 206 | *
 @Test
207 |      * public void throwsExceptionWhoseMessageCompliesWithMatcher() {
208 |      *     thrown.expectMessage(startsWith("What"));
209 |      *     throw new NullPointerException("What happened?");
210 |      * }
211 | */ 212 | public void expectMessage(Matcher matcher) { 213 | expect(hasMessage(matcher)); 214 | } 215 | 216 | /** 217 | * Verify that your code throws an exception whose cause is matched by 218 | * a Hamcrest matcher. 219 | *
 @Test
220 |      * public void throwsExceptionWhoseCauseCompliesWithMatcher() {
221 |      *     NullPointerException expectedCause = new NullPointerException();
222 |      *     thrown.expectCause(is(expectedCause));
223 |      *     throw new IllegalArgumentException("What happened?", cause);
224 |      * }
225 | */ 226 | public void expectCause(Matcher expectedCause) { 227 | expect(hasCause(expectedCause)); 228 | } 229 | 230 | private class ExpectedExceptionStatement extends Statement { 231 | private final Statement next; 232 | 233 | public ExpectedExceptionStatement(Statement base) { 234 | next = base; 235 | } 236 | 237 | @Override 238 | public void evaluate() throws Throwable { 239 | try { 240 | next.evaluate(); 241 | } catch (Throwable e) { 242 | handleException(e); 243 | return; 244 | } 245 | if (isAnyExceptionExpected()) { 246 | failDueToMissingException(); 247 | } 248 | } 249 | } 250 | 251 | private void handleException(Throwable e) throws Throwable { 252 | if (isAnyExceptionExpected()) { 253 | assertThat(e, matcherBuilder.build()); 254 | } else { 255 | throw e; 256 | } 257 | } 258 | 259 | private boolean isAnyExceptionExpected() { 260 | return matcherBuilder.expectsThrowable(); 261 | } 262 | 263 | private void failDueToMissingException() throws AssertionError { 264 | fail(missingExceptionMessage()); 265 | } 266 | 267 | private String missingExceptionMessage() { 268 | String expectation= StringDescription.toString(matcherBuilder.build()); 269 | return format(missingExceptionMessage, expectation); 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/ExpectedExceptionMatcherBuilder.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import static org.hamcrest.CoreMatchers.allOf; 4 | import static org.hamcrest.junit.JUnitMatchers.isThrowable; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.hamcrest.Matcher; 10 | 11 | /** 12 | * Builds special matcher used by {@link ExpectedException}. 13 | */ 14 | class ExpectedExceptionMatcherBuilder { 15 | 16 | private final List> matchers = new ArrayList>(); 17 | 18 | void add(Matcher matcher) { 19 | matchers.add(matcher); 20 | } 21 | 22 | boolean expectsThrowable() { 23 | return !matchers.isEmpty(); 24 | } 25 | 26 | Matcher build() { 27 | return isThrowable(allOfTheMatchers()); 28 | } 29 | 30 | private Matcher allOfTheMatchers() { 31 | if (matchers.size() == 1) { 32 | return cast(matchers.get(0)); 33 | } 34 | return allOf(castedMatchers()); 35 | } 36 | 37 | @SuppressWarnings({"unchecked", "rawtypes"}) 38 | private List> castedMatchers() { 39 | return new ArrayList>((List) matchers); 40 | } 41 | 42 | @SuppressWarnings("unchecked") 43 | private Matcher cast(Matcher singleMatcher) { 44 | return (Matcher) singleMatcher; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/JUnitMatchers.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import org.hamcrest.CoreMatchers; 4 | import org.hamcrest.Matcher; 5 | import org.hamcrest.core.CombinableMatcher.CombinableBothMatcher; 6 | import org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher; 7 | import org.hamcrest.junit.internal.StacktracePrintingMatcher; 8 | 9 | /** 10 | * Convenience import class: these are useful matchers for use with the assertThat method, but they are 11 | * not currently included in the basic CoreMatchers class from hamcrest. 12 | * 13 | * @since 4.4 14 | */ 15 | public class JUnitMatchers { 16 | /** 17 | * @return A matcher matching any collection containing element 18 | * @deprecated Please use {@link CoreMatchers#hasItem(Object)} instead. 19 | */ 20 | @Deprecated 21 | public static Matcher> hasItem(T element) { 22 | return CoreMatchers.hasItem(element); 23 | } 24 | 25 | /** 26 | * @return A matcher matching any collection containing an element matching elementMatcher 27 | * @deprecated Please use {@link CoreMatchers#hasItem(Matcher)} instead. 28 | */ 29 | @Deprecated 30 | public static Matcher> hasItem(Matcher elementMatcher) { 31 | return CoreMatchers.hasItem(elementMatcher); 32 | } 33 | 34 | /** 35 | * @return A matcher matching any collection containing every element in elements 36 | * @deprecated Please use {@link CoreMatchers#hasItems(Object...)} instead. 37 | */ 38 | @Deprecated 39 | public static Matcher> hasItems(T... elements) { 40 | return CoreMatchers.hasItems(elements); 41 | } 42 | 43 | /** 44 | * @return A matcher matching any collection containing at least one element that matches 45 | * each matcher in elementMatcher (this may be one element matching all matchers, 46 | * or different elements matching each matcher) 47 | * @deprecated Please use {@link CoreMatchers#hasItems(Matcher...)} instead. 48 | */ 49 | @Deprecated 50 | public static Matcher> hasItems(Matcher... elementMatchers) { 51 | return CoreMatchers.hasItems(elementMatchers); 52 | } 53 | 54 | /** 55 | * @return A matcher matching any collection in which every element matches elementMatcher 56 | * @deprecated Please use {@link CoreMatchers#everyItem(Matcher)} instead. 57 | */ 58 | @Deprecated 59 | public static Matcher> everyItem(final Matcher elementMatcher) { 60 | return CoreMatchers.everyItem(elementMatcher); 61 | } 62 | 63 | /** 64 | * @return a matcher matching any string that contains substring 65 | * @deprecated Please use {@link CoreMatchers#containsString(String)} instead. 66 | */ 67 | @Deprecated 68 | public static Matcher containsString(java.lang.String substring) { 69 | return CoreMatchers.containsString(substring); 70 | } 71 | 72 | /** 73 | * This is useful for fluently combining matchers that must both pass. For example: 74 | *
 75 |      *   assertThat(string, both(containsString("a")).and(containsString("b")));
 76 |      * 
77 | * 78 | * @deprecated Please use {@link CoreMatchers#both(Matcher)} instead. 79 | */ 80 | @Deprecated 81 | public static CombinableBothMatcher both(Matcher matcher) { 82 | return CoreMatchers.both(matcher); 83 | } 84 | 85 | /** 86 | * This is useful for fluently combining matchers where either may pass, for example: 87 | *
 88 |      *   assertThat(string, either(containsString("a")).or(containsString("b")));
 89 |      * 
90 | * 91 | * @deprecated Please use {@link CoreMatchers#either(Matcher)} instead. 92 | */ 93 | @Deprecated 94 | public static CombinableEitherMatcher either(Matcher matcher) { 95 | return CoreMatchers.either(matcher); 96 | } 97 | 98 | /** 99 | * @return A matcher that delegates to throwableMatcher and in addition 100 | * appends the stacktrace of the actual Throwable in case of a mismatch. 101 | */ 102 | public static Matcher isThrowable(Matcher throwableMatcher) { 103 | return StacktracePrintingMatcher.isThrowable(throwableMatcher); 104 | } 105 | 106 | /** 107 | * @return A matcher that delegates to exceptionMatcher and in addition 108 | * appends the stacktrace of the actual Exception in case of a mismatch. 109 | */ 110 | public static Matcher isException(Matcher exceptionMatcher) { 111 | return StacktracePrintingMatcher.isException(exceptionMatcher); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/MatcherAssert.java: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2000-2006 hamcrest.org 2 | */ 3 | package org.hamcrest.junit; 4 | 5 | 6 | import org.hamcrest.Matcher; 7 | import org.hamcrest.junit.internal.Matching; 8 | import org.hamcrest.junit.internal.MismatchAction; 9 | 10 | public class MatcherAssert { 11 | public static void assertThat(T actual, Matcher matcher) { 12 | assertThat("", actual, matcher); 13 | } 14 | 15 | public static void assertThat(String message, T actual, Matcher matcher) { 16 | Matching.checkMatch(message, actual, matcher, new MismatchAction() { 17 | @Override 18 | public void mismatch(String description) { 19 | throw new AssertionError(description); 20 | } 21 | }); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/MatcherAssume.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import org.hamcrest.Matcher; 4 | import org.hamcrest.junit.internal.Matching; 5 | import org.hamcrest.junit.internal.MismatchAction; 6 | import org.junit.AssumptionViolatedException; 7 | 8 | /** 9 | * A set of methods useful for stating assumptions about the conditions in which a test is meaningful. 10 | * A failed assumption does not mean the code is broken, but that the test provides no useful information. 11 | * The default JUnit runner treats tests with failing assumptions as ignored. Custom runners may behave differently. 12 | * 13 | * For example: 14 | *
15 |  * // only provides information if database is reachable.
16 |  * \@Test public void calculateTotalSalary() {
17 |  *    DBConnection dbc = Database.connect();
18 |  *    assumeNotNull(dbc);
19 |  *    // ...
20 |  * }
21 |  * 
22 | * These methods can be used directly: Assume.assumeTrue(...), however, they 23 | * read better if they are referenced through static import: 24 | *
25 |  * import static org.junit.Assume.*;
26 |  *    ...
27 |  *    assumeTrue(...);
28 |  * 
29 | * 30 | * @since 4.4 31 | */ 32 | public class MatcherAssume { 33 | /** 34 | * Call to assume that actual satisfies the condition specified by matcher. 35 | * If not, the test halts and is ignored. 36 | * Example: 37 | *
:
38 |      *   assumeThat(1, equalTo(1)); // passes
39 |      *   foo(); // will execute
40 |      *   assumeThat(0, equalTo(1)); // assumption failure! test halts
41 |      *   int x = 1 / 0; // will never execute
42 |      * 
43 | * 44 | * @param the static type accepted by the matcher (this can flag obvious compile-time problems such as assumeThat(1, is("a"))} 45 | * @param actual the computed value being compared 46 | * @param matcher an expression, built of {@link Matcher}s, specifying allowed values 47 | * @see org.hamcrest.Matcher 48 | * @see JUnitMatchers 49 | */ 50 | public static void assumeThat(T actual, Matcher matcher) { 51 | assumeThat("", actual, matcher); 52 | } 53 | 54 | /** 55 | * Call to assume that actual satisfies the condition specified by matcher. 56 | * If not, the test halts and is ignored. 57 | * Example: 58 | *
:
59 |      *   assumeThat(1, is(1)); // passes
60 |      *   foo(); // will execute
61 |      *   assumeThat(0, is(1)); // assumption failure! test halts
62 |      *   int x = 1 / 0; // will never execute
63 |      * 
64 | * 65 | * @param the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} 66 | * @param actual the computed value being compared 67 | * @param matcher an expression, built of {@link Matcher}s, specifying allowed values 68 | * @see org.hamcrest.CoreMatchers 69 | * @see JUnitMatchers 70 | */ 71 | public static void assumeThat(String message, T actual, Matcher matcher) { 72 | Matching.checkMatch(message, actual, matcher, new MismatchAction() { 73 | @Override 74 | public void mismatch(String description) { 75 | throw new AssumptionViolatedException(description); 76 | } 77 | }); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/internal/Matching.java: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2000-2006 hamcrest.org 2 | */ 3 | package org.hamcrest.junit.internal; 4 | 5 | 6 | import org.hamcrest.Description; 7 | import org.hamcrest.Matcher; 8 | import org.hamcrest.StringDescription; 9 | 10 | public class Matching { 11 | public static void checkMatch(String reason, T actual, Matcher matcher, MismatchAction action) { 12 | if (!matcher.matches(actual)) { 13 | Description description = new StringDescription(); 14 | description.appendText(reason) 15 | .appendText("\nExpected: ") 16 | .appendDescriptionOf(matcher) 17 | .appendText("\n but: "); 18 | matcher.describeMismatch(actual, description); 19 | 20 | action.mismatch(description.toString()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/internal/MismatchAction.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit.internal; 2 | 3 | public interface MismatchAction { 4 | void mismatch(String description); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/internal/StacktracePrintingMatcher.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit.internal; 2 | 3 | import java.io.PrintWriter; 4 | import java.io.StringWriter; 5 | 6 | import org.hamcrest.Description; 7 | import org.hamcrest.Matcher; 8 | 9 | /** 10 | * A matcher that delegates to throwableMatcher and in addition appends the 11 | * stacktrace of the actual Throwable in case of a mismatch. 12 | */ 13 | public class StacktracePrintingMatcher extends 14 | org.hamcrest.TypeSafeMatcher { 15 | 16 | private final Matcher throwableMatcher; 17 | 18 | public StacktracePrintingMatcher(Matcher throwableMatcher) { 19 | this.throwableMatcher = throwableMatcher; 20 | } 21 | 22 | public void describeTo(Description description) { 23 | throwableMatcher.describeTo(description); 24 | } 25 | 26 | @Override 27 | protected boolean matchesSafely(T item) { 28 | return throwableMatcher.matches(item); 29 | } 30 | 31 | @Override 32 | protected void describeMismatchSafely(T item, Description description) { 33 | throwableMatcher.describeMismatch(item, description); 34 | description.appendText("\nStacktrace was: "); 35 | description.appendText(readStacktrace(item)); 36 | } 37 | 38 | private String readStacktrace(Throwable throwable) { 39 | StringWriter stringWriter = new StringWriter(); 40 | throwable.printStackTrace(new PrintWriter(stringWriter)); 41 | return stringWriter.toString(); 42 | } 43 | 44 | public static Matcher isThrowable( 45 | Matcher throwableMatcher) { 46 | return new StacktracePrintingMatcher(throwableMatcher); 47 | } 48 | 49 | public static Matcher isException( 50 | Matcher exceptionMatcher) { 51 | return new StacktracePrintingMatcher(exceptionMatcher); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/internal/ThrowableCauseMatcher.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit.internal; 2 | 3 | import org.hamcrest.*; 4 | 5 | public class ThrowableCauseMatcher extends FeatureMatcher { 6 | public ThrowableCauseMatcher(Matcher causeMatcher) { 7 | super(causeMatcher, "exception with cause", "cause"); 8 | } 9 | 10 | @Override 11 | protected Throwable featureValueOf(Throwable actual) { 12 | return actual.getCause(); 13 | } 14 | 15 | 16 | public static Matcher hasCause(final Matcher matcher) { 17 | return new ThrowableCauseMatcher(matcher); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/hamcrest/junit/internal/ThrowableMessageMatcher.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit.internal; 2 | 3 | import org.hamcrest.*; 4 | 5 | public class ThrowableMessageMatcher extends FeatureMatcher { 6 | public ThrowableMessageMatcher(Matcher subMatcher) { 7 | super(subMatcher, "exception with message", "message"); 8 | } 9 | 10 | 11 | @Override 12 | protected String featureValueOf(Throwable actual) { 13 | return actual.getMessage(); 14 | } 15 | 16 | public static Matcher hasMessage(final Matcher matcher) { 17 | return new ThrowableMessageMatcher(matcher); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/org/hamcrest/junit/AssertionTest.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.CoreMatchers.*; 6 | import static org.hamcrest.junit.MatcherAssert.assertThat; 7 | import static org.junit.Assert.assertEquals; 8 | 9 | /** 10 | * Tests for {@link org.hamcrest.junit.MatcherAssert} 11 | */ 12 | public class AssertionTest { 13 | @Test 14 | public void assertThatIncludesDescriptionOfTestedValueInErrorMessage() { 15 | String expected = "expected"; 16 | String actual = "actual"; 17 | 18 | String expectedMessage = "identifier\nExpected: \"expected\"\n but: was \"actual\""; 19 | 20 | try { 21 | assertThat("identifier", actual, equalTo(expected)); 22 | } catch (AssertionError e) { 23 | assertEquals(expectedMessage, e.getMessage()); 24 | } 25 | } 26 | 27 | @Test 28 | public void assertThatIncludesAdvancedMismatch() { 29 | String expectedMessage = "identifier\nExpected: is an instance of java.lang.Integer\n but: \"actual\" is a java.lang.String"; 30 | 31 | try { 32 | assertThat("identifier", "actual", is(instanceOf(Integer.class))); 33 | } catch (AssertionError e) { 34 | assertEquals(expectedMessage, e.getMessage()); 35 | } 36 | } 37 | 38 | @Test 39 | public void assertThatDescriptionCanBeElided() { 40 | String expected = "expected"; 41 | String actual = "actual"; 42 | 43 | String expectedMessage = "\nExpected: \"expected\"\n but: was \"actual\""; 44 | 45 | try { 46 | assertThat(actual, equalTo(expected)); 47 | } catch (AssertionError e) { 48 | assertEquals(expectedMessage, e.getMessage()); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/org/hamcrest/junit/AssumptionTest.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import org.hamcrest.Matcher; 4 | import org.hamcrest.StringDescription; 5 | import org.junit.Test; 6 | 7 | import static org.hamcrest.Matchers.equalTo; 8 | import static org.hamcrest.junit.MatcherAssume.assumeThat; 9 | import static org.junit.Assert.assertTrue; 10 | 11 | public class AssumptionTest { 12 | @Test 13 | public void failingAssumeThrowsPublicAssumptionViolatedException() { 14 | Matcher assumption = equalTo(4); 15 | 16 | try { 17 | assumeThat(3, assumption); 18 | } catch (org.junit.AssumptionViolatedException e) { 19 | assertTrue(e.getMessage().contains(StringDescription.toString(assumption))); 20 | } 21 | } 22 | 23 | @Test 24 | public void passingAssumeDoesNothing() { 25 | assumeThat(3, equalTo(3)); 26 | } 27 | 28 | 29 | @Test 30 | public void failingAssumeWithMessageReportsBothMessageAndMatcher() { 31 | String message = "Some random message string."; 32 | Matcher assumption = equalTo(4); 33 | 34 | try { 35 | assumeThat(message, 3, assumption); 36 | } catch (org.junit.AssumptionViolatedException e) { 37 | assertTrue(e.getMessage().contains(message)); 38 | assertTrue(e.getMessage().contains(StringDescription.toString(assumption))); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/org/hamcrest/junit/AssumptionViolatedExceptionTest.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import static org.hamcrest.CoreMatchers.containsString; 4 | import static org.hamcrest.CoreMatchers.is; 5 | import static org.hamcrest.CoreMatchers.notNullValue; 6 | import static org.hamcrest.junit.MatcherAssert.assertThat; 7 | import static org.hamcrest.junit.MatcherAssume.assumeThat; 8 | 9 | import org.hamcrest.Matcher; 10 | import org.hamcrest.StringDescription; 11 | import org.junit.AssumptionViolatedException; 12 | import org.junit.Test; 13 | import org.junit.experimental.theories.DataPoint; 14 | import org.junit.experimental.theories.Theories; 15 | import org.junit.experimental.theories.Theory; 16 | import org.junit.runner.RunWith; 17 | 18 | @RunWith(Theories.class) 19 | public class AssumptionViolatedExceptionTest { 20 | @DataPoint 21 | public static Integer TWO = 2; 22 | 23 | @DataPoint 24 | public static Matcher IS_THREE = is(3); 25 | 26 | @DataPoint 27 | public static Matcher NULL = null; 28 | 29 | @Theory 30 | public void toStringReportsMatcher(Integer actual, Matcher matcher) { 31 | assumeThat(matcher, notNullValue()); 32 | assertThat(new AssumptionViolatedException(actual, matcher).toString(), 33 | containsString(matcher.toString())); 34 | } 35 | 36 | @Theory 37 | public void toStringReportsValue(Integer actual, Matcher matcher) { 38 | assertThat(new AssumptionViolatedException(actual, matcher).toString(), 39 | containsString(String.valueOf(actual))); 40 | } 41 | 42 | @Test 43 | public void assumptionViolatedExceptionWithMatcherDescribesItself() { 44 | AssumptionViolatedException e = new AssumptionViolatedException(3, is(2)); 45 | assertThat(StringDescription.asString(e), is("got: <3>, expected: is <2>")); 46 | } 47 | 48 | @Test 49 | public void simpleAssumptionViolatedExceptionDescribesItself() { 50 | AssumptionViolatedException e = new AssumptionViolatedException("not enough money"); 51 | assertThat(StringDescription.asString(e), is("not enough money")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/org/hamcrest/junit/EventCollector.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import static org.hamcrest.CoreMatchers.allOf; 4 | import static org.hamcrest.core.IsEqual.equalTo; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.hamcrest.Matcher; 10 | import org.hamcrest.TypeSafeMatcher; 11 | import org.junit.runner.Description; 12 | import org.junit.runner.Result; 13 | import org.junit.runner.notification.Failure; 14 | import org.junit.runner.notification.RunListener; 15 | 16 | class EventCollector extends RunListener { 17 | static Matcher everyTestRunSuccessful() { 18 | return allOf(hasNoFailure(), hasNoAssumptionFailure()); 19 | } 20 | 21 | private static Matcher hasNumberOfFailures( 22 | final int numberOfFailures) { 23 | return new TypeSafeMatcher() { 24 | @Override 25 | public boolean matchesSafely(EventCollector item) { 26 | return item.fFailures.size() == numberOfFailures; 27 | } 28 | 29 | public void describeTo(org.hamcrest.Description description) { 30 | description.appendText("has "); 31 | description.appendValue(numberOfFailures); 32 | description.appendText(" failures"); 33 | } 34 | 35 | @Override 36 | protected void describeMismatchSafely(EventCollector item, 37 | org.hamcrest.Description description) { 38 | description.appendValue(item.fFailures.size()); 39 | description.appendText(" failures"); 40 | } 41 | }; 42 | } 43 | 44 | static Matcher hasSingleFailure() { 45 | return hasNumberOfFailures(1); 46 | } 47 | 48 | static Matcher hasNoFailure() { 49 | return hasNumberOfFailures(0); 50 | } 51 | 52 | private static Matcher hasNumberOfAssumptionFailures( 53 | final int numberOfFailures) { 54 | return new TypeSafeMatcher() { 55 | @Override 56 | public boolean matchesSafely(EventCollector item) { 57 | return item.fAssumptionFailures.size() == numberOfFailures; 58 | } 59 | 60 | public void describeTo(org.hamcrest.Description description) { 61 | description.appendText("has "); 62 | description.appendValue(numberOfFailures); 63 | description.appendText(" assumption failures"); 64 | } 65 | }; 66 | } 67 | 68 | static Matcher hasSingleAssumptionFailure() { 69 | return hasNumberOfAssumptionFailures(1); 70 | } 71 | 72 | static Matcher hasNoAssumptionFailure() { 73 | return hasNumberOfAssumptionFailures(0); 74 | } 75 | 76 | static Matcher hasSingleFailureWithMessage(String message) { 77 | return hasSingleFailureWithMessage(equalTo(message)); 78 | } 79 | 80 | static Matcher hasSingleFailureWithMessage( 81 | final Matcher messageMatcher) { 82 | return new TypeSafeMatcher() { 83 | @Override 84 | public boolean matchesSafely(EventCollector item) { 85 | return hasSingleFailure().matches(item) 86 | && messageMatcher.matches(item.fFailures.get(0) 87 | .getMessage()); 88 | } 89 | 90 | public void describeTo(org.hamcrest.Description description) { 91 | description.appendText("has single failure with message "); 92 | messageMatcher.describeTo(description); 93 | } 94 | 95 | @Override 96 | protected void describeMismatchSafely(EventCollector item, 97 | org.hamcrest.Description description) { 98 | description.appendText("was "); 99 | hasSingleFailure().describeMismatch(item, description); 100 | description.appendText(": "); 101 | boolean first= true; 102 | for (Failure f : item.fFailures) { 103 | if (!first) { 104 | description.appendText(" ,"); 105 | } 106 | description.appendText("'"); 107 | description.appendText(f.getMessage()); 108 | description.appendText("'"); 109 | first= false; 110 | } 111 | } 112 | }; 113 | } 114 | 115 | static Matcher failureIs(final Matcher exceptionMatcher) { 116 | return new TypeSafeMatcher() { 117 | @Override 118 | public boolean matchesSafely(EventCollector item) { 119 | for (Failure f : item.fFailures) { 120 | return exceptionMatcher.matches(f.getException()); 121 | } 122 | return false; 123 | } 124 | 125 | public void describeTo(org.hamcrest.Description description) { 126 | description.appendText("failure is "); 127 | exceptionMatcher.describeTo(description); 128 | } 129 | }; 130 | } 131 | 132 | private final List fTestRunsStarted = new ArrayList(); 133 | 134 | private final List fTestRunsFinished = new ArrayList(); 135 | 136 | private final List fTestsStarted = new ArrayList(); 137 | 138 | private final List fTestsFinished = new ArrayList(); 139 | 140 | private final List fFailures = new ArrayList(); 141 | 142 | private final List fAssumptionFailures = new ArrayList(); 143 | 144 | private final List fTestsIgnored = new ArrayList(); 145 | 146 | @Override 147 | public void testRunStarted(Description description) throws Exception { 148 | fTestRunsStarted.add(description); 149 | } 150 | 151 | @Override 152 | public void testRunFinished(Result result) throws Exception { 153 | fTestRunsFinished.add(result); 154 | } 155 | 156 | @Override 157 | public void testStarted(Description description) throws Exception { 158 | fTestsStarted.add(description); 159 | } 160 | 161 | @Override 162 | public void testFinished(Description description) throws Exception { 163 | fTestsFinished.add(description); 164 | } 165 | 166 | @Override 167 | public void testFailure(Failure failure) throws Exception { 168 | fFailures.add(failure); 169 | } 170 | 171 | @Override 172 | public void testAssumptionFailure(Failure failure) { 173 | fAssumptionFailures.add(failure); 174 | } 175 | 176 | @Override 177 | public void testIgnored(Description description) throws Exception { 178 | fTestsIgnored.add(description); 179 | } 180 | 181 | @Override 182 | public String toString() { 183 | return fTestRunsStarted.size() + " test runs started, " 184 | + fTestRunsFinished.size() + " test runs finished, " 185 | + fTestsStarted.size() + " tests started, " 186 | + fTestsFinished.size() + " tests finished, " 187 | + fFailures.size() + " failures, " 188 | + fAssumptionFailures.size() + " assumption failures, " 189 | + fTestsIgnored.size() + " tests ignored"; 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/test/java/org/hamcrest/junit/ExpectedExceptionTest.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit; 2 | 3 | import org.hamcrest.Matcher; 4 | import org.hamcrest.Matchers; 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.runner.JUnitCore; 8 | import org.junit.runner.RunWith; 9 | import org.junit.runners.Parameterized; 10 | import org.junit.runners.Parameterized.Parameters; 11 | 12 | import java.util.Collection; 13 | 14 | import static java.util.Arrays.asList; 15 | import static org.hamcrest.CoreMatchers.*; 16 | import static org.hamcrest.core.IsEqual.equalTo; 17 | import static org.hamcrest.junit.EventCollector.*; 18 | import static org.hamcrest.junit.ExpectedException.none; 19 | import static org.hamcrest.junit.MatcherAssert.assertThat; 20 | import static org.junit.Assert.fail; 21 | import static org.junit.Assume.assumeTrue; 22 | 23 | @RunWith(Parameterized.class) 24 | public class ExpectedExceptionTest { 25 | private static final String ARBITRARY_MESSAGE = "arbitrary message"; 26 | 27 | @Parameters(name= "{0}") 28 | public static Collection testsWithEventMatcher() { 29 | return asList(new Object[][]{ 30 | {EmptyTestExpectingNoException.class, everyTestRunSuccessful()}, 31 | {ThrowExceptionWithExpectedType.class, 32 | everyTestRunSuccessful()}, 33 | {ThrowExceptionWithExpectedPartOfMessage.class, 34 | everyTestRunSuccessful()}, 35 | { 36 | ThrowExceptionWithWrongType.class, 37 | hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException"))}, 38 | { 39 | HasWrongMessage.class, 40 | hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n" 41 | + " but: message was \"actualMessage\""))}, 42 | { 43 | ThrowNoExceptionButExpectExceptionWithType.class, 44 | hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException")}, 45 | {WronglyExpectsExceptionMessage.class, hasSingleFailure()}, 46 | {ExpectsSubstring.class, everyTestRunSuccessful()}, 47 | { 48 | ExpectsSubstringNullMessage.class, 49 | hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\""))}, 50 | {ExpectsMessageMatcher.class, everyTestRunSuccessful()}, 51 | { 52 | ExpectedMessageMatcherFails.class, 53 | hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\""))}, 54 | {ExpectsMatcher.class, everyTestRunSuccessful()}, 55 | {ExpectAssertionErrorWhichIsNotThrown.class, hasSingleFailure()}, 56 | {FailedAssumptionAndExpectException.class, 57 | hasSingleAssumptionFailure()}, 58 | {FailBeforeExpectingException.class, 59 | hasSingleFailureWithMessage(ARBITRARY_MESSAGE)}, 60 | { 61 | ExpectsMultipleMatchers.class, 62 | hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")"))}, 63 | {ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful()}, 64 | {ThrowExpectedNullCause.class, everyTestRunSuccessful()}, 65 | { 66 | ThrowUnexpectedCause.class, 67 | hasSingleFailureWithMessage(Matchers.allOf( 68 | startsWith("\nExpected: ("), 69 | containsString("exception with cause is "), 70 | containsString("cause was "), 71 | containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"), 72 | containsString("Caused by: java.lang.NullPointerException: an unexpected cause")))}, 73 | { 74 | UseNoCustomMessage.class, 75 | hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.IllegalArgumentException") }, 76 | { 77 | UseCustomMessageWithoutPlaceHolder.class, 78 | hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, 79 | { 80 | UseCustomMessageWithPlaceHolder.class, 81 | hasSingleFailureWithMessage(ARBITRARY_MESSAGE 82 | + " - an instance of java.lang.IllegalArgumentException") } 83 | }); 84 | } 85 | 86 | private final Class classUnderTest; 87 | 88 | private final Matcher matcher; 89 | 90 | public ExpectedExceptionTest(Class classUnderTest, 91 | Matcher matcher) { 92 | this.classUnderTest = classUnderTest; 93 | this.matcher = matcher; 94 | } 95 | 96 | @Test 97 | public void runTestAndVerifyResult() { 98 | EventCollector collector = new EventCollector(); 99 | JUnitCore core = new JUnitCore(); 100 | core.addListener(collector); 101 | core.run(classUnderTest); 102 | assertThat(collector, matcher); 103 | } 104 | 105 | public static class EmptyTestExpectingNoException { 106 | @Rule 107 | public ExpectedException thrown = none(); 108 | 109 | @Test 110 | public void throwsNothing() { 111 | } 112 | } 113 | 114 | public static class ThrowExceptionWithExpectedType { 115 | @Rule 116 | public ExpectedException thrown = none(); 117 | 118 | @Test 119 | public void throwsNullPointerException() { 120 | thrown.expect(NullPointerException.class); 121 | throw new NullPointerException(); 122 | } 123 | } 124 | 125 | public static class ThrowExceptionWithExpectedPartOfMessage { 126 | @Rule 127 | public ExpectedException thrown = none(); 128 | 129 | @Test 130 | public void throwsNullPointerExceptionWithMessage() { 131 | thrown.expect(NullPointerException.class); 132 | thrown.expectMessage(ARBITRARY_MESSAGE); 133 | throw new NullPointerException(ARBITRARY_MESSAGE + "something else"); 134 | } 135 | } 136 | 137 | public static class ThrowExceptionWithWrongType { 138 | @Rule 139 | public ExpectedException thrown = none(); 140 | 141 | @Test 142 | public void throwsNullPointerException() { 143 | thrown.expect(NullPointerException.class); 144 | throw new IllegalArgumentException(); 145 | } 146 | } 147 | 148 | public static class HasWrongMessage { 149 | @Rule 150 | public ExpectedException thrown = none(); 151 | 152 | @Test 153 | public void throwsNullPointerException() { 154 | thrown.expectMessage("expectedMessage"); 155 | throw new IllegalArgumentException("actualMessage"); 156 | } 157 | } 158 | 159 | public static class ThrowNoExceptionButExpectExceptionWithType { 160 | @Rule 161 | public ExpectedException thrown = none(); 162 | 163 | @Test 164 | public void doesntThrowNullPointerException() { 165 | thrown.expect(NullPointerException.class); 166 | } 167 | } 168 | 169 | public static class WronglyExpectsExceptionMessage { 170 | @Rule 171 | public ExpectedException thrown = none(); 172 | 173 | @Test 174 | public void doesntThrowAnything() { 175 | thrown.expectMessage("anything!"); 176 | } 177 | } 178 | 179 | public static class ExpectsSubstring { 180 | @Rule 181 | public ExpectedException thrown = none(); 182 | 183 | @Test 184 | public void throwsMore() { 185 | thrown.expectMessage("anything!"); 186 | throw new NullPointerException( 187 | "This could throw anything! (as long as it has the right substring)"); 188 | } 189 | } 190 | 191 | public static class ExpectsSubstringNullMessage { 192 | @Rule 193 | public ExpectedException thrown = none(); 194 | 195 | @Test 196 | public void throwsMore() { 197 | thrown.expectMessage("anything!"); 198 | throw new NullPointerException(); 199 | } 200 | } 201 | 202 | public static class ExpectsMessageMatcher { 203 | @Rule 204 | public ExpectedException thrown = none(); 205 | 206 | @Test 207 | public void throwsMore() { 208 | thrown.expectMessage(startsWith(ARBITRARY_MESSAGE)); 209 | throw new NullPointerException(ARBITRARY_MESSAGE + "!"); 210 | } 211 | } 212 | 213 | public static class ExpectedMessageMatcherFails { 214 | @Rule 215 | public ExpectedException thrown = none(); 216 | 217 | @Test 218 | public void throwsMore() { 219 | thrown.expectMessage(equalTo("Wrong start")); 220 | throw new NullPointerException("Back!"); 221 | } 222 | } 223 | 224 | public static class ExpectsMatcher { 225 | @Rule 226 | public ExpectedException thrown = none(); 227 | 228 | @Test 229 | public void throwsMore() { 230 | thrown.expect(any(Exception.class)); 231 | throw new NullPointerException("Ack!"); 232 | } 233 | } 234 | 235 | public static class ExpectsMultipleMatchers { 236 | @Rule 237 | public ExpectedException thrown = none(); 238 | 239 | @Test 240 | public void throwsMore() { 241 | thrown.expect(IllegalArgumentException.class); 242 | thrown.expectMessage("Ack!"); 243 | throw new NullPointerException("Ack!"); 244 | } 245 | } 246 | 247 | //https://github.com/junit-team/junit/pull/583 248 | public static class ExpectAssertionErrorWhichIsNotThrown { 249 | @Rule 250 | public ExpectedException thrown = none(); 251 | 252 | @Test 253 | public void fails() { 254 | thrown.expect(AssertionError.class); 255 | } 256 | } 257 | 258 | public static class FailBeforeExpectingException { 259 | @Rule 260 | public ExpectedException thrown = none(); 261 | 262 | @Test 263 | public void fails() { 264 | fail(ARBITRARY_MESSAGE); 265 | thrown.expect(IllegalArgumentException.class); 266 | } 267 | } 268 | 269 | public static class FailedAssumptionAndExpectException { 270 | @Rule 271 | public ExpectedException thrown = none(); 272 | 273 | @Test 274 | public void failedAssumption() { 275 | assumeTrue(false); 276 | thrown.expect(NullPointerException.class); 277 | } 278 | } 279 | 280 | public static class ThrowExceptionWithMatchingCause { 281 | @Rule 282 | public ExpectedException thrown = none(); 283 | 284 | @Test 285 | public void throwExceptionWithMatchingCause() { 286 | Throwable expectedCause = new NullPointerException("expected cause"); 287 | 288 | thrown.expect(IllegalArgumentException.class); 289 | thrown.expectMessage("Ack!"); 290 | thrown.expectCause(is(expectedCause)); 291 | 292 | throw new IllegalArgumentException("Ack!", expectedCause); 293 | } 294 | } 295 | 296 | public static class ThrowExpectedNullCause { 297 | @Rule 298 | public ExpectedException thrown = none(); 299 | 300 | @Test 301 | public void throwExpectedNullCause() { 302 | thrown.expect(IllegalArgumentException.class); 303 | thrown.expectMessage("Ack!"); 304 | thrown.expectCause(nullValue(Throwable.class)); 305 | 306 | throw new IllegalArgumentException("Ack!"); 307 | } 308 | } 309 | 310 | public static class ThrowUnexpectedCause { 311 | 312 | @Rule 313 | public ExpectedException thrown = ExpectedException.none(); 314 | 315 | @Test 316 | public void throwWithCause() { 317 | thrown.expect(IllegalArgumentException.class); 318 | thrown.expectMessage("Ack!"); 319 | thrown.expectCause(is((Throwable)new NullPointerException("expected cause"))); 320 | 321 | throw new IllegalArgumentException("Ack!", new NullPointerException("an unexpected cause")); 322 | } 323 | } 324 | 325 | public static class UseNoCustomMessage { 326 | 327 | @Rule 328 | public ExpectedException thrown= ExpectedException.none(); 329 | 330 | @Test 331 | public void noThrow() { 332 | thrown.expect(IllegalArgumentException.class); 333 | } 334 | } 335 | 336 | public static class UseCustomMessageWithPlaceHolder { 337 | 338 | @Rule 339 | public ExpectedException thrown = ExpectedException.none(); 340 | 341 | @Test 342 | public void noThrow() { 343 | thrown.expect(IllegalArgumentException.class); 344 | thrown.reportMissingExceptionWithMessage(ARBITRARY_MESSAGE 345 | + " - %s"); 346 | } 347 | } 348 | 349 | public static class UseCustomMessageWithoutPlaceHolder { 350 | 351 | @Rule 352 | public ExpectedException thrown= ExpectedException.none(); 353 | 354 | @Test 355 | public void noThrow() { 356 | thrown.expect(IllegalArgumentException.class); 357 | thrown.reportMissingExceptionWithMessage(ARBITRARY_MESSAGE); 358 | } 359 | } 360 | } 361 | -------------------------------------------------------------------------------- /src/test/java/org/hamcrest/junit/internal/StacktracePrintingMatcherTest.java: -------------------------------------------------------------------------------- 1 | package org.hamcrest.junit.internal; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.hamcrest.Matchers.*; 6 | import static org.hamcrest.junit.MatcherAssert.assertThat; 7 | import static org.hamcrest.junit.internal.StacktracePrintingMatcher.isException; 8 | import static org.hamcrest.junit.internal.StacktracePrintingMatcher.isThrowable; 9 | import static org.junit.Assert.assertFalse; 10 | import static org.junit.Assert.assertTrue; 11 | 12 | public class StacktracePrintingMatcherTest { 13 | 14 | @Test 15 | public void succeedsWhenInnerMatcherSucceeds() throws Exception { 16 | assertTrue(isThrowable(any(Throwable.class)).matches(new Exception())); 17 | } 18 | 19 | @Test 20 | public void failsWhenInnerMatcherFails() throws Exception { 21 | assertFalse(isException(notNullValue(Exception.class)).matches(null)); 22 | } 23 | 24 | @Test 25 | public void assertThatIncludesStacktrace() { 26 | Exception actual = new IllegalArgumentException("my message"); 27 | Exception expected = new NullPointerException(); 28 | 29 | try { 30 | assertThat(actual, isThrowable(equalTo(expected))); 31 | } catch (AssertionError e) { 32 | assertThat(e.getMessage(), containsString("Stacktrace was: java.lang.IllegalArgumentException: my message")); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tag-release: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | version=${1:?version} 3 | git tag -u releases@hamcrest.org v${version} -m "tagging version ${version}" 4 | --------------------------------------------------------------------------------