How to use Interface Matcher class of org.hamcrest package

Best junit code snippet using org.hamcrest.Interface Matcher

Source:ASTBasedABSTestRunnerGeneratorTest.java Github

copy

Full Screen

1/**2 * Copyright (c) 2009-2011, The HATS Consortium. All rights reserved. 3 * This file is licensed under the terms of the Modified BSD License.4 */5package abs.backend.tests;6import static abs.backend.tests.ReflectionUtils.getField;7import static abs.backend.tests.ReflectionUtils.setField;8import static org.hamcrest.CoreMatchers.equalTo;9import static org.hamcrest.CoreMatchers.notNullValue;10import static org.hamcrest.CoreMatchers.nullValue;11import static org.junit.Assert.assertEquals;12import static org.junit.Assert.assertFalse;13import static org.junit.Assert.assertSame;14import static org.junit.Assert.assertThat;15import static org.junit.Assert.assertTrue;16import static org.junit.Assert.fail;17import static org.hamcrest.CoreMatchers.both;18import static org.hamcrest.CoreMatchers.everyItem;19import static org.hamcrest.CoreMatchers.hasItem;20import java.io.ByteArrayOutputStream;21import java.io.PrintStream;22import java.util.Collections;23import java.util.Iterator;24import java.util.List;25import java.util.Map;26import java.util.Map.Entry;27import java.util.Set;28import org.hamcrest.BaseMatcher;29import org.hamcrest.Description;30import org.hamcrest.Matcher;31import org.junit.Test;32import abs.frontend.analyser.SemanticCondition;33import abs.frontend.analyser.SemanticConditionList;34import abs.frontend.ast.ClassDecl;35import abs.frontend.ast.InterfaceDecl;36import abs.frontend.ast.Model;37import abs.frontend.ast.ModuleDecl;38import abs.frontend.parser.Main;39import abs.frontend.parser.ParserError;40/**41 * Unit tests for {@link ASTBasedABSTestRunnerGenerator}42 * @author woner43 *44 */45public class ASTBasedABSTestRunnerGeneratorTest {46 private final static String ABS_UNIT =47 "module AbsUnit; export *;" +48 "[TypeAnnotation] data DataPoint = DataPoint; " +49 "[TypeAnnotation] data Ignored = Ignored;" +50 "[TypeAnnotation] data Test = Test; " +51 "[TypeAnnotation] data Suite = Suite; " +52 "[TypeAnnotation] data Fixture = Fixture; ";53 private final static String TEST_CODE =54 "module Test; export *; import * from AbsUnit;" +55 "[Fixture] interface T { [Test] Unit t(); }" +56 "[Suite] class TI implements T { Unit t() { } }";57 58 private final static Iterable<Entry<InterfaceDecl, Set<ClassDecl>>> EMPTY_MAP = 59 Collections.<InterfaceDecl, Set<ClassDecl>>emptyMap().entrySet();60 61 private static class SizeMatcher 62 extends BaseMatcher<Iterable<Entry<InterfaceDecl, Set<ClassDecl>>>> {63 64 private final int size;65 66 public SizeMatcher(int size) {67 this.size = size;68 }69 70 public boolean matches(Object arg0) {71 if (arg0 instanceof Iterable) {72 Iterable<?> it = (Iterable<?>) arg0;73 Iterator<?> tr = it.iterator();74 75 int count = 0;76 while (count < size) {77 if (! tr.hasNext()) {78 return false;79 }80 tr.next();81 count++;82 }83 return ! tr.hasNext();84 }85 return false;86 }87 88 @SuppressWarnings("unused")89 public void describeTo(Description arg0) {90 // TODO Auto-generated method stub91 92 }93 94 }95 /**96 * @see ASTBasedABSTestRunnerGeneratorTest.ModuleMatcher below for note about generics!97 */98 private static class TestClassMatcher<I,C>99 extends BaseMatcher<Entry<I, Set<C>>> {100 101 public boolean matches(Object arg0) {102 if (!(arg0 instanceof Entry)) {103 return false;104 }105 106 final Entry<?, ?> entry = (Entry<?, ?>) arg0;107 if (!(entry.getKey() instanceof InterfaceDecl)) {108 return false;109 }110 111 if (!(entry.getValue() instanceof Set)) {112 return false;113 }114 115 final Set<?> set = (Set<?>) entry.getValue();116 if (set.size() != 1) {117 return false;118 }119 120 final Object ele = set.iterator().next();121 if (!(ele instanceof ClassDecl)) {122 return false;123 }124 125 final InterfaceDecl intf = (InterfaceDecl) entry.getKey();126 final ClassDecl clazz = (ClassDecl) ele;127 128 return intf.getName().equals("T") &&129 clazz.getName().equals("TI");130 }131 132 @SuppressWarnings("unused")133 public void describeTo(Description arg0) {134 }135 136 }137 138 /**139 * NB: type patched to be generic instead of the more specific ModuleDecl because140 * javac is too picky about hamcrests' generics!141 */142 private static class ModuleMatcher<T> 143 extends BaseMatcher<T> {144 public boolean matches(Object arg0) {145 if (arg0 instanceof ModuleDecl) {146 ModuleDecl module = (ModuleDecl) arg0;147 if (module.getName().equals(ASTBasedABSTestRunnerGenerator.RUNNER_MAIN)) {148 return module.hasBlock();149 }150 }151 return false;152 }153 @SuppressWarnings("unused")154 public void describeTo(Description arg0) {155 // TODO Auto-generated method stub156 157 }158 }159 @SuppressWarnings("unchecked")160 private static void assertMatches(161 Model model,162 Matcher<Object> testType, 163 Matcher<Object> dataPointType,164 Matcher<Object> fixtureType,165 Matcher<Object> suiteType,166 Matcher<Iterable<Entry<InterfaceDecl, Set<ClassDecl>>>> tests,167 Boolean isEmpty,168 ABSTestRunnerGenerator aut) {169 170 assertSame(model,getField(aut, AbstractABSTestRunnerGenerator.class, "model"));171 assertThat(getField(aut, AbstractABSTestRunnerGenerator.class, "testType"),testType);172 assertThat(getField(aut, AbstractABSTestRunnerGenerator.class, "dataPointType"),dataPointType);173 assertThat(getField(aut, AbstractABSTestRunnerGenerator.class, "fixtureType"),fixtureType);174 assertThat(getField(aut, AbstractABSTestRunnerGenerator.class, "suiteType"),suiteType);175 176 Map<InterfaceDecl, Set<ClassDecl>> actual = 177 (Map<InterfaceDecl, Set<ClassDecl>>) getField(aut, AbstractABSTestRunnerGenerator.class, "tests");178 assertThat(actual.entrySet(),tests);179 assertEquals(isEmpty,getField(aut, AbstractABSTestRunnerGenerator.class, "isEmpty"));180 }181 @SuppressWarnings("unused")182 @Test(expected=IllegalArgumentException.class)183 public final void testABSTestRunnerGeneratorNull() {184 new ASTBasedABSTestRunnerGenerator(null);185 }186 187 @Test188 public final void testABSTestRunnerGenerator() {189 Model model = new Model();190 ABSTestRunnerGenerator generator = 191 new ASTBasedABSTestRunnerGenerator(model);192 193 assertMatches(model, 194 nullValue(), nullValue(), nullValue(), nullValue(), 195 equalTo(EMPTY_MAP), Boolean.TRUE,196 generator);197 198 try {199 model = Main.parseString(ABS_UNIT, true);200 generator = new ASTBasedABSTestRunnerGenerator(model);201 202 assertMatches(model, 203 notNullValue(), notNullValue(), notNullValue(), notNullValue(), 204 equalTo(EMPTY_MAP), Boolean.TRUE,205 generator);206 207 model = Main.parseString(ABS_UNIT + TEST_CODE, true);208 generator = new ASTBasedABSTestRunnerGenerator(model);209 210 assertMatches(model, 211 notNullValue(), notNullValue(), notNullValue(), notNullValue(), 212 both(everyItem(new TestClassMatcher())).213 and(new SizeMatcher(1)), Boolean.FALSE,214 generator);215 216 } catch (Exception e) {217 throw new IllegalStateException("Cannot parse test code",e);218 }219 }220 221 @Test222 public final void testHasUnitTest() {223 Model model = new Model();224 ABSTestRunnerGenerator generator = 225 new ASTBasedABSTestRunnerGenerator(model);226 227 generator = setField(generator, AbstractABSTestRunnerGenerator.class, "isEmpty", Boolean.TRUE);228 assertFalse(generator.hasUnitTest());229 generator = setField(generator, AbstractABSTestRunnerGenerator.class, "isEmpty", Boolean.FALSE);230 assertTrue(generator.hasUnitTest());231 }232 233 @Test234 public final void testGenerateTestRunner() {235 final Model model;236 try {237 model = Main.parseString(ABS_UNIT + TEST_CODE, true);238 } catch (Exception e) {239 throw new IllegalStateException("Cannot parse test code",e);240 }241 242 ABSTestRunnerGenerator generator = new ASTBasedABSTestRunnerGenerator(model);243 ByteArrayOutputStream stream = new ByteArrayOutputStream();244 PrintStream print = new PrintStream(stream); 245 generator.generateTestRunner(print);246 String runner = stream.toString();247 248 try {249 Model result = Main.parseString(ABS_UNIT + TEST_CODE + runner, true);250 251 StringBuilder parseErrors = new StringBuilder();252 if (result.hasParserErrors()) {253 parseErrors.append("Syntactic errors: ");254 List<ParserError> es = result.getParserErrors();255 parseErrors.append(es.size());256 parseErrors.append("\n");257 for (ParserError e : es) {258 parseErrors.append(e.getHelpMessage());259 parseErrors.append("\n");260 }261 }262 263 assertFalse("Generated code must not have parse error: "+parseErrors,result.hasParserErrors());264 265 StringBuilder errors = new StringBuilder();266 if (result.hasErrors()) {267 SemanticConditionList el = result.getErrors();268 errors.append("Semantic errors: ");269 errors.append(el.getErrorCount());270 errors.append("\n");271 for (SemanticCondition error : el) {272 errors.append(error.getHelpMessage());273 errors.append("\n");274 }275 }276 277 assertFalse("Generated code must not have semantic error: "+errors,result.hasErrors());278 result.typeCheck();279 assertFalse("Generated code must not have type error",result.hasTypeErrors());280 281 assertThat("Has one module that has the name 'AbsUnit.TestRunner' and a main block",282 result.getModuleDecls(),hasItem(new ModuleMatcher()));283 284 } catch (Exception e) {285 fail("Cannot throw an exception ");286 }287 288 }289 290}...

Full Screen

Full Screen

Source:PipelineOptionsReflectorTest.java Github

copy

Full Screen

1/*2 * Licensed to the Apache Software Foundation (ASF) under one3 * or more contributor license agreements. See the NOTICE file4 * distributed with this work for additional information5 * regarding copyright ownership. The ASF licenses this file6 * to you under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance8 * with the License. You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18package org.apache.beam.sdk.options;19import static org.hamcrest.MatcherAssert.assertThat;20import static org.hamcrest.Matchers.allOf;21import static org.hamcrest.Matchers.equalTo;22import static org.hamcrest.Matchers.hasItem;23import static org.hamcrest.Matchers.is;24import static org.hamcrest.Matchers.isOneOf;25import static org.hamcrest.Matchers.not;26import com.fasterxml.jackson.annotation.JsonIgnore;27import java.util.Set;28import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;29import org.hamcrest.FeatureMatcher;30import org.hamcrest.Matcher;31import org.hamcrest.Matchers;32import org.junit.Test;33import org.junit.runner.RunWith;34import org.junit.runners.JUnit4;35/** Unit tests for {@link PipelineOptionsReflector}. */36@RunWith(JUnit4.class)37public class PipelineOptionsReflectorTest {38 @Test39 public void testGetOptionSpecs() throws NoSuchMethodException {40 Set<PipelineOptionSpec> properties =41 PipelineOptionsReflector.getOptionSpecs(SimpleOptions.class, true);42 assertThat(43 properties,44 Matchers.hasItems(45 PipelineOptionSpec.of(46 SimpleOptions.class, "foo", SimpleOptions.class.getDeclaredMethod("getFoo"))));47 }48 /** Test interface. */49 public interface SimpleOptions extends PipelineOptions {50 String getFoo();51 void setFoo(String value);52 }53 @Test54 public void testFiltersNonGetterMethods() {55 Set<PipelineOptionSpec> properties =56 PipelineOptionsReflector.getOptionSpecs(OnlyTwoValidGetters.class, true);57 assertThat(properties, not(hasItem(hasName(isOneOf("misspelled", "hasParameter", "prefix")))));58 }59 /** Test interface. */60 public interface OnlyTwoValidGetters extends PipelineOptions {61 String getFoo();62 void setFoo(String value);63 boolean isBar();64 void setBar(boolean value);65 String gtMisspelled();66 void setMisspelled(String value);67 String getHasParameter(String value);68 void setHasParameter(String value);69 String noPrefix();70 void setNoPrefix(String value);71 }72 @Test73 public void testBaseClassOptions() {74 Set<PipelineOptionSpec> props =75 PipelineOptionsReflector.getOptionSpecs(ExtendsSimpleOptions.class, true);76 assertThat(props, hasItem(allOf(hasName("foo"), hasClass(SimpleOptions.class))));77 assertThat(props, hasItem(allOf(hasName("foo"), hasClass(ExtendsSimpleOptions.class))));78 assertThat(props, hasItem(allOf(hasName("bar"), hasClass(ExtendsSimpleOptions.class))));79 }80 /** Test interface. */81 public interface ExtendsSimpleOptions extends SimpleOptions {82 @Override83 String getFoo();84 @Override85 void setFoo(String value);86 String getBar();87 void setBar(String value);88 }89 @Test90 public void testExcludesNonPipelineOptionsMethods() {91 Set<PipelineOptionSpec> properties =92 PipelineOptionsReflector.getOptionSpecs(ExtendsNonPipelineOptions.class, true);93 assertThat(properties, not(hasItem(hasName("foo"))));94 }95 /** Test interface. */96 public interface NoExtendsClause {97 String getFoo();98 void setFoo(String value);99 }100 /** Test interface. */101 public interface ExtendsNonPipelineOptions extends NoExtendsClause, PipelineOptions {}102 @Test103 public void testExcludesHiddenInterfaces() {104 Set<PipelineOptionSpec> properties =105 PipelineOptionsReflector.getOptionSpecs(HiddenOptions.class, true);106 assertThat(properties, not(hasItem(hasName("foo"))));107 }108 @Test109 public void testIncludesHiddenInterfaces() {110 Set<PipelineOptionSpec> properties =111 PipelineOptionsReflector.getOptionSpecs(HiddenOptions.class, false);112 assertThat(properties, hasItem(hasName("foo")));113 }114 /** Test interface. */115 @Hidden116 public interface HiddenOptions extends PipelineOptions {117 String getFoo();118 void setFoo(String value);119 }120 @Test121 public void testShouldSerialize() {122 Set<PipelineOptionSpec> properties =123 PipelineOptionsReflector.getOptionSpecs(JsonIgnoreOptions.class, true);124 assertThat(properties, hasItem(allOf(hasName("notIgnored"), shouldSerialize())));125 assertThat(properties, hasItem(allOf(hasName("ignored"), not(shouldSerialize()))));126 }127 /** Test interface. */128 public interface JsonIgnoreOptions extends PipelineOptions {129 String getNotIgnored();130 void setNotIgnored(String value);131 @JsonIgnore132 String getIgnored();133 void setIgnored(String value);134 }135 @Test136 public void testMultipleInputInterfaces() {137 Set<Class<? extends PipelineOptions>> interfaces =138 ImmutableSet.of(BaseOptions.class, ExtendOptions1.class, ExtendOptions2.class);139 Set<PipelineOptionSpec> props = PipelineOptionsReflector.getOptionSpecs(interfaces);140 assertThat(props, hasItem(allOf(hasName("baseOption"), hasClass(BaseOptions.class))));141 assertThat(props, hasItem(allOf(hasName("extendOption1"), hasClass(ExtendOptions1.class))));142 assertThat(props, hasItem(allOf(hasName("extendOption2"), hasClass(ExtendOptions2.class))));143 }144 /** Test interface. */145 public interface BaseOptions extends PipelineOptions {146 String getBaseOption();147 void setBaseOption(String value);148 }149 /** Test interface. */150 public interface ExtendOptions1 extends BaseOptions {151 String getExtendOption1();152 void setExtendOption1(String value);153 }154 /** Test interface. */155 public interface ExtendOptions2 extends BaseOptions {156 String getExtendOption2();157 void setExtendOption2(String value);158 }159 private static Matcher<PipelineOptionSpec> hasName(String name) {160 return hasName(is(name));161 }162 private static Matcher<PipelineOptionSpec> hasName(Matcher<String> matcher) {163 return new FeatureMatcher<PipelineOptionSpec, String>(matcher, "name", "name") {164 @Override165 protected String featureValueOf(PipelineOptionSpec actual) {166 return actual.getName();167 }168 };169 }170 private static Matcher<PipelineOptionSpec> hasClass(Class<?> clazz) {171 return new FeatureMatcher<PipelineOptionSpec, Class<?>>(172 Matchers.<Class<?>>is(clazz), "defining class", "class") {173 @Override174 protected Class<?> featureValueOf(PipelineOptionSpec actual) {175 return actual.getDefiningInterface();176 }177 };178 }179 private static Matcher<PipelineOptionSpec> hasGetter(String methodName) {180 return new FeatureMatcher<PipelineOptionSpec, String>(is(methodName), "getter method", "name") {181 @Override182 protected String featureValueOf(PipelineOptionSpec actual) {183 return actual.getGetterMethod().getName();184 }185 };186 }187 private static Matcher<PipelineOptionSpec> shouldSerialize() {188 return new FeatureMatcher<PipelineOptionSpec, Boolean>(189 equalTo(true), "should serialize", "shouldSerialize") {190 @Override191 protected Boolean featureValueOf(PipelineOptionSpec actual) {192 return actual.shouldSerialize();193 }194 };195 }196}...

Full Screen

Full Screen

Source:HouseTest.java Github

copy

Full Screen

1package net.amygdalum.xrayinterface.examples.house;2import static net.amygdalum.xrayinterface.XRayMatcher.providesFeaturesOf;3import static org.hamcrest.CoreMatchers.instanceOf;4import static org.hamcrest.CoreMatchers.is;5import static org.hamcrest.MatcherAssert.assertThat;6import static org.hamcrest.Matchers.contains;7import static org.hamcrest.Matchers.hasSize;8import java.util.Collection;9import java.util.List;10import org.hamcrest.Matcher;11import org.junit.Before;12import org.junit.Test;13import net.amygdalum.xrayinterface.IsEquivalent;14import net.amygdalum.xrayinterface.XRayInterface;15public class HouseTest {16 private Key key;17 private House house;18 @Before19 public void before() {20 key = new Key();21 house = new House(key);22 house.add(new Safe());23 house.lock(key);24 }25 @Test26 public void testHouseOwner() throws Exception {27 boolean open = house.open(key);28 assertThat(open, is(true));29 List<Furniture> furniture = house.listFurniture();30 assertThat(furniture, contains(instanceOf(Safe.class)));31 }32 @Test(expected = UnsupportedOperationException.class)33 public void testBrute() throws Exception {34 house.listFurniture();35 }36 @Test37 public void testStranger() throws Exception {38 boolean open = house.open(new Key());39 assertThat(open, is(false));40 }41 @Test42 public void testLockpicker() throws Exception {43 XRayHouse xrayHouse = XRayInterface.xray(house).to(XRayHouse.class);44 xrayHouse.open();45 List<Furniture> furniture = house.listFurniture();46 assertThat(furniture, contains(instanceOf(Safe.class)));47 }48 @Test49 public void testAquiringHousekey() throws Exception {50 XRayHouseWithKeyGetter xrayHouse = XRayInterface.xray(house).to(XRayHouseWithKeyGetter.class);51 key = xrayHouse.getHouseKey();52 house.open(key);53 List<Furniture> furniture = house.listFurniture();54 assertThat(furniture, contains(instanceOf(Safe.class)));55 }56 @Test57 public void testChangingLock() throws Exception {58 XRayHouseWithKeySetter xrayHouse = XRayInterface.xray(house).to(XRayHouseWithKeySetter.class);59 xrayHouse.setHouseKey(key);60 house.open(key);61 List<Furniture> furniture = house.listFurniture();62 assertThat(furniture, contains(instanceOf(Safe.class)));63 }64 @Test65 public void testMatchingHouses() throws Exception {66 assertThat(house, XRayHouseMatcher.matchesHouse()67 .withHouseKey(key)68 .withLocked(true)69 .withFurniture(hasSize(1)));70 }71 @Test72 public void testPreventRuntimeErrorsOnXRaying() throws Exception {73 assertThat(House.class, providesFeaturesOf(XRayHouse.class));74 assertThat(House.class, providesFeaturesOf(XRayHouseWithKeyGetter.class));75 assertThat(House.class, providesFeaturesOf(XRayHouseWithKeySetter.class));76 }77 interface XRayHouse {78 void open();79 }80 interface XRayHouseWithKeyGetter {81 Key getHouseKey();82 }83 interface XRayHouseWithKeySetter {84 void setHouseKey(Key key);85 }86 interface XRayHouseMatcher extends Matcher<House> {87 XRayHouseMatcher withHouseKey(Key key);88 XRayHouseMatcher withLocked(boolean locked);89 XRayHouseMatcher withFurniture(Matcher<Collection<? extends Object>> furniture);90 91 static XRayHouseMatcher matchesHouse() {92 return IsEquivalent.equivalentTo(XRayHouseMatcher.class);93 }94 95 }96}...

Full Screen

Full Screen

Source:HamcrestAdapter.java Github

copy

Full Screen

1/*2 * Copyright (c) 2006-2011 Rogério Liesenfeld3 * This file is subject to the terms of the MIT license (see LICENSE.txt).4 */5package mockit.external.hamcrest;67import java.lang.reflect.*;89import mockit.internal.util.*;1011import static mockit.internal.util.Utilities.*;1213/**14 * Adapts the {@code org.hamcrest.Matcher} interface to {@link mockit.external.hamcrest.Matcher}.15 */16@SuppressWarnings({"UnnecessaryFullyQualifiedName"})17public final class HamcrestAdapter<T> extends BaseMatcher<T>18{19 private final org.hamcrest.Matcher<T> hamcrestMatcher;2021 public static <T> HamcrestAdapter<T> create(final Object matcher)22 {23 org.hamcrest.Matcher<T> hamcrestMatcher;2425 if (matcher instanceof org.hamcrest.Matcher<?>) {26 //noinspection unchecked27 hamcrestMatcher = (org.hamcrest.Matcher<T>) matcher;28 }29 else {30 hamcrestMatcher = new org.hamcrest.BaseMatcher<T>()31 {32 Method handler;3334 public boolean matches(Object value)35 {36 if (handler == null) {37 handler = Utilities.findNonPrivateHandlerMethod(matcher);38 }3940 Boolean result = Utilities.invoke(matcher, handler, value);4142 return result == null || result;43 }4445 public void describeTo(org.hamcrest.Description description)46 {47 }48 };49 }5051 return new HamcrestAdapter<T>(hamcrestMatcher);52 }5354 private HamcrestAdapter(org.hamcrest.Matcher<T> matcher)55 {56 hamcrestMatcher = matcher;57 }5859 public boolean matches(Object item)60 {61 return hamcrestMatcher.matches(item);62 }6364 public void describeTo(Description description)65 {66 org.hamcrest.Description strDescription = new org.hamcrest.StringDescription();67 hamcrestMatcher.describeTo(strDescription);68 description.appendText(strDescription.toString());69 }7071 public Object getInnerValue()72 {73 Object innermostMatcher = getInnermostMatcher();7475 return getArgumentValueFromMatcherIfAvailable(innermostMatcher);76 }7778 private Object getInnermostMatcher()79 {80 org.hamcrest.Matcher<T> innerMatcher = hamcrestMatcher;8182 while (83 innerMatcher instanceof org.hamcrest.core.Is ||84 innerMatcher instanceof org.hamcrest.core.IsNot85 ) {86 //noinspection unchecked87 innerMatcher = getField(innerMatcher.getClass(), org.hamcrest.Matcher.class, innerMatcher);88 }8990 return innerMatcher;91 }9293 private Object getArgumentValueFromMatcherIfAvailable(Object argMatcher)94 {95 if (96 argMatcher instanceof org.hamcrest.core.IsEqual ||97 argMatcher instanceof org.hamcrest.core.IsSame ||98 "org.hamcrest.number.OrderingComparison".equals(argMatcher.getClass().getName())99 ) {100 return getField(argMatcher.getClass(), Object.class, argMatcher);101 }102103 return null;104 }105} ...

Full Screen

Full Screen

Source:MatcherBuilder.java Github

copy

Full Screen

1package com.bluecatcode.hamcrest.matchers;2import org.hamcrest.Description;3import org.hamcrest.Factory;4import org.hamcrest.Matcher;5import org.hamcrest.TypeSafeMatcher;6import javax.annotation.Nullable;7public class MatcherBuilder<T> extends TypeSafeMatcher<T> {8 protected final T item;9 private final ItemMatcher<T> itemMatcher;10 private final ObjectDescriber<T> objectDescriber;11 private final MismatchDescriber<T> mismatchDescriber;12 public MatcherBuilder(T item,13 ItemMatcher<T> itemMatcher,14 ObjectDescriber<T> objectDescriber,15 MismatchDescriber<T> mismatchDescriber) {16 if (itemMatcher == null) {17 throw new IllegalArgumentException("Expected an item matcher");18 }19 if (objectDescriber == null) {20 throw new IllegalArgumentException("Expected an object description");21 }22 if (mismatchDescriber == null) {23 throw new IllegalArgumentException("Expected an mismatch describer");24 }25 this.item = item;26 this.itemMatcher = itemMatcher;27 this.objectDescriber = objectDescriber;28 this.mismatchDescriber = mismatchDescriber;29 }30 @Override31 protected boolean matchesSafely(@Nullable T item) {32 return itemMatcher.match(item);33 }34 @Override35 public void describeMismatchSafely(T item, Description mismatchDescription) {36 mismatchDescriber.describe(item, mismatchDescription);37 }38 @Override39 public void describeTo(Description description) {40 objectDescriber.describe(item, description);41 }42 interface ItemMatcher<T> {43 boolean match(@Nullable T item);44 }45 interface MismatchDescriber<T> {46 Description describe(@Nullable T item, Description mismatchDescription);47 }48 interface ObjectDescriber<T> {49 Description describe(@Nullable T item, Description description);50 }51 @Factory52 public static <T> Matcher<T> newMatcher(T item,53 ItemMatcher<T> itemMatcher,54 ObjectDescriber<T> objectDescriber,55 MismatchDescriber<T> mismatchDescriber) {56 return new MatcherBuilder<>(item, itemMatcher, objectDescriber, mismatchDescriber);57 }58 @Factory59 public static <T> Matcher<T> newMatcher(T item,60 ItemMatcher<T> itemMatcher) {61 return new MatcherBuilder<>(item, itemMatcher,62 (o, description) -> description.appendText(o == null ? "null" : o.getClass().getSimpleName()),63 (i, mismatchDescription) -> mismatchDescription.appendText("was ").appendValue(i)64 );65 }66}...

Full Screen

Full Screen

Source:IsCompatibleTypeTest.java Github

copy

Full Screen

1package org.hamcrest.object;2import org.hamcrest.AbstractMatcherTest;3import org.hamcrest.Matcher;4import static org.hamcrest.MatcherAssert.assertThat;5import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith;6public class IsCompatibleTypeTest extends AbstractMatcherTest {7 public static class BaseClass {8 }9 public static class ExtendedClass extends BaseClass {10 }11 public interface BaseInterface {12 }13 public interface ExtendedInterface extends BaseInterface {14 }15 public static class ClassImplementingBaseInterface implements BaseInterface {16 }17 @Override18 protected Matcher<?> createMatcher() {19 return typeCompatibleWith(BaseClass.class);20 }21 public void testMatchesSameClass() {22 assertThat(BaseClass.class, typeCompatibleWith(BaseClass.class));23 }24 public void testMatchesSameInterface() {25 assertThat(BaseInterface.class, typeCompatibleWith(BaseInterface.class));26 }27 public void testMatchesExtendedClass() {28 assertThat(ExtendedClass.class, typeCompatibleWith(BaseClass.class));29 }30 public void testMatchesClassImplementingInterface() {31 assertThat(ClassImplementingBaseInterface.class, typeCompatibleWith(BaseInterface.class));32 }33 public void testMatchesExtendedInterface() {34 assertThat(ExtendedInterface.class, typeCompatibleWith(BaseInterface.class));35 }36// public void testDoesNotMatchIncompatibleTypes() {37// assertThat(BaseClass.class, not(compatibleType(ExtendedClass.class)));38// assertThat(Integer.class, not(compatibleType(String.class)));39// }40 public void testHasReadableDescription() {41 assertDescription("type < java.lang.Runnable", typeCompatibleWith(Runnable.class));42 }43}...

Full Screen

Full Screen

Source:XRayMatcherTest.java Github

copy

Full Screen

1package net.amygdalum.xrayinterface;2import static org.hamcrest.CoreMatchers.containsString;3import static org.hamcrest.CoreMatchers.equalTo;4import static org.hamcrest.MatcherAssert.assertThat;5import org.hamcrest.Description;6import org.hamcrest.StringDescription;7import org.junit.Test;8public class XRayMatcherTest {9 @Test10 public void testDescribeTo() throws Exception {11 XRayMatcher matcher = new XRayMatcher(UnlockedInterface.class);12 Description description = new StringDescription();13 matcher.describeTo(description);14 assertThat(description.toString(), equalTo("can unlock features of <interface net.amygdalum.xrayinterface.XRayMatcherTest$UnlockedInterface>"));15 }16 @Test17 public void testDescribeMismatchSafely() throws Exception {18 XRayMatcher matcher = new XRayMatcher(UnlockedInterface.class);19 Description description = new StringDescription();20 matcher.describeMismatch(Object.class, description);21 assertThat(description.toString(), containsString("cannot map following members in <class java.lang.Object>: "));22 assertThat(description.toString(), containsString("void setStr(String)"));23 assertThat(description.toString(), containsString("int getI()"));24 }25 interface UnlockedInterface {26 void setStr(String str);27 int getI();28 }29}...

Full Screen

Full Screen

Source:ServerResponseWithCode.java Github

copy

Full Screen

1package com.ft.dropwizard.matcher;2import com.sun.jersey.api.client.UniformInterfaceException;3import org.hamcrest.Description;4import org.hamcrest.Factory;5import org.hamcrest.Matcher;6import org.hamcrest.TypeSafeMatcher;7public class ServerResponseWithCode extends TypeSafeMatcher<UniformInterfaceException> {8 private int code;9 private ServerResponseWithCode(int responseCode) {10 this.code = responseCode;11 }12 @Override13 protected boolean matchesSafely(UniformInterfaceException exception) {14 return exception.getResponse().getStatus() == code;15 }16 @Override17 public void describeTo(Description description) {18 description.appendText("Response with code: " + code);19 }20 @Factory21 public static Matcher<? super UniformInterfaceException> errorCode(int errorCode) {22 return new ServerResponseWithCode(errorCode);23 }24 @Factory25 public static Matcher<? super UniformInterfaceException> responseCode(int responseCode) {26 return new ServerResponseWithCode(responseCode);27 }28}...

Full Screen

Full Screen

Interface Matcher

Using AI Code Generation

copy

Full Screen

1import static org.hamcrest.MatcherAssert.assertThat;2import static org.hamcrest.Matchers.*;3import org.hamcrest.Matcher;4import org.hamcrest.MatcherAssert;5import org.hamcrest.Matchers;6import org.hamcrest.collection.IsIterableContainingInOrder;7import org.hamcrest.core.IsEqual;8import org.hamcrest.core.IsNot;9import org.hamcrest.core.IsNull;10import org.hamcrest.core.StringContains;11import org.junit.Test;12import java.util.Arrays;13import java.util.List;14import java.util.stream.Collectors;15import java.util.stream.Stream;16public class HamcrestInterfaceMatcherTest {17 public void givenString_whenMatchesRegularExpression_thenCorrect() {18 String str = "foo";19 assertThat(str, matchesPattern("f.*"));20 }21 public void givenString_whenMatchesRegularExpressionWithFlags_thenCorrect() {22 String str = "foo";23 assertThat(str, matchesPattern("(?i)f.*"));24 }25 public void givenString_whenMatchesRegularExpressionWithGroups_thenCorrect() {26 String str = "foo";27 Matcher matcher = matchesPattern("f(.)");28 assertThat(str, matcher);29 assertThat(matcher.matches(), is(true));30 assertThat(matcher.groupCount(), is(1));31 assertThat(matcher.group(1), is("o"));32 }33 public void givenString_whenMatchesRegularExpressionWithGroupsAndFlags_thenCorrect() {34 String str = "foo";35 Matcher matcher = matchesPattern("(?i)f(.)");36 assertThat(str, matcher);37 assertThat(matcher.matches(), is(true));38 assertThat(matcher.groupCount(), is(1));39 assertThat(matcher.group(1), is("o"));40 }41 public void givenString_whenMatchesRegularExpressionWithGroupsAndFlagsAndMultipleMatches_thenCorrect() {42 String str = "foo";43 Matcher matcher = matchesPattern("f(.)");44 assertThat(str, matcher);45 assertThat(matcher.matches(), is(true));46 assertThat(matcher.groupCount(), is(1));47 assertThat(matcher.group(1), is("o"));48 matcher.reset("bar");49 assertThat(matcher.matches(), is(false));50 }51 public void givenString_whenMatchesRegularExpressionWithGroupsAndFlagsAndMultipleMatches2_thenCorrect() {52 String str = "foo";53 Matcher matcher = matchesPattern("(?i)f(.)");54 assertThat(str, matcher);55 assertThat(matcher.matches(), is(true));56 assertThat(matcher.groupCount(), is(1));57 assertThat(matcher

Full Screen

Full Screen

Interface Matcher

Using AI Code Generation

copy

Full Screen

1import org.hamcrest.Matcher;2import org.hamcrest.Matchers;3import static org.hamcrest.MatcherAssert.assertThat;4import static org.hamcrest.Matchers.*;5import static org.hamcrest.Matchers.equalTo;6import static org.hamcrest.Matchers.is;7public class HamcrestExample {8 public static void main(String args[]) {9 assertThat(10, is(equalTo(10)));10 }11}

Full Screen

Full Screen

Interface Matcher

Using AI Code Generation

copy

Full Screen

1import static org.hamcrest.MatcherAssert.assertThat;2import static org.hamcrest.Matchers.*;3import org.junit.Test;4public class HamcrestTest {5 public void test() {6 assertThat("Hello World", matchesPattern("Hello.*"));7 }8}

Full Screen

Full Screen
copy
1Operation ArrayList LinkedList 23AddAll (Insert) 101,16719 2623,29291 45Add (Insert-Sequentially) 152,46840 966,6221667Add (insert-randomly) 36527 2919389remove (Delete) 20,56,9095 20,45,49041011contains (Search) 186,15,704 189,64,98112
Full Screen

JUnit Tutorial:

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.

JUnit Tutorial Chapters:

Here are the detailed JUnit testing chapters to help you get started:

  • Importance of Unit testing - Learn why Unit testing is essential during the development phase to identify bugs and errors.
  • Top Java Unit testing frameworks - Here are the upcoming JUnit automation testing frameworks that you can use in 2023 to boost your unit testing.
  • What is the JUnit framework
  • Why is JUnit testing important - Learn the importance and numerous benefits of using the JUnit testing framework.
  • Features of JUnit - Learn about the numerous features of JUnit and why developers prefer it.
  • JUnit 5 vs. JUnit 4: Differences - Here is a complete comparison between JUnit 5 and JUnit 4 testing frameworks.
  • Setting up the JUnit environment - Learn how to set up your JUnit testing environment.
  • Getting started with JUnit testing - After successfully setting up your JUnit environment, this chapter will help you get started with JUnit testing in no time.
  • Parallel testing with JUnit - Parallel Testing can be used to reduce test execution time and improve test efficiency. Learn how to perform parallel testing with JUnit.
  • Annotations in JUnit - When writing automation scripts with JUnit, we can use JUnit annotations to specify the type of methods in our test code. This helps us identify those methods when we run JUnit tests using Selenium WebDriver. Learn in detail what annotations are in JUnit.
  • Assertions in JUnit - Assertions are used to validate or test that the result of an action/functionality is the same as expected. Learn in detail what assertions are and how to use them while performing JUnit testing.
  • Parameterization in JUnit - Parameterized Test enables you to run the same automated test scripts with different variables. By collecting data on each method's test parameters, you can minimize time spent on writing tests. Learn how to use parameterization in JUnit.
  • Nested Tests In JUnit 5 - A nested class is a non-static class contained within another class in a hierarchical structure. It can share the state and setup of the outer class. Learn about nested annotations in JUnit 5 with examples.
  • Best practices for JUnit testing - Learn about the best practices, such as always testing key methods and classes, integrating JUnit tests with your build, and more to get the best possible results.
  • Advanced Use Cases for JUnit testing - Take a deep dive into the advanced use cases, such as how to run JUnit tests in Jupiter, how to use JUnit 5 Mockito for Unit testing, and more for JUnit testing.

JUnit Certification:

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.

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

...Most popular Stackoverflow questions on Interface-Matcher

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful