如何使用 Hamcrest assertThat() 匹配器在 Java 中創建 JUnit 測試用例 – 完整教程
已發表: 2022-02-05
如何使用Hamcrest for testing
? 前一段時間,我寫了一篇包含所有細節的 Hello World JUnit 文章。 在本教程中,我們將詳細介紹how to use Hamcrest to create JUnit
。
Hamcrest 是一個 Java testing framework
,匹配器與 JUnit 框架捆綁在一起,以創建更具可讀性的 Java 單元測試。 我今天試過了,我非常喜歡它。
非常簡單和完整的文檔使其完美。
如果您有以下任何問題,那麼您來對地方了:
- 使用 Eclipse 在 Java 中編寫 JUnit 測試用例
- 如何用Java編寫junit測試用例
- Java 中的示例 JUnit 測試用例
- 使用
Hamcrest Matchers
編寫 JUnit 測試用例 - JUnit 測試中
assertThat vs Assert
方法的優勢 - hamcrest
assertthat()
教程 - 使用 Hamcrest 進行測試
讓我們開始吧:
在 Eclipse 中創建 Java 類CrunchifyHemcrestJUnitTest.java
。 我們將創建 4 種不同類別的測試。
- 為
Java List
創建 JUnit 測試用例 - 為 Java Map 創建 JUnit 測試用例
- 為 Java 對象創建 JUnit 測試用例
- 為空檢查創建 JUnit 測試用例
以下是頂級 Hamcrest 匹配器:
- 是()
- 有項目()
- 有大小()
- 包含()
- 包含InAnyOrder()
下面的教程涵蓋了幾乎所有將一直通過的匹配器測試用例。 只需修改以創建誤報等。
您需要在項目中添加以下 maven 依賴項。
1 2 3 4 5 |
< dependency > < groupId > org . hamcrest < / groupId > < artifactId > hamcrest - all < / artifactId > < version > 1.3 < / version > < / dependency > |
只需將其添加到pom.xml
文件中。 如果您沒有看到 pom.xml,請按照本教程進行操作。

