Best junit code snippet using org.hamcrest.CustomTypeSafeMatcher.describeTo
Source:Matchers.java
...55 final String actualMl = literal.toString();56 return literal.value.equals(comparable)57 && actualMl.equals(ml);58 }59 public void describeTo(Description description) {60 description.appendText("literal with value " + comparable61 + " and ML " + ml);62 }63 };64 }65 /** Matches an AST node by its string representation. */66 static Matcher<AstNode> isAst(boolean parenthesize, String expected) {67 return isAst(AstNode.class, parenthesize, expected);68 }69 /** Matches an AST node by its string representation. */70 static <T extends AstNode> Matcher<T> isAst(Class<? extends T> clazz,71 boolean parenthesize, String expected) {72 return new CustomTypeSafeMatcher<T>("ast with value [" + expected + "]") {73 protected boolean matchesSafely(T t) {74 assertThat(clazz.isInstance(t), is(true));75 final String s =76 stringValue(t);77 return s.equals(expected);78 }79 private String stringValue(T t) {80 return t.unparse(new AstWriter().withParenthesize(parenthesize));81 }82 @Override protected void describeMismatchSafely(T item,83 Description description) {84 description.appendText("was ").appendValue(stringValue(item));85 }86 };87 }88 /** Matches an Code node by its string representation. */89 static Matcher<Code> isCode(String expected) {90 return new CustomTypeSafeMatcher<Code>("code " + expected) {91 @Override protected boolean matchesSafely(Code code) {92 final String plan = Codes.describe(code);93 return plan.equals(expected);94 }95 @Override protected void describeMismatchSafely(Code code,96 Description description) {97 final String plan = Codes.describe(code);98 description.appendText("was ").appendValue(plan);99 }100 };101 }102 /** Matches a Code if it is wholly within Calcite. */103 static Matcher<Code> isFullyCalcite() {104 return new CustomTypeSafeMatcher<Code>("code is all Calcite") {105 protected boolean matchesSafely(Code code) {106 final String plan = Codes.describe(code);107 return plan.startsWith("calcite(") // instanceof CalciteCode108 && !plan.contains("morelScalar")109 && !plan.contains("morelTable");110 }111 };112 }113 static List<Object> list(Object... values) {114 return Arrays.asList(values);115 }116 static Map<Object, Object> map(Object... keyValues) {117 final LinkedHashMap<Object, Object> map = new LinkedHashMap<>();118 for (int i = 0; i < keyValues.length / 2; i++) {119 map.put(keyValues[i * 2], keyValues[i * 2 + 1]);120 }121 return map;122 }123 @SafeVarargs124 static <E> Matcher<Iterable<E>> equalsUnordered(E... elements) {125 final Set<E> expectedSet = Sets.newHashSet(elements);126 return new TypeSafeMatcher<Iterable<E>>() {127 protected boolean matchesSafely(Iterable<E> item) {128 //noinspection rawtypes129 return Sets.newHashSet((Iterable) item).equals(expectedSet);130 }131 public void describeTo(Description description) {132 description.appendText("equalsUnordered").appendValue(expectedSet);133 }134 };135 }136 @SafeVarargs137 static <E> Matcher<Iterable<E>> equalsOrdered(E... elements) {138 final List<E> expectedList = Arrays.asList(elements);139 return new TypeSafeMatcher<Iterable<E>>() {140 protected boolean matchesSafely(Iterable<E> item) {141 return Lists.newArrayList(item).equals(expectedList);142 }143 public void describeTo(Description description) {144 description.appendText("equalsOrdered").appendValue(expectedList);145 }146 };147 }148 @SuppressWarnings({"unchecked", "rawtypes"})149 static <E> Matcher<E> isUnordered(E expected) {150 final E expectedMultiset = expected instanceof Iterable151 ? (E) ImmutableMultiset.copyOf((Iterable) expected)152 : expected;153 return new TypeSafeMatcher<E>() {154 @Override public void describeTo(Description description) {155 description.appendText("equalsOrdered").appendValue(expectedMultiset);156 }157 @Override protected boolean matchesSafely(E actual) {158 final E actualMultiset = expectedMultiset instanceof Multiset159 && (actual instanceof Iterable)160 && !(actual instanceof Multiset)161 ? (E) ImmutableMultiset.copyOf((Iterable) actual)162 : actual;163 return expectedMultiset.equals(actualMultiset);164 }165 };166 }167 static Matcher<Throwable> throwsA(String message) {168 return new CustomTypeSafeMatcher<Throwable>("throwable: " + message) {169 @Override protected boolean matchesSafely(Throwable item) {170 return item.toString().contains(message);171 }172 };173 }174 static <T extends Throwable> Matcher<Throwable> throwsA(Class<T> clazz,175 Matcher<?> messageMatcher) {176 return new CustomTypeSafeMatcher<Throwable>(clazz + " with message "177 + messageMatcher) {178 @Override protected boolean matchesSafely(Throwable item) {179 return clazz.isInstance(item)180 && messageMatcher.matches(item.getMessage());181 }182 };183 }184 /** Creates a Matcher that behaves the same as a given delegate Matcher,185 * but remembers the value that was compared.186 *187 * @param <T> Type of expected item */188 public static <T> LearningMatcher<T> learning(Class<T> type) {189 return new LearningMatcherImpl<>(Is.isA(type));190 }191 /** Creates a Matcher that matches an Applicable, calls it with the given192 * argument, and checks the result. */193 static Matcher<Object> whenAppliedTo(Object arg,194 Matcher<Object> resultMatcher) {195 return new CallingMatcher(arg, resultMatcher);196 }197 /** Creates a Matcher that matches a Type based on {@link Type#moniker()}. */198 static Matcher<Type> hasMoniker(String expectedMoniker) {199 return new CustomTypeSafeMatcher<Type>("type with moniker ["200 + expectedMoniker + "]") {201 @Override protected boolean matchesSafely(Type type) {202 return type.moniker().equals(expectedMoniker);203 }204 };205 }206 /** Creates a Matcher that matches a {@link DataType} with given type207 * constructors. */208 static Matcher<DataType> hasTypeConstructors(String expected) {209 return new CustomTypeSafeMatcher<DataType>("datatype with constructors "210 + expected) {211 @Override protected boolean matchesSafely(DataType type) {212 return type.typeConstructors.toString().equals(expected);213 }214 };215 }216 /** Creates a Matcher that tests for a sub-class and then makes another217 * test.218 *219 * @param <T> Value type220 * @param <T2> Required subtype */221 static <T, T2 extends T> Matcher<T> instanceOfAnd(Class<T2> expectedClass,222 Matcher<T2> matcher) {223 return new TypeSafeDiagnosingMatcher<T>() {224 @Override protected boolean matchesSafely(T item,225 Description mismatchDescription) {226 if (!expectedClass.isInstance(item)) {227 mismatchDescription.appendText("expected instance of " + expectedClass228 + " but was " + item + " (a " + item.getClass() + ")");229 return false;230 }231 if (!matcher.matches(item)) {232 matcher.describeMismatch(item, mismatchDescription);233 return false;234 }235 return true;236 }237 @Override public void describeTo(Description description) {238 description.appendText("instance of " + expectedClass + " and ");239 matcher.describeTo(description);240 }241 };242 }243 /** Matcher that remembers the actual value it was.244 *245 * @param <T> Type of expected item */246 public interface LearningMatcher<T> extends Matcher<T> {247 T get();248 }249 /** Matcher that performs an action when a value is matched.250 *251 * @param <T> Type of expected item */252 private abstract static class MatcherWithConsumer<T> extends BaseMatcher<T> {253 final Matcher<T> matcher;254 MatcherWithConsumer(Matcher<T> matcher) {255 this.matcher = matcher;256 }257 protected abstract void consume(T t);258 @SuppressWarnings("unchecked")259 @Override public boolean matches(Object o) {260 if (matcher.matches(o)) {261 consume((T) o);262 return true;263 } else {264 return false;265 }266 }267 @Override public void describeMismatch(Object o,268 Description description) {269 matcher.describeMismatch(o, description);270 }271 @Override public void describeTo(Description description) {272 matcher.describeTo(description);273 }274 }275 /** Implementation of {@link LearningMatcher}.276 *277 * @param <T> Type of expected item */278 private static class LearningMatcherImpl<T> extends MatcherWithConsumer<T>279 implements LearningMatcher<T> {280 final List<T> list = new ArrayList<>();281 LearningMatcherImpl(Matcher<T> matcher) {282 super(matcher);283 }284 @Override public T get() {285 return list.get(0);286 }287 @Override protected void consume(T t) {288 list.add(t);289 }290 }291 /** Helper for {@link #whenAppliedTo(Object, Matcher)}. */292 private static class CallingMatcher extends BaseMatcher<Object> {293 private final Object arg;294 private final Matcher<Object> resultMatcher;295 CallingMatcher(Object arg, Matcher<Object> resultMatcher) {296 this.arg = arg;297 this.resultMatcher = resultMatcher;298 }299 @Override public void describeTo(Description description) {300 description.appendText("calls with ")301 .appendValue(arg)302 .appendText(" and returns ")303 .appendDescriptionOf(resultMatcher);304 }305 @Override public boolean matches(Object o) {306 if (!(o instanceof Applicable)) {307 return false;308 }309 final Applicable applicable = (Applicable) o;310 final Object result = applicable.apply(Codes.emptyEnv(), arg);311 return resultMatcher.matches(result);312 }313 }...
Source:CustomMatchers.java
...46 protected boolean matchesSafely(T item) {47 return predicate.test(item);48 }49 @Override50 public void describeTo(Description description) {51 description.appendValue(predicate);52 }53 };54 }55 /**56 * Matcher for a collection of a given size.57 * @param size of collection58 * @return matcher for a collection of a given size59 */60 public static Matcher<Collection<?>> hasSize(final int size) {61 return new TypeSafeMatcher<Collection<?>>() {62 @Override63 protected boolean matchesSafely(Collection<?> collection) {64 return collection != null && collection.size() == size;65 }66 @Override67 public void describeTo(Description description) {68 description.appendText("hasSize(").appendValue(size).appendText(")");69 }70 };71 }72 /**73 * Matcher for an empty collection.74 * @return matcher for an empty collection75 */76 public static Matcher<Collection<?>> isEmpty() {77 return new TypeSafeMatcher<Collection<?>>() {78 @Override79 protected boolean matchesSafely(Collection<?> collection) {80 return collection != null && collection.isEmpty();81 }82 @Override83 public void describeTo(Description description) {84 description.appendText("isEmpty()");85 }86 };87 }88 /**89 * Matcher for a point at a given location.90 * @param expected expected location91 * @return matcher for a point at a given location92 */93 public static Matcher<? super Point2D> is(final Point2D expected) {94 return new CustomTypeSafeMatcher<Point2D>(Objects.toString(expected)) {95 @Override96 protected boolean matchesSafely(Point2D actual) {97 return expected.distance(actual) <= 0.0000001;98 }99 };100 }101 /**102 * Matcher for a point at a given location.103 * @param expected expected location104 * @return matcher for a point at a given location105 */106 public static Matcher<? super LatLon> is(final LatLon expected) {107 return new CustomTypeSafeMatcher<LatLon>(Objects.toString(expected)) {108 @Override109 protected boolean matchesSafely(LatLon actual) {110 return Math.abs(expected.getX() - actual.getX()) <= LatLon.MAX_SERVER_PRECISION111 && Math.abs(expected.getY() - actual.getY()) <= LatLon.MAX_SERVER_PRECISION;112 }113 };114 }115 /**116 * Matcher for a point at a given location.117 * @param expected expected location118 * @return matcher for a point at a given location119 */120 public static Matcher<? super EastNorth> is(final EastNorth expected) {121 return new CustomTypeSafeMatcher<EastNorth>(Objects.toString(expected)) {122 @Override123 protected boolean matchesSafely(EastNorth actual) {124 return Math.abs(expected.getX() - actual.getX()) <= LatLon.MAX_SERVER_PRECISION125 && Math.abs(expected.getY() - actual.getY()) <= LatLon.MAX_SERVER_PRECISION;126 }127 };128 }129 /**130 * Matcher for a {@link Bounds} object131 * @param expected expected bounds132 * @param tolerance acceptable deviation (epsilon)133 * @return Matcher for a {@link Bounds} object134 */135 public static Matcher<Bounds> is(final Bounds expected, double tolerance) {136 return new TypeSafeMatcher<Bounds>() {137 @Override138 public void describeTo(Description description) {139 description.appendText("is ")140 .appendValue(expected)141 .appendText(" (tolerance: " + tolerance + ")");142 }143 @Override144 protected void describeMismatchSafely(Bounds bounds, Description mismatchDescription) {145 mismatchDescription.appendText("was ").appendValue(bounds);146 }147 @Override148 protected boolean matchesSafely(Bounds bounds) {149 return Math.abs(expected.getMinLon() - bounds.getMinLon()) <= tolerance &&150 Math.abs(expected.getMinLat() - bounds.getMinLat()) <= tolerance &&151 Math.abs(expected.getMaxLon() - bounds.getMaxLon()) <= tolerance &&152 Math.abs(expected.getMaxLat() - bounds.getMaxLat()) <= tolerance;153 }154 };155 }156 /**157 * Matcher for a floating point number.158 * @param expected expected value159 * @param errorMode the error mode160 * @param tolerance admissible error161 * @return Matcher for a floating point number162 */163 public static Matcher<Double> isFP(final double expected, ErrorMode errorMode, double tolerance) {164 return new TypeSafeMatcher<Double>() {165 @Override166 public void describeTo(Description description) {167 description.appendText("is ")168 .appendValue(expected)169 .appendText(" (tolerance")170 .appendText(errorMode == ErrorMode.RELATIVE ? ", relative:" : ":")171 .appendText(Double.toString(tolerance))172 .appendText(")");173 }174 @Override175 protected void describeMismatchSafely(Double was, Description mismatchDescription) {176 mismatchDescription.appendText("was ").appendValue(was);177 if (errorMode == ErrorMode.RELATIVE) {178 mismatchDescription.appendText(" (actual relative error: ")179 .appendText(String.format(Locale.US, "%.2e", Math.abs((was - expected) / expected)))180 .appendText(")");...
Source:HeaderMatchers.java
...42 public boolean matches(Object item) {43 return item != null && StringUtils.isNotBlank(item.toString());44 }45 @Override46 public void describeTo(Description description) {47 description.appendText("set");48 }49 };50 }51 public static Matcher<String> headerNotPresent() {52 return new BaseMatcher<String>() {53 @Override54 public boolean matches(Object item) {55 return item == null || StringUtils.isBlank(item.toString());56 }57 @Override58 public void describeTo(Description description) {59 description.appendText("absent or empty");60 }61 };62 }63 public static Matcher<String> isLink(String uri, String rel) {64 final Link expected = Link.fromUri(uri).rel(rel).build();65 return new CustomTypeSafeMatcher<String>(String.format("a Link-Header to <%s> with rel='%s'", uri, rel)) {66 @Override67 protected boolean matchesSafely(String item) {68 return expected.equals(new LinkDelegate().fromString(item));69 }70 };71 }72 public static Matcher<String> isValidEntityTag() {...
Source:CarHamcrestMatcher.java
...38 return new CarHamcrestMatcher(matcher);39 }4041 @Override42 public void describeTo(Description desc) {43 this.matcher.describeTo(desc);44 }4546 @Override47 protected boolean matchesSafely(Car car) {48 return this.matcher.matches(car);49 }5051 private static class HasEngineType extends CustomTypeSafeMatcher<Car> {5253 private EngineType engineType;5455 public HasEngineType(EngineType engineType) {56 super("engine type is " + engineType);57 this.engineType = engineType;
...
Source:CustomViewMatchers.java
...28 this.viewId = viewId;29 this.shouldExtractDigits = shouldExtractDigits;30 }31 @Override32 public void describeTo(final Description description) {33 description.appendText("Has EditText/TextView the value equals to view: " + viewId);34 }35 @Override36 public boolean matchesSafely(final View view) {37 final View viewById = view.getRootView().findViewById(viewId);38 if (!(view instanceof TextView || !(viewById instanceof TextView))) {39 return false;40 }41 //noinspection ConstantConditions42 final String targetText = ((TextView) viewById).getText().toString();43 //noinspection ConstantConditions44 String text = ((TextView) view).getText().toString();45 text = shouldExtractDigits ? text.replaceAll(EXTRACT_DIGITS_REGEX, "") : text;46 return text.equalsIgnoreCase(targetText);...
Source:CarsHamcrestMatcher.java
...32 return new CarsHamcrestMatcher(matcher);33 }3435 @Override36 public void describeTo(Description desc) {37 this.matcher.describeTo(desc);38 }3940 @Override41 protected boolean matchesSafely(Collection<Car> cars) {42 43 StringWriter sw = new StringWriter();44 Closure writer = closure(); { of(sw).write(var(String.class)); }45 assertEquals(1, writer.getFreeVarsNumber());46 writer.each(asList("first", "second", "third"));47 assertEquals("firstsecondthird", sw.toString());4849 return this.matcher.matches(cars);50 }51
...
Source:CustomTypeSafeMatcher.java
...32/* 32 */ this.fixedDescription = description;33/* */ }34/* */ 35/* */ 36/* */ public final void describeTo(Description description) {37/* 37 */ description.appendText(this.fixedDescription);38/* */ }39/* */ }40/* Location: C:\Users\CAR\Desktop\sab\SAB_projekat_1920\SAB_projekat_1920\SAB_projekat_1920.jar!\org\hamcrest\CustomTypeSafeMatcher.class41 * Java compiler version: 5 (49.0)42 * JD-Core Version: 1.1.343 */...
describeTo
Using AI Code Generation
1public class CustomTypeSafeMatcherTest {2 public void testCustomTypeSafeMatcher() {3 assertThat(2, new CustomTypeSafeMatcher<Integer>("even number") {4 protected boolean matchesSafely(Integer item) {5 return item % 2 == 0;6 }7 });8 }9}10package com.journaldev.hamcrest;11import static org.hamcrest.MatcherAssert.assertThat;12import static org.hamcrest.Matchers.equalTo;13import org.hamcrest.CustomTypeSafeMatcher;14import org.junit.Test;15public class CustomTypeSafeMatcherExample2 {16 public void testCustomTypeSafeMatcher() {17 assertThat("Hello World", new CustomTypeSafeMatcher<String>("contains World") {18 protected boolean matchesSafely(String item) {19 return item.contains("World");20 }21 });22 }23 public void testCustomTypeSafeMatcher2() {24 assertThat("Hello World", new CustomTypeSafeMatcher<String>("contains World") {25 protected boolean matchesSafely(String item) {26 return item.contains("World");27 }28 protected void describeMismatchSafely(String item, Description mismatchDescription) {29 mismatchDescription.appendText("was ").appendValue(item);30 }31 });32 }33 public void testCustomTypeSafeMatcher3() {34 assertThat("Hello World", new CustomTypeSafeMatcher<String>("contains World") {
describeTo
Using AI Code Generation
1package com.example;2import org.hamcrest.CustomTypeSafeMatcher;3import org.hamcrest.MatcherAssert;4import org.hamcrest.Matcher;5import org.hamcrest.Description;6import org.hamcrest.TypeSafeMatcher;7import org.hamcrest.core.IsEqual;8import org.hamcrest.core.IsNot;9public class Example {10 public static void main(String[] args) {11 Matcher<String> matcher = new CustomTypeSafeMatcher<String>("a substring") {12 protected boolean matchesSafely(String item) {13 return item.contains(substring);14 }15 };16 MatcherAssert.assertThat("a string containing a substring", matcher);17 MatcherAssert.assertThat("a string not containing a substring", IsNot.not(matcher));18 Matcher<String> matcher2 = new CustomTypeSafeMatcher<String>("a substring") {19 protected boolean matchesSafely(String item) {20 return item.contains(substring);21 }22 public void describeMismatchSafely(String item, Description mismatchDescription) {23 mismatchDescription.appendText("was \"").appendText(item).appendText("\"");24 }25 };26 MatcherAssert.assertThat("a string containing a substring", matcher2);27 MatcherAssert.assertThat("a string not containing a substring", IsNot.not(matcher2));28 Matcher<String> matcher3 = new CustomTypeSafeMatcher<String>("a substring")
describeTo
Using AI Code Generation
1public class CustomTypeSafeMatcherTest {2 private static final Matcher<CustomTypeSafeMatcher.Book> BOOK_MATCHER = new CustomTypeSafeMatcher.BookMatcher();3 private static final Matcher<CustomTypeSafeMatcher.Book> BOOK_MATCHER1 = new CustomTypeSafeMatcher.BookMatcher1();4 public void testBookMatcher() {5 assertThat(new CustomTypeSafeMatcher.Book("A Tale of Two Cities", 1859), BOOK_MATCHER);6 assertThat(new CustomTypeSafeMatcher.Book("A Tale of Two Cities", 1859), BOOK_MATCHER1);7 }8}9public class CustomTypeSafeMatcher {10 public static class Book {11 private final String title;12 private final int yearPublished;13 public Book(String title, int yearPublished) {14 this.title = title;15 this.yearPublished = yearPublished;16 }17 public String getTitle() {18 return title;19 }20 public int getYearPublished() {21 return yearPublished;22 }23 }24 public static class BookMatcher extends TypeSafeMatcher<Book> {25 private String title;26 private int yearPublished;27 public BookMatcher withTitle(String title) {28 this.title = title;29 return this;30 }31 public BookMatcher publishedIn(int yearPublished) {32 this.yearPublished = yearPublished;33 return this;34 }35 public boolean matchesSafely(Book book) {36 return book.getTitle().equals(title) && book.getYearPublished() == yearPublished;37 }38 public void describeTo(Description description) {39 description.appendText("a book called ").appendValue(title).appendText(" published in ").appendValue(yearPublished);40 }41 }42 public static class BookMatcher1 extends TypeSafeMatcher<Book> {43 private String title;44 private int yearPublished;45 public BookMatcher1 withTitle(String title) {46 this.title = title;47 return this;48 }49 public BookMatcher1 publishedIn(int yearPublished) {50 this.yearPublished = yearPublished;51 return this;52 }53 public boolean matchesSafely(Book book) {54 return book.getTitle().equals
describeTo
Using AI Code Generation
1import org.hamcrest.CustomTypeSafeMatcher;2import org.hamcrest.Description;3import org.hamcrest.Matcher;4import org.hamcrest.StringDescription;5public class CustomMatcher extends CustomTypeSafeMatcher<String> {6 public CustomMatcher(Matcher<String> matcher) {7 super(matcher);8 }9 protected String getMismatchSafely(String item) {10 return item;11 }12 protected void describeMismatchSafely(String item, Description mismatchDescription) {13 mismatchDescription.appendText("was ").appendValue(item);14 }15 public void describeTo(Description description) {16 description.appendText("a string");17 }18}19public class CustomMatcherTest {20 public void testCustomMatcher() {21 String actual = "abc";22 String expected = "xyz";23 assertThat(actual, new CustomMatcher(equalTo(expected)));24 }25}26public class CustomMatcherTest {27 public void testCustomMatcher() {28 String actual = "abc";29 String expected = "xyz";30 assertThat(actual, new CustomMatcher(equalTo(expected)));31 }32}33public class CustomMatcherTest {34 public void testCustomMatcher() {35 String actual = "abc";36 String expected = "xyz";37 assertThat(actual, new CustomMatcher(equalTo(expected)));38 }39}40public class CustomMatcherTest {41 public void testCustomMatcher() {42 String actual = "abc";43 String expected = "xyz";44 assertThat(actual, new CustomMatcher(equalTo(expected)));45 }46}47public class CustomMatcherTest {48 public void testCustomMatcher() {49 String actual = "abc";50 String expected = "xyz";51 assertThat(actual, new CustomMatcher(equalTo(expected)));52 }53}54public class CustomMatcherTest {
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!!