Best junit code snippet using org.hamcrest.CoreMatchers.startsWith
Source:DemoServiceTest.java
...34import static org.hamcrest.CoreMatchers.not;35import static org.hamcrest.CoreMatchers.notNullValue;36import static org.hamcrest.CoreMatchers.nullValue;37import static org.hamcrest.CoreMatchers.sameInstance;38import static org.hamcrest.CoreMatchers.startsWith;39import static org.hamcrest.CoreMatchers.theInstance;40import static org.hamcrest.Matchers.array;41import static org.hamcrest.Matchers.arrayContaining;42import static org.hamcrest.Matchers.arrayContainingInAnyOrder;43import static org.hamcrest.Matchers.arrayWithSize;44import static org.hamcrest.Matchers.closeTo;45import static org.hamcrest.Matchers.comparesEqualTo;46import static org.hamcrest.Matchers.contains;47import static org.hamcrest.Matchers.containsInAnyOrder;48import static org.hamcrest.Matchers.empty;49import static org.hamcrest.Matchers.emptyArray;50import static org.hamcrest.Matchers.emptyCollectionOf;51import static org.hamcrest.Matchers.emptyIterable;52import static org.hamcrest.Matchers.equalToIgnoringCase;53import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;54import static org.hamcrest.Matchers.eventFrom;55import static org.hamcrest.Matchers.greaterThan;56import static org.hamcrest.Matchers.greaterThanOrEqualTo;57import static org.hamcrest.Matchers.hasEntry;58import static org.hamcrest.Matchers.hasItemInArray;59import static org.hamcrest.Matchers.hasKey;60import static org.hamcrest.Matchers.hasProperty;61import static org.hamcrest.Matchers.hasSize;62import static org.hamcrest.Matchers.hasToString;63import static org.hamcrest.Matchers.hasValue;64import static org.hamcrest.Matchers.isEmptyOrNullString;65import static org.hamcrest.Matchers.isEmptyString;66import static org.hamcrest.Matchers.isIn;67import static org.hamcrest.Matchers.isOneOf;68import static org.hamcrest.Matchers.iterableWithSize;69import static org.hamcrest.Matchers.lessThan;70import static org.hamcrest.Matchers.lessThanOrEqualTo;71import static org.hamcrest.Matchers.samePropertyValuesAs;72import static org.hamcrest.Matchers.stringContainsInOrder;73import static org.hamcrest.Matchers.typeCompatibleWith;74;75/**76 * Descriptionï¼ service unit test77 * Author: zhangm@seaskylight.com78 * Date: 2018/3/7 14:2379 */80public class DemoServiceTest extends BaseTest {81 @Autowired82 private DemoService demoService;83 @Test84 public void testHi() {85 String name = "test";86 Assert.assertEquals(demoService.hi(name), "hi:" + name);87 // å®é
å¼ï¼actualï¼ä¸ææå¼ï¼expectedï¼ç¸ç88 Assert.assertThat("hi:test", is(equalTo(demoService.hi(name))));89 // å¹é
ç»å®ç±»åçä»»ä½åé.90 Assert.assertThat("name", any(String.class));91 // å¹é
ä»»ä½ä¸è¥¿ã92 Assert.assertThat(5, anything());93 // è¾å
¥å®é
å¼å¤§äºæå®å¼94 Assert.assertThat(11, greaterThan(10));95 // è¾å
¥å®é
å¼å°äºæå®å¼96 Assert.assertThat(1, lessThan(2));97 // è¾å
¥æµè¯å¼å¤§äºæçäºæå®å¼98 Assert.assertThat(10, greaterThanOrEqualTo(10));99 // è¾å
¥æµè¯å¼å°äºæçäºæå®å¼100 Assert.assertThat(10, lessThanOrEqualTo(10));101 // æ°ç»çé¿åº¦å¿
é¡»ä¸å¹é
å¨çæ°éå¹é
ï¼å¹¶ä¸å®ä»¬ç顺åºå¾éè¦ã102 String[] strings = {"why", "hello", "there"};103 Assert.assertThat(strings, arrayContaining("why", "hello", "there"));104 // varargå¹é
å¨ï¼å¦æè¾å
¥String以ç»å®çåå符串ç»å°¾ï¼æè
å¼å¤´ï¼åå¹é
çå¹é
å¨ã以åç¸çã105 Assert.assertThat(strings, arrayContaining(startsWith("w"), equalTo("hello"), endsWith("re")));106 // å®ä»¬ç顺åºå¹¶ä¸éè¦107 Assert.assertThat(strings, arrayContainingInAnyOrder("hello", "there", "why"));108 Assert.assertThat(strings, arrayWithSize(3));109 // ç¨äºæ£æ¥æ°ç»æ¯å¦å
·æç¹å®é¿åº¦ã110 ArrayList<Object> objects = new ArrayList<>();111 objects.add(0, "o");112 objects.add(1, "a");113 objects.add(2, "b");114 objects.add(3, "c");115 Assert.assertThat(objects.toArray(), arrayWithSize(greaterThan(2)));116 // è¾å
¥Iterableå
·ææå®å¤§å°æ¶å¹é
æä¸æå®å¤§å°å¹é
117 Assert.assertThat(objects, iterableWithSize(4));118 // å¯ä»¥ä¸DoubleæBigDecimalä¸èµ·ä½¿ç¨çå¹é
å¨ï¼ä»¥æ£æ¥å¼æ¯å¦å¨ææå¼çæå®è¯¯å·®èå´å
ã119 Double i = 6.5;120 BigDecimal b = BigDecimal.valueOf(i);121 Assert.assertThat(i, closeTo(6, 0.5));122 Assert.assertThat(b, closeTo(BigDecimal.valueOf(6L), BigDecimal.valueOf(0.5d)));123 Assert.assertThat(BigDecimal.valueOf(600L), closeTo(BigDecimal.valueOf(650L), BigDecimal.valueOf(50L)));124 // è¾å
¥çå¹é
å¨å¼è¿å0ï¼åå¹é
å¨å°å¹é
ï¼å¦åå°ä¸å¹é
125 Assert.assertThat(i, comparesEqualTo(6.5));126 Assert.assertThat(i, equalTo(6.5));127 // æµè¯éåçå¼ï¼æ°ç¸å¹é
128 Assert.assertThat(Arrays.asList(strings), contains("why", "hello", "there"));129 // æµè¯éåçå¼ï¼æ°ç¸å¹é
ï¼é¡ºåºå¯ä»¥ä¸å130 Assert.assertThat(Arrays.asList(strings), containsInAnyOrder("hello", "why", "there"));131 // å符串æ¯å¦å
å«ç»å®çåå符串132 Assert.assertThat("value", containsString("l"));133 // å¹é
空éå134 ArrayList<Object> list = Lists.newArrayList();135 Assert.assertThat(list, empty());136 // å¦æè¾å
¥æ°ç»çé¿åº¦ä¸º0ï¼åå¹é
çå¹é
å¨137 Double[] doubles = new Double[0];138 Assert.assertThat(doubles, emptyArray());139 // Typesafeå¹é
å¨ï¼å¦æè¾å
¥éå为ç»å®ç±»åä¸ä¸ºç©ºï¼åå¹é
ã140 HashSet<String> set = new HashSet<>();141 Assert.assertThat(set, emptyCollectionOf(String.class));142 // å¦æè¾å
¥Iterable没æå¼ï¼åå¹é
çå¹é
å¨ã143 Assert.assertThat(set, emptyIterable());144 // Typesafe Matcherï¼å¦æè¾å
¥çIterable没æå¼å¹¶ä¸æ¯ç»å®ç±»åï¼åå¹é
ã145 Assert.assertThat(set, emptyCollectionOf(String.class));146 // å¦æè¾å
¥çStringå¼çäºæå®çStringè忽ç¥å¤§å°åï¼åå¹é
çå¹é
å¨ã147 Assert.assertThat("value", equalToIgnoringCase("VAlUe"));148 // è¾å
¥çStringå¼çäºæå®çStringèä¸å¹é
å¤ä½çç©ºæ ¼149 String testValue = "this is my value ";150 Assert.assertThat(testValue, equalToIgnoringWhiteSpace(" This Is My value"));151 // å¦æè¾å
¥EventObjectæ¥èªç»å®æºï¼åå¹é
å¨ãä¹å¯ä»¥æ¥åEventObjectæå®åç±»åçã152 Object source = new Object();153 EventObject testEvent = new EventObject(source);154 Assert.assertThat(testEvent, eventFrom(source));155 // EventObjectæå®åç±»åç156 EventObject menuEvent = new MenuEvent(source);157 Assert.assertThat(menuEvent, eventFrom(MenuEvent.class, source));158 // ç»å®æ å°å
å«ä¸æå®é®åå¼å¹é
çæ¡ç®159 HashMap<Integer, String> map = new HashMap<>();160 map.put(1, "hi");161 map.put(2, "hello");162 Assert.assertThat(map, hasEntry(2, "hello"));163 Assert.assertThat(map, hasEntry(greaterThan(1), startsWith("h")));164 // è¾å
¥Mapå
·æè³å°ä¸ä¸ªä¸æå®å¼æå¹é
项å¹é
çé®165 Assert.assertThat(map, hasKey(1));166 Assert.assertThat(map, hasKey(lessThan(2)));167 // è¾å
¥Mapå
·æè³å°ä¸ä¸ªä¸æå®å¼æå¹é
å¨å¹é
çå¼168 Assert.assertThat(map, hasValue(startsWith("h")));169 // è¾å
¥Iterableå
·æè³å°ä¸ä¸ªä¸æå®å¼æå¹é
å¨å¹é
ç项ç®170 Assert.assertThat(objects, hasItems("a", "o"));171 ArrayList<Integer> integers = Lists.newArrayList(1, 2, 3, 4, 5, 6);172 Assert.assertThat(integers, hasItem(lessThan(3)));173 // è¾å
¥æ°ç»å
·æè³å°ä¸ä¸ªä¸æå®å¼æå¹é
å¨å¹é
ç项ç®174 Assert.assertThat(strings, hasItemInArray("there"));175 Assert.assertThat(strings, hasItemInArray(startsWith("t")));176 // è¾å
¥å¯¹è±¡æ»¡è¶³Bean约å®å¹¶ä¸å
·æå
·ææå®å称çå±æ§ï¼å¹¶ä¸è¯¥å±æ§çå¼å¯éå°177 User user = new User();178 user.setAge(12);179 user.setName("fei");180 Assert.assertThat(user, hasProperty("age", greaterThan(10)));181 Assert.assertThat(user, hasProperty("name"));182 // è¾å
¥Collectionå
·ææå®ç大å°ï¼æè
å®ç大å°ä¸æå®çå¹é
å¨å¹é
.183 Assert.assertThat(integers, hasSize(lessThan(10)));184 // è¾å
¥å¯¹è±¡çtoStringï¼ï¼æ¹æ³å¹é
æå®çStringæè¾å
¥å¹é
å¨.185 Assert.assertThat(3.1415926, hasToString("3.1415926"));186 Assert.assertThat(3.1415926, hasToString(containsString(".")));187 // è¾å
¥å¯¹è±¡æ¯ç»å®ç±»å188 Assert.assertThat("Hello World !", instanceOf(String.class));189 // è¾å
¥å符串为空ænullæ¶å¹é
190 Assert.assertThat("", isEmptyOrNullString());191 Assert.assertThat(null, isEmptyOrNullString());192 // è¾å
¥å符串为空æ¶å¹é
193 Assert.assertThat("", isEmptyString());194 // 空å¼ä¸é空å¼å¹é
195 Assert.assertThat(null, nullValue());196 Assert.assertThat("", notNullValue());197 // å½å¨ç»å®çCollectionæArrayä¸æ¾å°è¾å
¥é¡¹æ¶å¹é
198 Assert.assertThat(6, isIn(integers));199 // å½è¾å
¥å¯¹è±¡æ¯ç»å®å¯¹è±¡ä¹ä¸æ¶å¹é
200 Assert.assertThat("!", isOneOf("$", "#", "%", "!", "ï¿¥"));201 // å转å
¶å¹é
é»è¾202 Assert.assertThat("apple", not("orange"));203 Assert.assertThat(5, not(lessThan(2)));204 // è¾å
¥å¯¹è±¡ä¸æå®å¼ç¸åçå®ä¾æ¶å¹é
205 User user1 = user;206 Assert.assertThat(user, sameInstance(user1));207 Assert.assertThat(user, theInstance(user1));208 //è¾å
¥Beanå
·æä¸æå®Beanç¸åçå±æ§å¼æ¶å¹é
209 User user2 = new User();210 user2.setAge(12);211 user2.setName("fei");212 Assert.assertThat(user, samePropertyValuesAs(user2));213 // è¾å
¥å符串å
å«ç»å®Iterableä¸çåå符串ï¼åæä»Iterableè¿åç顺åºè¿è¡å¹é
214 String test = "Rule number one: two's company, but three's a crowd!";215 Assert.assertThat(test, stringContainsInOrder(Arrays.asList("one", "two", "three")));216 //è¾å
¥ç±»åç对象å¯ä»¥åé
ç»æå®åºæ¬ç±»åçå¼ç¨æ¶è¿è¡å¹é
217 Assert.assertThat(User.class, typeCompatibleWith(Object.class));218 // ç»åå¹é
å¨219 // 类似äºé»è¾AND220 Assert.assertThat(test, allOf(startsWith("R"), endsWith("!")));221 List<Matcher<? super String>> matchers = Arrays.asList(containsString("one"), startsWith("R"));222 Assert.assertThat(test, allOf(matchers));223 // 类似äºé»è¾æ224 Assert.assertThat(test, anyOf(containsString("hello"), instanceOf(String.class)));225 Assert.assertThat(test, anyOf(matchers));226 // è¾å
¥æ°ç»çå
ç´ åå«ä½¿ç¨æå®çå¹é
å¨æ顺åºå¹é
æ¶å¹é
ãå¹é
å¨çæ°éå¿
é¡»çäºæ°ç»ç大å°ã227 Assert.assertThat(strings, array(startsWith("w"), equalTo("hello"), notNullValue()));228 // å½ä¸å®çå¯ç»åå¹é
å¨.andï¼ï¼ç»å使ç¨æ¶ï¼å°å¨ä¸¤ä¸ªæå®çå¹é
å¨å¹é
æ¶å¹é
ã(é½)229 Assert.assertThat(test, both(startsWith("R")).and(containsString("two")));230 // å½ä¸å®çå¯ç»åå¹é
å¨.orï¼ï¼ç»å使ç¨æ¶ï¼å¦ææå®çå¹é
å¨å¹é
ï¼è¦ä¹ï¼231 Assert.assertThat(test, either(notNullValue()).or(instanceOf(String.class)));232 // å½è¾å
¥å¹é
å¨å¹é
æ¶å¹é
类似 not233 Assert.assertThat(1, Matchers.is(1));234 // ç¨äºè¦çå¦ä¸ä¸ªå¹é
å¨ç失败è¾åºãå½éè¦èªå®ä¹æ
éè¾åºæ¶ä½¿ç¨ãåæ°æ¯å¤±è´¥æ¶æ¯ï¼åå§Matcherï¼ç¶åæ¯å°ä½¿ç¨å ä½ç¬¦ï¼
0ï¼ï¼
1ï¼ï¼
2æ ¼å¼å为失败æ¶æ¯çææå¼ã235 Integer actual = 7;236 Integer expected = 10;237 Assert.assertThat(actual, describedAs("input > %0", greaterThan(expected), expected));238 }239 @Test240 public void testHello(){241 // èªå®ä¹å¹é
å¨242 // å¤æå¶æ°243 int i = 4;...
Source:HamcrestCoreMatchersTest.java
...20import static org.hamcrest.CoreMatchers.not;21import static org.hamcrest.CoreMatchers.notNullValue;22import static org.hamcrest.CoreMatchers.nullValue;23import static org.hamcrest.CoreMatchers.sameInstance;24import static org.hamcrest.CoreMatchers.startsWith;25import static org.hamcrest.CoreMatchers.startsWithIgnoringCase;26import static org.hamcrest.CoreMatchers.theInstance;27import static org.hamcrest.MatcherAssert.assertThat;28import java.util.List;29import org.junit.jupiter.api.Test;30import com.google.common.collect.Lists;3132public class HamcrestCoreMatchersTest {3334 @Test35 public void givenTestInput_WhenUsingIsForMatch() {3637 // GIVEN38 String testString = "hamcrest core";3940 // ASSERT41 assertThat(testString, is("hamcrest core"));42 assertThat(testString, is(equalTo("hamcrest core")));43 }4445 @Test46 public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() {4748 // GIVEN49 Object original = 100;5051 // ASSERT52 assertThat(original, equalToObject(100));53 }5455 @Test56 public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() {5758 assertThat("hamcrest", is(instanceOf(String.class)));59 }6061 @Test62 public void givenTestInput_WhenUsingIsA_ThenAssertType() {6364 assertThat("hamcrest core", isA(String.class));65 }6667 @Test68 public void givenTestInput_WhenUsingEqualToMatcherForEquality() {6970 // GIVEN71 String actualString = "Hamcrest Core";72 List<String> actualList = Lists.newArrayList("hamcrest", "core");7374 // ASSERT75 assertThat(actualString, is(equalTo("Hamcrest Core")));76 assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core"))));77 }7879 @Test80 public void givenTestInput_WhenUsingNotForMatch() {8182 // GIVEN83 String testString = "hamcrest";8485 // ASSERT86 assertThat(testString, not("hamcrest core"));87 assertThat(testString, is(not(equalTo("hamcrest core"))));88 assertThat(testString, is(not(instanceOf(Integer.class))));89 }9091 @Test92 public void givenTestInput_WhenUsingNullValueForNullCheck() {9394 // GIVEN95 Integer nullObject = null;9697 // ASSERT98 assertThat(nullObject, is(nullValue()));99 assertThat(nullObject, is(nullValue(Integer.class)));100 }101102 @Test103 public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() {104105 // GIVEN106 Integer testNumber = 123;107108 // ASSERT109 assertThat(testNumber, is(notNullValue()));110 assertThat(testNumber, is(notNullValue(Integer.class)));111 }112113 @Test114 public void givenString_WhenStartsWith_ThenCorrect() {115116 // GIVEN117 String testString = "hamcrest core";118119 // ASSERT120 assertThat(testString, startsWith("hamcrest"));121 }122123 @Test124 public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() {125126 // GIVEN127 String testString = "hamcrest core";128129 // ASSERT130 assertThat(testString, startsWithIgnoringCase("HAMCREST"));131 }132133 @Test134 public void givenString_WhenEndsWith_ThenCorrect() {135136 // GIVEN137 String testString = "hamcrest core";138139 // ASSERT140 assertThat(testString, endsWith("core"));141 }142143 @Test144 public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() {145146 // GIVEN147 String testString = "hamcrest core";148149 // ASSERT150 assertThat(testString, endsWithIgnoringCase("CORE"));151 }152153 @Test154 public void givenString_WhenContainsString_ThenCorrect() {155156 // GIVEN157 String testString = "hamcrest core";158159 // ASSERT160 assertThat(testString, containsString("co"));161 }162163 @Test164 public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() {165166167 // GIVEN168 String testString = "hamcrest core";169170 // ASSERT171 assertThat(testString, containsStringIgnoringCase("CO"));172 }173174 @Test175 public void givenTestInput_WhenUsingHasItemInCollection() {176177 // GIVEN178 List<String> list = Lists.newArrayList("java", "spring", "baeldung");179180 // ASSERT181 assertThat(list, hasItem("java"));182 assertThat(list, hasItem(isA(String.class)));183 }184185186 @Test187 public void givenTestInput_WhenUsingHasItemsInCollection() {188189 // GIVEN190 List<String> list = Lists.newArrayList("java", "spring", "baeldung");191192 // ASSERT193 assertThat(list, hasItems("java", "baeldung"));194 assertThat(list, hasItems(isA(String.class), endsWith("ing")));195 }196197 @Test198 public void givenTestInput_WhenUsingAnyForClassType() {199200 assertThat("hamcrest", is(any(String.class)));201 assertThat("hamcrest", is(any(Object.class)));202 }203204 @Test205 public void givenTestInput_WhenUsingAllOfForAllMatchers() {206207 // GIVEN208 String testString = "Hamcrest Core";209210 // ASSERT211 assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core")));212 }213214 @Test215 public void givenTestInput_WhenUsingAnyOfForAnyMatcher() {216217 // GIVEN218 String testString = "Hamcrest Core";219220 // ASSERT221 assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung")));222 }223224 @Test225 public void givenTestInput_WhenUsingBothForMatcher() {226227 // GIVEN228 String testString = "Hamcrest Core Matchers";229230 // ASSERT231 assertThat(testString, both(startsWith("Ham")).and(containsString("Core")));232 }233234 @Test235 public void givenTestInput_WhenUsingEitherForMatcher() {236237 // GIVEN238 String testString = "Hamcrest Core Matchers";239240 // ASSERT241 assertThat(testString, either(startsWith("Bael")).or(containsString("Core")));242 }243244245 @Test246 public void givenTestInput_WhenUsingEveryItemForMatchInCollection() {247248 // GIVEN249 List<String> testItems = Lists.newArrayList("Common", "Core", "Combinable");250251 // ASSERT252 assertThat(testItems, everyItem(startsWith("Co")));253 }254255 @Test256 public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() {257258 // GIVEN259 String string1 = "hamcrest";260 String string2 = string1;261262 // ASSERT263 assertThat(string1, is(sameInstance(string2)));264 }265266 @Test
...
Source:CoreMatchers.java
...13import static org.hamcrest.CoreMatchers.is;14import static org.hamcrest.CoreMatchers.isA;15import static org.hamcrest.CoreMatchers.notNullValue;16import static org.hamcrest.CoreMatchers.nullValue;17import static org.hamcrest.CoreMatchers.startsWith;18import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;19import static org.junit.Assert.assertThat;20import java.math.BigDecimal;21import java.util.ArrayList;22import java.util.Calendar;23import java.util.HashMap;24import java.util.HashSet;25import java.util.List;26import java.util.Map;27import java.util.Set;28import org.hamcrest.core.IsSame;29import org.junit.Test;30import com.google.common.collect.Lists;31/**32 * This java example will demonstrate hamcrest33 * core matchers.34 * 35 * @author Justin Musgrove36 * @see <a href='http://www.leveluplunch.com/java/examples/hamcrest-core-matchers-junit-testing/'>Core matchers</a>37 * 38 */39public class CoreMatchers {40 41 @Test42 public void hamcrest_core_allof () {43 String microBrew = "Lake Louie Brewery Company";44 45 assertThat(microBrew, allOf(startsWith("Lake"), containsString("Brew")));46 }47 48 @Test49 public void hamcrest_core_anyOf () {50 51 String microBrew = "Grumpy Troll Brewery";52 53 assertThat(microBrew, anyOf(startsWith("brew"), containsString("Troll")));54 }55 @Test56 public void hamcrest_core_combinableMatcher () {57 58 String isLite = "Miller Lite";59 60 assertThat(isLite, both(containsString("Miller")).and(containsString("Lite")));61 }62 @Test63 public void hamcrest_core_describedAs () {64 65 BigDecimal myBigDecimal = new BigDecimal("0");66 67 assertThat(myBigDecimal, 68 describedAs("a big decimal equal to %0", 69 equalTo(myBigDecimal), 70 myBigDecimal.toPlainString()));71 }72 73 @Test74 public void hamcrest_core_every () {75 76 List<Integer> ages = Lists.newArrayList(21, 25, 30, 18);77 assertThat(ages, everyItem(greaterThanOrEqualTo(18)));78 }79 80 81 @Test82 public void hamcrest_core_is() {83 84 String isLite = "Miller Brewing Company";85 86 assertThat("Miller Brewing Company", is(equalTo(isLite)));87 }88 89 @Test90 public void hamcrest_core_isA() {91 92 Map<Integer, String> map = new HashMap<Integer, String>();93 94 assertThat(map, isA(Map.class));95 }96 97 98 @Test99 public void hamcrest_core_anything () {100 101 assertThat("", anything());102 }103 104 @Test105 @SuppressWarnings("unchecked")106 public void hamcrest_core_hasItems_matchers () {107 108 List<String> regionalBreweries = Lists.newArrayList(109 "Capital Brewery", 110 "City Brewing Company ", 111 "Jacob Leinenkugel Brewing Company",112 "Lakefront Brewery", 113 "New Glarus Brewing Company", 114 "Stevens Point Brewery"); 115 116 assertThat(regionalBreweries, hasItems(117 containsString("Brew"), 118 endsWith("y")));119 }120 121 @Test122 public void hamcrest_core_hasItems () {123 124 List<String> regionalBreweries = Lists.newArrayList(125 "Capital Brewery", 126 "City Brewing Company ", 127 "Jacob Leinenkugel Brewing Company",128 "Lakefront Brewery, Inc.", 129 "New Glarus Brewing Company", 130 "Stevens Point Brewery"); 131 132 assertThat(regionalBreweries, hasItems(133 "Capital Brewery", 134 "City Brewing Company ", 135 "Jacob Leinenkugel Brewing Company",136 "Lakefront Brewery, Inc.", 137 "New Glarus Brewing Company", 138 "Stevens Point Brewery"));139 }140 141 @Test142 public void hamcrest_core_isEqual () {143 144 String spottedCreator = "New Glarus Brewing Company";145 146 assertThat(spottedCreator, equalTo("New Glarus Brewing Company"));147 }148 149 150 @Test151 public void hamcrest_core_isInstanceOf () {152 Calendar cal = Calendar.getInstance();153 154 assertThat(cal, instanceOf(Calendar.class));155 }156 157 @Test158 public void hamcrest_core_is_notNullValue () {159 Set<String> daNull = new HashSet<String>();160 161 assertThat(daNull, is(notNullValue()));162 }163 164 165 @Test166 public void hamcrest_core_is_nullValue () {167 168 Set<String> daNull = null;169 170 assertThat(daNull, is(nullValue()));171 }172 173 @Test174 public void hamcrest_core_isSame_string () {175 176 String wiBrewery = "Capital Brewery";177 String wiRegionalBrewery = "Capital Brewery";178 179 assertThat(wiRegionalBrewery, IsSame.<String>sameInstance(wiBrewery));180 }181 182 @Test183 public void hamcrest_core_is_same_list () {184 185 List<String> someList = new ArrayList<String>();186 187 assertThat(someList, IsSame.<List<String>>sameInstance(someList));188 }189 @Test190 public void hamcrest_core_containsString () {191 192 String brewery = "Pabst Brewing Company";193 194 assertThat(brewery, containsString("Brew"));195 }196 197 198 @Test199 public void hamcrest_core_string_startsWith () {200 String highSchool = "Tarpon spring spongers";201 202 assertThat(highSchool, startsWith("Tarpon"));203 }204 205 @Test206 public void hamcrest_core_string_endsWith () {207 208 String baseBallTeam = "Milwaukee brewers";209 210 assertThat(baseBallTeam, endsWith("brewers"));211 }212 213 214}...
Source:AssertThatTest.java
...18import static org.hamcrest.CoreMatchers.isA;19import static org.hamcrest.CoreMatchers.not;20import static org.hamcrest.CoreMatchers.nullValue;21import static org.hamcrest.CoreMatchers.sameInstance;22import static org.hamcrest.CoreMatchers.startsWith;23import static org.hamcrest.CoreMatchers.theInstance;24import static org.junit.Assert.assertThat;25/**26 * Exploring assertThat assertion using Harmcrest matchers27 */28public class AssertThatTest {29 @Test30 public void testAssertThat() {31 String string = "String";32 assertThat(string, is("String")); // This assertions does the same33 assertThat(string, equalTo("String"));34 assertThat(string, is(equalTo("String")));35 }36 @Test37 public void testAssertThatChain() {38 String string = "String";39 assertThat(string, allOf(containsString("ing"), startsWith("S"), endsWith("g")));40 assertThat(string, anyOf(containsString("tr"), startsWith("A"), endsWith("g")));41 assertThat(string, not(allOf(containsString("tr"), startsWith("A"), endsWith("g"))));42 assertThat(string, both(startsWith("S")).and(endsWith("g")));43 assertThat(string, both(startsWith("S")).and(endsWith("s")).or(endsWith("g")));44 assertThat(string, either(startsWith("X")).or(startsWith("S")).or(endsWith("g")));45 }46 @Test47 public void testVerboseHamcrestMatcher() {48 String string = "S";49 // This assertion if fails return a better description as:50 // java.lang.AssertionError: Expected: a String that start with "S" but: was "Foo"51 assertThat(string, describedAs("a String that start with %0", startsWith("S"), "S"));52 }53 @Test54 public void testSimpleHamcrestMatcher() {55 // Creates a matcher that always matches, regardless of the examined object.56 assertThat(null, anything());57 assertThat(null, nullValue());58 assertThat(null, is(nullValue()));59 Object actual = new Object();60 Object expected = actual;61 assertThat(actual, isA(Object.class));62 assertThat(actual, sameInstance(expected));63 assertThat(actual, theInstance(expected));64 assertThat(actual, not(sameInstance(new Object())));65 }66 @Test67 public void testArrayHamcrestMatcher() {68 List<String> strings = Arrays.asList("String", "Strong", "Street");69 assertThat(strings, everyItem(isA(String.class)));70 assertThat(strings, everyItem(startsWith("S")));71 assertThat(strings, hasItem("Strong"));72 assertThat(strings, hasItem(is("Street")));73 assertThat(strings, hasItems("Street", "String"));74 assertThat(strings, hasItems(endsWith("g"), endsWith("t")));75 }76}...
Source:AssertThatDemoTest.java
...16import static org.hamcrest.CoreMatchers.is;17import static org.hamcrest.CoreMatchers.isA;18import static org.hamcrest.CoreMatchers.not;19import static org.hamcrest.CoreMatchers.sameInstance;20import static org.hamcrest.CoreMatchers.startsWith;21import static org.junit.Assert.assertThat;22public class AssertThatDemoTest {23 @Test24 public void testAssertThat() {25 // assertThatçåºæ¬åçæ¯ï¼ç¨æå®çå¹é
å¨å¹é
æå®çå®é
å¼ãå¦æä¸å¹é
ï¼åçæé误信æ¯ï¼å¹¶æåºAssertionErrorå¼å¸¸ã26 // public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher) {27 // if (!matcher.matches(actual)) {28 // Description description = new StringDescription();29 // description.appendText(reason)30 // .appendText("\nExpected: ")31 // .appendDescriptionOf(matcher)32 // .appendText("\n but: ");33 // matcher.describeMismatch(actual, description);34 //35 // throw new AssertionError(description.toString());36 // }37 // }38 assertThat("Hello, World!", is("Hello, World!"));39 assertThat("Hello, World!", equalTo("Hello, World!"));40 assertThat("Hello, World!", startsWith("Hello"));41 assertThat("Hello, World!", endsWith("World!"));42 assertThat("Hello, World!", containsString("llo, Wor"));43 assertThat(6, not(8));44 assertThat("Hello, World!", anyOf(startsWith("Hello"), endsWith("Welcome")));45 assertThat("Hello, World!", either(startsWith("Hello")).or(endsWith("Welcome")));46 assertThat("Hello, World!", allOf(startsWith("Hello"), endsWith("World!")));47 assertThat("Hello, World!", both(startsWith("Hello")).and(endsWith("World!")));48 assertThat("Hello, World!", isA(String.class));49 assertThat("Hello, World!", anything());50 assertThat("Hello, World!", instanceOf(String.class));51 Object o = new Object();52 assertThat(o, sameInstance(o));53 assertThat(asList(1, 2, 3), hasItem(3));54 assertThat(asList(1, 2, 3), everyItem(not(8)));55 // èªå®ä¹MatcheråèassertThat("Is fails", "Hello, World!", is("Hi, World!"))çå®ä¹å失败æ¥åã56 // å¯ä»¥å¨ä¸ä¸ªç±»æ¯org.hamcrest.CoreMatchersçå·¥å
·ç±»ä¸æä¾éææ¹æ³ï¼è¯¥æ¹æ³è¿åèªå®ä¹Matcherã57 assertThat(Set.of(1, 2, 3), new HasElement<>(2));58 }59}...
Source:AssertTests.java
...7import static org.hamcrest.CoreMatchers.everyItem;8import static org.hamcrest.CoreMatchers.hasItems;9import static org.hamcrest.CoreMatchers.not;10import static org.hamcrest.CoreMatchers.sameInstance;11import static org.hamcrest.CoreMatchers.startsWith;12import static org.junit.Assert.assertArrayEquals;13import static org.junit.Assert.assertEquals;14import static org.junit.Assert.assertFalse;15import static org.junit.Assert.assertNotNull;16import static org.junit.Assert.assertNotSame;17import static org.junit.Assert.assertNull;18import static org.junit.Assert.assertSame;19import static org.junit.Assert.assertThat;20import static org.junit.Assert.assertTrue;21import java.util.Arrays;22import org.hamcrest.core.CombinableMatcher;23import org.junit.Ignore;24import org.junit.Test;25public class AssertTests {26 @Test27 public void testAssertArrayEquals() {28 byte[] expected = "trial".getBytes();29 byte[] actual = "trial".getBytes();30 assertArrayEquals("failure - byte arrays not same", expected, actual);31 }32 @Test33 public void testAssertEquals() {34 assertEquals("failure - strings are not equal", "text", "text");35 }36 @Test37 public void testAssertFalse() {38 assertFalse("failure - should be false", false);39 }40 @Test41 public void testAssertNotNull() {42 assertNotNull("should not be null", new Object());43 }44 @Test45 public void testAssertNotSame() {46 assertNotSame("should not be same Object", new Object(), new Object());47 }48 @Test49 public void testAssertNull() {50 assertNull("should be null", null);51 }52 @Test53 public void testAssertSame() {54 Integer aNumber = 768;55 assertSame("should be same", aNumber, aNumber);56 }57 // JUnit Matchers assertThat58 @Test59 public void testAssertThatBothContainsString() {60 assertThat("albumen", both(containsString("a")).and(containsString("b")));61 }62 @Test63 public void testAssertThatHasItems() {64 assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));65 }66 @Test67 public void testAssertThatEveryItemContainsString() {68 assertThat(Arrays.asList("fun", "ban", "net"), everyItem(containsString("n")));69 }70 // Core Hamcrest Matchers with assertThat71 @Test72 public void testAssertThatHamcrestCoreMatchers() {73 assertThat("good", allOf(equalTo("good"), startsWith("good")));74 assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));75 assertThat("good", anyOf(equalTo("bad"), equalTo("good")));76 assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));77 assertThat(new Object(), not(sameInstance(new Object())));78 }79 @Test80 public void testAssertTrue() {81 assertTrue("failure - should be true", true);82 }83}...
Source:combinational_collection_assert.java
...6import static org.hamcrest.CoreMatchers.is;7import static org.hamcrest.CoreMatchers.not;8import static org.hamcrest.CoreMatchers.notNullValue;9import static org.hamcrest.CoreMatchers.nullValue;10import static org.hamcrest.CoreMatchers.startsWith;11import static org.junit.Assert.*;12import java.util.Arrays;13import java.util.Collection;14import java.util.HashSet;15import java.util.Set;16import org.junit.Test;17public class combinational_collection_assert {18 @Test19 public void a_StringMatchers() { 20 String tested="TEKSYSTEMS";21 String check ="EKS";22 assertThat("MATCHING",tested, anything(check));23 }24 @Test25 public void b_NullMatchers() { 26 String tested=null;27 assertThat(" Null MATCHING",tested,nullValue());28 }29 @Test30 public void c_NotNullMatchers() { 31 String tested="";32 assertThat(" Null MATCHING",tested,notNullValue());33 }34 @Test35 public void d_STRINGSameMatchers() { 36 String tested="jharna";37 String check="jharna";38 assertThat(" MATCHING",tested,is(check));39 }40 @Test41 public void e_STRINGNotSameMatchers() { 42 String tested="jharna";43 String check="jharna1234";44 assertThat(" MATCHING",tested,not(check));45 }46 //--------------------------------combination assert---------------------------------47 @Test48 public void f_CombinationSTRINGNotSameMatchers() { 49 String tested="!!!!jharna@";50 assertThat(" MATCHING",tested,allOf(startsWith("!"),endsWith("@")));51 52 }53 //-------------------------------Collection Assert---------------------54 55 @Test56 public void f_CoLLECTIONSTRINGSameMatchers() { 57 String[] testArray= {"a","b","c"};58 Collection<String> tested=Arrays.asList(testArray);59 assertThat("MATCHES" ,tested, hasItem("b"));60}61 @Test62 public void g_CoLLECTIONSTRINGSameMatchers() {63 String[] testArray={"mate","rate"};64 Set<String> tested=new HashSet<String>(Arrays.asList(testArray));65 assertThat(tested,hasItem(endsWith("ate")));66 }67 68 @Test69 public void h_CoLLECTIONSTRINGSameMatchers() {70 String[] testArray={"teksystems","tekstsav"};71 Set<String> tested=new HashSet<String>(Arrays.asList(testArray));72 assertThat(tested,hasItem(startsWith("tek")));73 }74}...
Source:HamcrestMatchersTest.java
1package com.mhuffers.unittesting.unittesting.business;2import static org.hamcrest.CoreMatchers.containsString;3import static org.hamcrest.CoreMatchers.everyItem;4import static org.hamcrest.CoreMatchers.hasItems;5import static org.hamcrest.CoreMatchers.startsWith;6import static org.hamcrest.MatcherAssert.assertThat;7import static org.hamcrest.Matchers.greaterThan;8import static org.hamcrest.Matchers.hasSize;9import static org.hamcrest.Matchers.isEmptyString;10import static org.hamcrest.Matchers.lessThan;11import java.util.Arrays;12import java.util.List;13import org.junit.Test;14public class HamcrestMatchersTest {15 @Test16 public void assertsUsingHamcrest() {17 List<Integer> list = Arrays.asList(1,2,3,4);18 19 assertThat(list,hasSize(4));20 assertThat(list,hasItems(3,1));21 assertThat(list,everyItem(greaterThan(0)));22 assertThat(list,everyItem(lessThan(5)));23 24 assertThat("",isEmptyString());25 assertThat("ABCD",containsString("BC"));26 assertThat("ABCD",startsWith("AB"));27 }28}...
startsWith
Using AI Code Generation
1import static org.hamcrest.CoreMatchers.startsWith;2import static org.hamcrest.MatcherAssert.assertThat;3import org.hamcrest.core.StringStartsWith;4public class StringStartsWithExample {5 public static void main(String[] args) {6 StringStartsWith startsWith = new StringStartsWith("java");7 assertThat("java is a programming language", startsWith);8 }9}
startsWith
Using AI Code Generation
1import static org.hamcrest.CoreMatchers.startsWith;2import static org.junit.Assert.assertThat;3import org.junit.Test;4public class HamcrestTest {5 public void test() {6 assertThat("Hello World", startsWith("Hello"));7 }8}9[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ HamcrestTest ---10[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ HamcrestTest ---11[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ HamcrestTest ---12[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ HamcrestTest ---13[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ HamcrestTest ---
startsWith
Using AI Code Generation
1import org.hamcrest.Matchers.startsWith2import org.hamcrest.Matchers.endsWith3def 'startsWith'() {4}5def 'endsWith'() {6 str.endsWith('bcd')
startsWith
Using AI Code Generation
1import org.hamcrest.CoreMatchers.startsWith2import org.junit.Test3import static org.hamcrest.CoreMatchers.startsWith4import static org.junit.Assert.assertThat5class HamcrestTest {6 void test() {7 assertThat(str, startsWith("Hello"))8 }9}10import org.hamcrest.CoreMatchers.startsWith11import org.junit.Test12import static org.hamcrest.CoreMatchers.startsWith13import static org.junit.Assert.assertThat14class HamcrestTest {15 void test() {16 assertThat(str, startsWith("Hello"))17 }18}19import org.hamcrest.CoreMatchers.startsWith20import org.junit.Test21import static org.hamcrest.CoreMatchers.startsWith22import static org.junit.Assert.assertThat23class HamcrestTest {24 void test() {25 assertThat(str, startsWith("Hello"))26 }27}28import org.hamcrest.CoreMatchers.startsWith29import org.junit.Test30import static org.hamcrest.CoreMatchers.startsWith31import static org.junit.Assert.assertThat32class HamcrestTest {33 void test() {34 assertThat(str, startsWith("Hello"))35 }36}37import org.hamcrest.CoreMatchers.startsWith38import org.junit.Test39import static org.hamcrest.CoreMatchers.startsWith40import static org.junit.Assert.assertThat41class HamcrestTest {42 void test() {43 assertThat(str, startsWith("Hello"))44 }45}46import org.hamcrest.CoreMatchers.startsWith47import org.junit.Test48import static org.hamcrest.CoreMatchers.startsWith49import static org.junit.Assert.assertThat50class HamcrestTest {51 void test() {52 assertThat(str, startsWith("Hello"))53 }54}55import org.hamcrest.CoreMatchers.startsWith56import org.junit.Test57import static org.hamcrest.CoreMatchers.startsWith58import static org.junit.Assert.assertThat59class HamcrestTest {60 void test() {
startsWith
Using AI Code Generation
1import static org.hamcrest.CoreMatchers.startsWith;2import static org.hamcrest.MatcherAssert.assertThat;3import static org.hamcrest.Matchers.*;4import java.util.Arrays;5import java.util.List;6import org.hamcrest.Matcher;7import org.hamcrest.Matchers;8import org.junit.Test;9public class HamcrestExample {10 public void test() {11 assertThat("Hello World", startsWith("Hello"));12 assertThat("Hello World", containsString("World"));13 assertThat("Hello World", endsWith("World"));14 assertThat("Hello World", equalTo("Hello World"));15 assertThat("Hello World", is("Hello World"));16 assertThat("Hello World", is(equalTo("Hello World")));17 assertThat("Hello World", is(equalToIgnoringCase("hello world")));18 assertThat("Hello World", is(not("Hello World!")));19 assertThat("Hello World", is(notNullValue()));20 assertThat("Hello World", is(notNullValue(String.class)));21 assertThat("Hello World", is(notNullValue()));22 assertThat("Hello World", is(notNullValue(String.class)));23 assertThat("Hello World", is(notNullValue()));24 assertThat("Hello World", is(notNullValue(String.class)));25 assertThat("Hello World", is(notNullValue()));26 assertThat("Hello World", is(notNullValue(String.class)));27 assertThat(1, is(1));28 assertThat(1, is(not(2)));29 assertThat(1, is(lessThan(2)));30 assertThat(1, is(greaterThan(0)));31 assertThat(1, is(lessThanOrEqualTo(1)));32 assertThat(1, is(greaterThanOrEqualTo(1)));33 assertThat(1, is(both(greaterThan(0)).and(lessThan(2))));34 assertThat(1, is(both(greaterThan(0)).and(lessThan(2))));35 assertThat(1, is(both(greaterThan(0)).and(lessThan(2))));36 assertThat(1, is(both(greaterThan(0)).and(lessThan(2))));37 assertThat(1, is(both(greaterThan(0)).and(lessThan(2))));38 assertThat(1, is(both(greaterThan(0)).and(lessThan(2))));39 assertThat(1, is(not(both(greaterThan(0)).and(lessThan(2)))));40 assertThat(1, is(both(greaterThan(0)).and
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!