這是一個完整的Java代碼
只需右鍵單擊一個類並Run As
-> JUnit Test
。
CrunchifyHamcrestJUnitTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
package crunchify . com . java . tutorials ; import org . hamcrest . collection . IsEmptyCollection ; import org . hamcrest . collection . IsMapContaining ; import org . hamcrest . core . IsNull ; import org . junit . Test ; import java . util . * ; import static org . hamcrest . CoreMatchers . * ; import static org . hamcrest . MatcherAssert . assertThat ; import static org . hamcrest . Matchers . hasProperty ; import static org . hamcrest . collection . IsCollectionWithSize . hasSize ; import static org . hamcrest . collection . IsIterableContainingInAnyOrder . containsInAnyOrder ; import static org . hamcrest . collection . IsIterableContainingInOrder . contains ; /** * @author Crunchify.com * <p> * Hamcrest JUnit Tutorials by Crunchify.com * 1. Create JUnit testcases for Java List * 2. Create JUnit testcases for Java Map * 3. Create JUnit testcases for Java Object * 4. Create JUnit testcases for Null Check */ public class CrunchifyHamcrestJUnitTest { // Testcase-1: JUnit for List @Test public void crunchifyListJUnitTests ( ) { // List: An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. // The user can access elements by their integer index (position in the list), and search for elements in the list. List <String> company = Arrays . asList ( "Crunchify.com" , "Google.com" , "Facebook.com" ) ; // asList(): Returns a fixed-size list backed by the specified array. Changes made to the array will be visible in the returned list, // and changes made to the list will be visible in the array. // The returned list is Serializable and implements RandomAccess. List <String> crunchifyCompany = Arrays . asList ( "Crunchify.com" , "Google.com" , "Facebook.com" ) ; crunchifyLog ( "\n~~~~~~~~~~~JUnit List Check Test~~~~~~~~~~~" ) ; crunchifyLog ( "1) assertThat(company, is(crunchifyCompany)) check" ) ; // A shortcut to the frequently used is(equalTo(x)). assertThat ( company , is ( crunchifyCompany ) ) ; crunchifyLog ( "2) .hasItems() check" ) ; assertThat ( company , hasItems ( "Crunchify.com" ) ) ; crunchifyLog ( "3) .hasSize() check" ) ; assertThat ( company , hasSize ( 3 ) ) ; assertThat ( company . size ( ) , is ( 3 ) ) ; crunchifyLog ( "4) .contains() and .containsInAnyOrder() check" ) ; assertThat ( company , contains ( "Crunchify.com" , "Google.com" , "Facebook.com" ) ) ; assertThat ( company , containsInAnyOrder ( "Google.com" , "Crunchify.com" , "Facebook.com" ) ) ; // FAIL // assertThat(company, contains("Google.com", "Crunchify.com", "Facebook.com")); crunchifyLog ( "5) .empty() check" ) ; assertThat ( company , not ( IsEmptyCollection . empty ( ) ) ) ; assertThat ( new ArrayList < > ( ) , IsEmptyCollection . empty ( ) ) ; } private void crunchifyLog ( String crunchifyText ) { System . out . println ( crunchifyText ) ; } @Test public void crunchifyMapJUnitTests ( ) { Map < String , String > company = new HashMap < > ( ) ; company . put ( "C" , "Crunchify.com" ) ; company . put ( "G" , "Google.com" ) ; company . put ( "F" , "Facebook.com" ) ; // Map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. // This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface. Map < String , String > crunchifyCompany = new HashMap < > ( ) ; crunchifyCompany . put ( "C" , "Crunchify.com" ) ; // put(): Associates the specified value with the specified key in this map (optional operation). // If the map previously contained a mapping for the key, the old value is replaced by the specified value. // (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.) crunchifyCompany . put ( "G" , "Google.com" ) ; crunchifyCompany . put ( "F" , "Facebook.com" ) ; crunchifyLog ( "\n~~~~~~~~~~~ JUnit Map Check Test - All tests will PASS in our example ~~~~~~~~~~~" ) ; crunchifyLog ( "1) assertThat(company, is(crunchifyCompany) check" ) ; assertThat ( company , is ( crunchifyCompany ) ) ; crunchifyLog ( "2) assertThat(company.size(), is(3)) check" ) ; assertThat ( company . size ( ) , is ( 3 ) ) ; crunchifyLog ( "3) .hasEntry() check which creates a matcher for Maps matching at least one entry whose key equals the specified key & value." ) ; assertThat ( company , IsMapContaining . hasEntry ( "C" , "Crunchify.com" ) ) ; assertThat ( company , not ( IsMapContaining . hasEntry ( "G" , "Twitter.com" ) ) ) ; crunchifyLog ( "4) .hasKey() creates a matcher for Maps matching at least one key that is equal to the specified key." ) ; assertThat ( company , IsMapContaining . hasKey ( "F" ) ) ; crunchifyLog ( "5) .hasValue() creates a matcher for Maps matching at least one key that is equal to the specified value." ) ; assertThat ( company , IsMapContaining . hasValue ( "Crunchify.com" ) ) ; } @SuppressWarnings ( "unchecked" ) @Test public void crunchifyObjectJUnitTests ( ) { List <Company> list = Arrays . asList ( new Company ( "Crunchify" , 10 ) , new Company ( "Google" , 30000 ) ) ; assertThat ( list , hasItems ( new Company ( "Crunchify" , 10 ) , new Company ( "Google" , 30000 ) ) ) ; assertThat ( list , containsInAnyOrder ( new Company ( "Google" , 30000 ) , new Company ( "Crunchify" , 10 ) ) ) ; assertThat ( list , containsInAnyOrder ( hasProperty ( "name" , is ( "Google" ) ) , hasProperty ( "name" , is ( "Crunchify" ) ) ) ) ; crunchifyLog ( "\n~~~~~~~~~~~ JUnit Object Check Test Completed ~~~~~~~~~~~" ) ; } // Create Company Object public static class Company { public Company ( String name , int employeeCount ) { this . name = name ; this . employeeCount = employeeCount ; } private String name ; private int employeeCount ; public int getEmployeeCount ( ) { return employeeCount ; } public void setEmployeeCount ( int employeeCount ) { this . employeeCount = employeeCount ; } public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } // Test equal, override equals() and hashCode() @Override public boolean equals ( Object c ) { if ( this == c ) return true ; if ( c == null | | getClass ( ) ! = c . getClass ( ) ) return false ; Company fruit = ( Company ) c ; return employeeCount == fruit . employeeCount && Objects.equals(name, fruit.name); } @Override public int hashCode ( ) { return Objects . hash ( name , employeeCount ) ; } } @Test public void crunchifyNullCheckJUnitTest ( ) { // Two ways to check isNull assertThat ( null , is ( nullValue ( ) ) ) ; assertThat ( null , is ( IsNull . nullValue ( ) ) ) ; // Two ways to check isNotNull assertThat ( "crunchify" , is ( notNullValue ( ) ) ) ; assertThat ( "crunchify" , is ( IsNull . notNullValue ( ) ) ) ; crunchifyLog ( "\n~~~~~~~~~~~ JUnit Null Check Test Completed ~~~~~~~~~~~" ) ; } } |
Eclipse 控制台輸出:
只需將上面的程序作為 Java 應用程序運行,您應該會看到如下所示的結果。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit Object Check Test Completed ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit Null Check Test Completed ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit List Check Test ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ 1 ) assertThat ( company , is ( crunchifyCompany ) ) check 2 ) . hasItems ( ) check 3 ) . hasSize ( ) check ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit List Check Test ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ 1 ) assertThat ( company , is ( crunchifyCompany ) ) check 2 ) . hasItems ( ) check 3 ) . hasSize ( ) check 4 ) . contains ( ) and . containsInAnyOrder ( ) check 5 ) . empty ( ) check ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit Map Check Test - All tests will PASS in our example ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ 1 ) assertThat ( company , is ( crunchifyCompany ) check 2 ) assertThat ( company . size ( ) , is ( 3 ) ) check 3 ) . hasEntry ( ) check which creates a matcher for Maps matching at least one entry whose key equals the specified key & value . 4 ) . hasKey ( ) creates a matcher for Maps matching at least one key that is equal to the specified key . 5 ) . hasValue ( ) creates a matcher for Maps matching at least one key that is equal to the specified value . ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit Object Check Test Completed ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ JUnit Null Check Test Completed ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Process finished with exit code 0 |

如果您在運行上述程序時遇到任何問題,請告訴我們。