Source:What's the difference between JPA and Hibernate?
Objects.requireNonNull(someObject);
someObject.doCalc();
Best junit code snippet using org.hamcrest.Interface Description
Source:LicensedConditionTest.java  
1package it.com.atlassian.plugin.connect.plugin.web.condition;2import com.atlassian.plugin.Plugin;3import com.atlassian.plugin.connect.modules.beans.AuthenticationBean;4import com.atlassian.plugin.connect.modules.beans.AuthenticationType;5import com.atlassian.plugin.connect.modules.beans.ConnectAddonBean;6import com.atlassian.plugin.connect.modules.beans.LifecycleBean;7import com.atlassian.plugin.connect.modules.beans.WebItemModuleBean;8import com.atlassian.plugin.connect.modules.beans.nested.I18nProperty;9import com.atlassian.plugin.connect.modules.beans.nested.ScopeName;10import com.atlassian.plugin.connect.modules.beans.nested.SingleConditionBean;11import com.atlassian.plugin.connect.modules.util.ModuleKeyUtils;12import com.atlassian.plugin.connect.testsupport.TestPluginInstaller;13import com.atlassian.plugin.connect.testsupport.util.auth.TestAuthenticator;14import com.atlassian.plugin.web.WebInterfaceManager;15import com.atlassian.plugin.web.conditions.ConditionLoadingException;16import com.atlassian.plugin.web.descriptors.WebItemModuleDescriptor;17import com.atlassian.plugins.osgi.test.AtlassianPluginsTestRunner;18import com.google.common.collect.ImmutableList;19import com.google.common.collect.Sets;20import it.com.atlassian.plugin.connect.util.TimebombedLicenseManager;21import org.hamcrest.Description;22import org.hamcrest.Matcher;23import org.hamcrest.TypeSafeMatcher;24import org.junit.After;25import org.junit.Before;26import org.junit.Test;27import org.junit.runner.RunWith;28import java.io.IOException;29import java.util.Collections;30import static org.hamcrest.MatcherAssert.assertThat;31import static org.hamcrest.Matchers.contains;32import static org.hamcrest.Matchers.not;33@RunWith(AtlassianPluginsTestRunner.class)34public class LicensedConditionTest {35    public static final String LOCATION = "fake-addon-location";36    public static final String ADDON_MODULE_KEY = "test-addon-module-key";37    private final TestPluginInstaller testPluginInstaller;38    private final TimebombedLicenseManager timebombedLicenseManager;39    private final TestAuthenticator testAuthenticator;40    private final WebInterfaceManager webInterfaceManager;41    public LicensedConditionTest(TimebombedLicenseManager timebombedLicenseManager,42                                 TestPluginInstaller testPluginInstaller,43                                 TestAuthenticator testAuthenticator, WebInterfaceManager webInterfaceManager) {44        this.testPluginInstaller = testPluginInstaller;45        this.testAuthenticator = testAuthenticator;46        this.timebombedLicenseManager = timebombedLicenseManager;47        this.webInterfaceManager = webInterfaceManager;48    }49    private Plugin installJsonAddon(String addonKey) throws IOException {50        final WebItemModuleBean licenseConditionWebItem = WebItemModuleBean.newWebItemBean()51                .withKey(ADDON_MODULE_KEY)52                .withName(new I18nProperty(ADDON_MODULE_KEY, "blaw"))53                .withLocation(LOCATION)54                .withUrl("/nowhere")55                .withConditions(ImmutableList.of(56                        SingleConditionBean.newSingleConditionBean().withCondition("addon_is_licensed").build()57                ))58                .build();59        ConnectAddonBean addonBean = ConnectAddonBean.newConnectAddonBean()60                .withKey(addonKey)61                .withBaseurl(testPluginInstaller.getInternalAddonBaseUrl(addonKey))62                .withDescription(getClass().getCanonicalName())63                .withAuthentication(AuthenticationBean.newAuthenticationBean().withType(AuthenticationType.JWT).build())64                .withScopes(Sets.newHashSet(ScopeName.READ))65                .withLifecycle(LifecycleBean.newLifecycleBean().withInstalled("/installed").build())66                .withModule("webItems", licenseConditionWebItem)67                .withLicensing(true)68                .build();69        return testPluginInstaller.installAddon(addonBean);70    }71    @Before72    public void setUp() throws ConditionLoadingException, IOException {73        timebombedLicenseManager.setLicense();74    }75    @After76    public void tearDown() throws IOException {77        for (String key : testPluginInstaller.getInstalledAddonKeys()) {78            testPluginInstaller.uninstallAddon(key);79        }80    }81    @Test82    public void webItemsDisplayedWhenLicensedAndAddonIsLicensedConditionPresent() throws IOException {83        testAuthenticator.authenticateUser("admin");84        String addonKey = timebombedLicenseManager.generateLicensedAddonKey();85        final Plugin plugin = installJsonAddon(addonKey);86        final Iterable<WebItemModuleDescriptor> displayableWebItems = webInterfaceManager.getDisplayableItems(LOCATION, Collections.emptyMap());87        assertThat(displayableWebItems, contains(webItemWithKey(plugin, ADDON_MODULE_KEY)));88    }89    @Test90    public void webItemsNotDisplayedWhenUnlicensedAndAddonIsLicensedConditionPresent() throws IOException {91        testAuthenticator.authenticateUser("admin");92        String addonKey = timebombedLicenseManager.generateUnlicensedAddonKey();93        final Plugin plugin = installJsonAddon(addonKey);94        final Iterable<WebItemModuleDescriptor> displayableWebItems = webInterfaceManager.getDisplayableItems(LOCATION, Collections.emptyMap());95        assertThat(displayableWebItems, not(contains(webItemWithKey(plugin, ADDON_MODULE_KEY))));96    }97    private Matcher<WebItemModuleDescriptor> webItemWithKey(Plugin plugin, String key) {98        return new TypeSafeMatcher<WebItemModuleDescriptor>() {99            @Override100            protected boolean matchesSafely(WebItemModuleDescriptor item) {101                return getWebItemKey(item).equals(getWebItemModuleKey());102            }103            @Override104            public void describeTo(Description description) {105                description.appendText("web item with key ");106                description.appendValue(getWebItemModuleKey());107            }108            @Override109            protected void describeMismatchSafely(WebItemModuleDescriptor item, Description mismatchDescription) {110                mismatchDescription.appendText("web item with key ");111                mismatchDescription.appendValue(getWebItemKey(item));112            }113            private String getWebItemKey(WebItemModuleDescriptor item) {114                return item.getKey();115            }116            private String getWebItemModuleKey() {117                return ModuleKeyUtils.addonAndModuleKey(plugin.getKey(), key);118            }119        };120    }121}...Source:ConnectConditionClassResolverTest.java  
1package it.com.atlassian.plugin.connect.plugin.web.condition;2import com.atlassian.plugin.connect.modules.beans.AuthenticationBean;3import com.atlassian.plugin.connect.modules.beans.ConnectAddonBean;4import com.atlassian.plugin.connect.modules.beans.WebItemModuleBean;5import com.atlassian.plugin.connect.modules.beans.nested.I18nProperty;6import com.atlassian.plugin.connect.modules.util.ModuleKeyUtils;7import com.atlassian.plugin.connect.plugin.web.item.WebItemModuleProvider;8import com.atlassian.plugin.connect.testsupport.TestPluginInstaller;9import com.atlassian.plugin.connect.testsupport.util.AddonUtil;10import com.atlassian.plugin.connect.testsupport.util.auth.TestAuthenticator;11import com.atlassian.plugin.web.WebInterfaceManager;12import com.atlassian.plugin.web.descriptors.WebItemModuleDescriptor;13import com.atlassian.plugins.osgi.test.AtlassianPluginsTestRunner;14import it.com.atlassian.plugin.connect.plugin.AbstractConnectAddonTest;15import org.hamcrest.Description;16import org.hamcrest.Matcher;17import org.hamcrest.TypeSafeMatcher;18import org.junit.Test;19import org.junit.runner.RunWith;20import java.io.IOException;21import java.util.Collections;22import java.util.List;23import static com.atlassian.plugin.connect.modules.beans.ConnectAddonBean.newConnectAddonBean;24import static com.atlassian.plugin.connect.modules.beans.WebItemModuleBean.newWebItemBean;25import static com.atlassian.plugin.connect.modules.beans.nested.SingleConditionBean.newSingleConditionBean;26import static org.hamcrest.MatcherAssert.assertThat;27import static org.hamcrest.Matchers.contains;28@RunWith(AtlassianPluginsTestRunner.class)29public class ConnectConditionClassResolverTest extends AbstractConnectAddonTest {30    private static final String LOCATION = "fake-location";31    private final WebInterfaceManager webInterfaceManager;32    public ConnectConditionClassResolverTest(WebItemModuleProvider webItemModuleProvider,33                                             TestPluginInstaller testPluginInstaller,34                                             TestAuthenticator testAuthenticator,35                                             WebInterfaceManager webInterfaceManager) {36        super(webItemModuleProvider, testPluginInstaller, testAuthenticator);37        this.webInterfaceManager = webInterfaceManager;38    }39    @Test40    @SuppressWarnings("unchecked")41    public void shouldApplyPluginProvidedConditionsToWebItems() throws IOException {42        String visibleItemKey = "visible-item";43        String hiddenItemKey = "hidden-item";44        ConnectAddonBean addon = newConnectAddonBean()45                .withKey(AddonUtil.randomPluginKey())46                .withBaseurl("http://example.com")47                .withAuthentication(AuthenticationBean.none())48                .withModules("webItems",49                        buildWebItem(visibleItemKey, "Visible", "always-display"),50                        buildWebItem(hiddenItemKey, "Hidden", "never-display"))51                .build();52        plugin = testPluginInstaller.installAddon(addon);53        List<WebItemModuleDescriptor> webItems = webInterfaceManager.getItems(LOCATION);54        List<WebItemModuleDescriptor> displayableWebItems = webInterfaceManager.getDisplayableItems(LOCATION, Collections.emptyMap());55        assertThat(webItems, contains(webItemWithKey(visibleItemKey), webItemWithKey(hiddenItemKey)));56        assertThat(displayableWebItems, contains(webItemWithKey(visibleItemKey)));57    }58    private WebItemModuleBean buildWebItem(String key, String name, String condition) {59        return newWebItemBean()60                .withKey(key)61                .withUrl("/")62                .withName(new I18nProperty(name, ""))63                .withConditions(newSingleConditionBean().withCondition(condition).build())64                .withLocation(LOCATION)65                .build();66    }67    private Matcher<WebItemModuleDescriptor> webItemWithKey(String key) {68        return new TypeSafeMatcher<WebItemModuleDescriptor>() {69            @Override70            protected boolean matchesSafely(WebItemModuleDescriptor item) {71                return getWebItemKey(item).equals(getWebItemModuleKey());72            }73            @Override74            public void describeTo(Description description) {75                description.appendText("web item with key ");76                description.appendValue(getWebItemModuleKey());77            }78            @Override79            protected void describeMismatchSafely(WebItemModuleDescriptor item, Description mismatchDescription) {80                mismatchDescription.appendText("web item with key ");81                mismatchDescription.appendValue(getWebItemKey(item));82            }83            private String getWebItemKey(WebItemModuleDescriptor item) {84                return item.getKey();85            }86            private String getWebItemModuleKey() {87                return ModuleKeyUtils.addonAndModuleKey(plugin.getKey(), key);88            }89        };90    }91}...Source:IsEquivalent.java  
1package net.amygdalum.xrayinterface;2import java.lang.reflect.Field;3import java.lang.reflect.Method;4import java.util.LinkedHashMap;5import java.util.Map;6import org.hamcrest.BaseMatcher;7import org.hamcrest.Description;8import org.hamcrest.Matcher;9import org.hamcrest.StringDescription;10import org.hamcrest.core.IsEqual;11import org.hamcrest.core.IsNull;12public class IsEquivalent<S, T extends Matcher<S>> extends BaseMatcher<S> {13	private static final String WITH = "with";14	private Class<T> interfaceClazz;15	private Map<String, Object> properties;16	public IsEquivalent(Class<T> interfaceClazz) {17		this.interfaceClazz = interfaceClazz;18		this.properties = new LinkedHashMap<String, Object>();19	}20	public static <S, T extends Matcher<S>> T equivalentTo(Class<T> interfaceClazz) {21		return new XRayInterfaceWith<S, T>(new IsEquivalent<S, T>(interfaceClazz)).to(interfaceClazz);22	}23	protected MethodInvocationHandler handle(final String name) {24		return new MethodInvocationHandler() {25			@SuppressWarnings("unchecked")26			@Override27			public Object invoke(Object object, Object... args) throws Throwable {28				((IsEquivalent<S, T>) object).properties.put(name, args[0]);29				return new XRayInterfaceWith<S, T>(IsEquivalent.this).to(interfaceClazz);30			}31		};32	}33	@Override34	public boolean matches(Object item) {35		if (item == null) {36			return false;37		}38		for (Map.Entry<String, Object> property : properties.entrySet()) {39			String name = property.getKey();40			Object value = property.getValue();41			try {42				Object itemValue = propertyValueFor(item, name);43				Matcher<?> matcher = matcherFor(value);44				if (!matcher.matches(itemValue)) {45					return false;46				}47			} catch (NoSuchFieldException e) {48				return false;49			}50		}51		return true;52	}53	private Object propertyValueFor(Object item, String name) throws NoSuchFieldException {54		Class<?> currentClass = item.getClass();55		while (currentClass != null) {56			for (String fieldName : SignatureUtil.computeFieldNames(name)) {57				try {58					Field field = currentClass.getDeclaredField(fieldName);59					field.setAccessible(true);60					return field.get(item);61				} catch (Exception e) {62					continue;63				}64			}65			currentClass = currentClass.getSuperclass();66		}67		throw new NoSuchFieldException(name);68	}69	private Matcher<?> matcherFor(Object value) {70		if (value instanceof Matcher<?>) {71			return (Matcher<?>) value;72		} else if (value == null) {73			return IsNull.nullValue();74		} else {75			return IsEqual.equalTo(value);76		}77	}78	@Override79	public void describeTo(Description description) {80		description.appendText("with properties ").appendValueList("", ", ", "", properties.entrySet());81	}82	@Override83	public void describeMismatch(Object item, Description description) {84		Map<String, Object> mismatchedProperties = new LinkedHashMap<>();85		for (Map.Entry<String,Object> entry : properties.entrySet()) {86			String property = entry.getKey();87			Object expected = entry.getValue();88			try {89				Object value = propertyValueFor(item, property);90				if (expected instanceof Matcher<?>) {91					value = describe((Matcher<?>) expected, value);92				}93				mismatchedProperties.put(property, value);94			} catch (NoSuchFieldException e) {95				mismatchedProperties.put(property, "<missing>");96			}97		}98		description.appendText("with properties ").appendValueList("", ", ", "", mismatchedProperties.entrySet());99	}100	private String describe(Matcher<?> expected, Object value) {101		StringDescription description = new StringDescription();102		expected.describeMismatch(value, description);103		return description.toString();104	}105	106	@Override107	public boolean equals(Object obj) {108		return super.equals(obj);109	}110	private static final class XRayInterfaceWith<S, T extends Matcher<S>> extends XRayInterface {111		private XRayInterfaceWith(Object object) {112			super(object);113		}114		@SuppressWarnings("unchecked")115		@Override116		protected MethodInvocationHandler findInvocationHandler(Method method) throws NoSuchMethodException, NoSuchFieldException {117			IsEquivalent<S, T> satisfiesMatcher = (IsEquivalent<S, T>) getObject();118			if (method.getName().startsWith(WITH) && method.getParameterTypes().length == 1 && method.getReturnType() == satisfiesMatcher.interfaceClazz) {119				return satisfiesMatcher.handle(method.getName().substring(4));120			}121			return super.findInvocationHandler(method);122		}123	}124}...Source:IsEquivalentTest.java  
1package net.amygdalum.xrayinterface;2import static net.amygdalum.xrayinterface.IsEquivalent.equivalentTo;3import static org.hamcrest.CoreMatchers.containsString;4import static org.hamcrest.CoreMatchers.equalTo;5import static org.hamcrest.CoreMatchers.nullValue;6import static org.hamcrest.MatcherAssert.assertThat;7import static org.hamcrest.Matchers.greaterThan;8import static org.hamcrest.Matchers.lessThan;9import static org.hamcrest.Matchers.not;10import org.hamcrest.CoreMatchers;11import org.hamcrest.Description;12import org.hamcrest.Matcher;13import org.hamcrest.StringDescription;14import org.hamcrest.core.IsNot;15import org.junit.Test;16public class IsEquivalentTest {17	@Test18	public void testComparisonWithNull() throws Exception {19		assertThat((EqTest) null, IsNot.not((Matcher<EqTest>) equivalentTo(EqTestValue.class)20			.withI(0)21			.withStr(null)));22	}23	@Test24	public void testValueBasedDefaultValues() throws Exception {25		assertThat(new EqTest(), equivalentTo(EqTestValue.class)26				.withI(0)27				.withStr(null));28	}29	30	@Test31	public void testValueBasedSetValues() throws Exception {32		assertThat(new EqTest("str", 42), equivalentTo(EqTestValue.class)33			.withI(42)34			.withStr("str"));35	}36	@Test37	public void testMatcherBasedDefaultValues() throws Exception {38		assertThat(new EqTest(), equivalentTo(EqTestMatcher.class)39			.withI(equalTo(0))40			.withStr(nullValue()));41	}42	@Test43	public void testMatcherBasedSetValues() throws Exception {44		assertThat(new EqTest("str", 42), equivalentTo(EqTestMatcher.class)45			.withI(CoreMatchers.<Integer> both(greaterThan(41)).and(lessThan(43)))46			.withStr(containsString("st")));47	}48	@Test49	public void testInheritedProperties() throws Exception {50		assertThat(new EqSubTest("str", 42), equivalentTo(EqSubTestValue.class)51			.withI(42)52			.withStr("str"));53	}54	@Test55	public void testMissingProperties() throws Exception {56		assertThat(new EqSuperTest(42), not(equivalentTo(EqMissingTestValue.class)57			.withI(42)58			.withStr("str")));59	}60	@Test61	public void testDescription() throws Exception {62		EqMissingTestValue matcher = equivalentTo(EqMissingTestValue.class)63			.withI(42)64			.withStr("str");65		Description description = new StringDescription();66		matcher.describeTo(description);67		assertThat(description.toString(), equalTo("with properties <I=42>, <Str=str>"));68	}69	@Test70	public void testMismatchDescription() throws Exception {71		EqMissingTestValue matcher = equivalentTo(EqMissingTestValue.class)72			.withI(42)73			.withStr("str");74		Description description = new StringDescription();75		matcher.describeMismatch(new EqTest("Kölnisch Wasser", 4711), description);76		77		assertThat(description.toString(), equalTo("with properties <I=4711>, <Str=Kölnisch Wasser>"));78	}79	@SuppressWarnings("unused")80	private static class EqTest {81		private String str;82		private int i;83		public EqTest() {84		}85		public EqTest(String str, int i) {86			this.str = str;87			this.i = i;88		}89	}90	@SuppressWarnings("unused")91	private static class EqSubTest extends EqSuperTest {92		private String str;93		public EqSubTest() {94		}95		public EqSubTest(String str, int i) {96			super(i);97			this.str = str;98		}99	}100	@SuppressWarnings("unused")101	private static class EqSuperTest {102		private int i;103		public EqSuperTest() {104		}105		public EqSuperTest(int i) {106			this.i = i;107		}108	}109	interface EqTestValue extends Matcher<EqTest> {110		EqTestValue withStr(String str);111		EqTestValue withI(int i);112	}113	interface EqTestMatcher extends Matcher<EqTest> {114		EqTestMatcher withStr(Matcher<? super String> str);115		EqTestMatcher withI(Matcher<? super Integer> i);116	}117	interface EqSubTestValue extends Matcher<EqSubTest> {118		EqSubTestValue withStr(String str);119		EqSubTestValue withI(int i);120	}121	interface EqMissingTestValue extends Matcher<EqSuperTest> {122		EqMissingTestValue withStr(String str);123		EqMissingTestValue withI(int i);124	}125}...Source:MatcherBuilder.java  
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}...Source:JavaLocalClassTest.java  
1package org.jboss.forge.test.roaster.model;2import static org.hamcrest.CoreMatchers.allOf;3import static org.hamcrest.CoreMatchers.equalTo;4import static org.hamcrest.CoreMatchers.everyItem;5import static org.hamcrest.CoreMatchers.instanceOf;6import java.util.List;7import org.hamcrest.BaseMatcher;8import org.hamcrest.CoreMatchers;9import org.hamcrest.Description;10import org.jboss.forge.roaster.Roaster;11import org.jboss.forge.roaster.model.JavaClass;12import org.jboss.forge.roaster.model.JavaInterface;13import org.jboss.forge.roaster.model.source.JavaClassSource;14import org.jboss.forge.roaster.model.source.JavaSource;15import org.junit.Assert;16import org.junit.Test;17public class JavaLocalClassTest18{19   @Test20   public void testLocalClassMatch()21   {22      JavaClassSource source = Roaster.parse(JavaClassSource.class,23               getClass().getResourceAsStream("/org/jboss/forge/grammar/java/MockLocalClass.java"));24      Assert.assertFalse(source.isLocalClass());25      List<JavaSource<?>> nestedTypes = source.getNestedTypes();26      Assert.assertThat(nestedTypes.size(), equalTo(17));27      Assert.assertThat(nestedTypes.get(0), instanceOf(JavaInterface.class));28      Assert.assertThat(nestedTypes.subList(1, 17),29               everyItem(allOf(CoreMatchers.<JavaSource<?>> instanceOf(JavaClass.class), new IsLocalMatcher())));30   }31   private class IsLocalMatcher extends BaseMatcher<JavaSource<?>>32   {33      @Override34      public boolean matches(Object item)35      {36         if (item instanceof JavaClass)37         {38            return ((JavaClass<?>) item).isLocalClass();39         }40         return false;41      }42      @Override43      public void describeTo(Description description)44      {45         description.appendText("a local class");46      }47      @Override48      public void describeMismatch(Object item, Description description)49      {50         description.appendValue(item).appendText("is not a local class");51      }52   }53}...Source:IsCompatibleTypeTest.java  
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}...Source:XRayMatcherTest.java  
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}...Interface Description
Using AI Code Generation
1import org.hamcrest.Description;2import org.hamcrest.Matcher;3import org.hamcrest.TypeSafeMatcher;4import org.openqa.selenium.By;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.support.ui.Select;9import org.testng.annotations.AfterTest;10import org.testng.annotations.BeforeTest;11import org.testng.annotations.Test;12public class Dropdown {13	WebDriver driver;14	public void setup() {15		System.setProperty("webdriver.chrome.driver", "C:\\Users\\Bhupesh\\Downloads\\chromedriver_win32\\chromedriver.exe");16		driver = new ChromeDriver();17		driver.manage().window().maximize();18	}19	public void dropdown() {20		Select dropdown = new Select(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")));21		dropdown.selectByIndex(1);22		dropdown.selectByValue("USD");23		dropdown.selectByVisibleText("AED");24		java.util.List<WebElement> options = dropdown.getOptions();25		for(WebElement option: options) {26			System.out.println(option.getText());27		}28	}29	public void tearDown() {30		driver.quit();31	}32}33import org.hamcrest.Description;34import org.hamcrest.Matcher;35import org.hamcrest.TypeSafeMatcher;36import org.openqa.selenium.By;37import org.openqa.selenium.WebDriver;38import org.openqa.selenium.WebElement;39import org.openqa.selenium.chrome.ChromeDriver;40import org.openqa.selenium.support.ui.Select;41import org.testng.annotations.AfterTest;42import org.testng.annotations.BeforeTest;43import org.testng.annotations.Test;44public class Dropdown {45	WebDriver driver;46	public void setup() {47		System.setProperty("webdriver.chrome.driver", "C:\\Users\\Bhupesh\\Downloads\\chromedriver_win32\\chromedriver.exe");48		driver = new ChromeDriver();49		driver.manage().window().maximize();50	}51	public void dropdown() {Interface Description
Using AI Code Generation
1import org.hamcrest.Description;2public class MyDescription implements Description {3}4import org.hamcrest.Matcher;5public class MyMatcher implements Matcher {6}7import org.hamcrest.SelfDescribing;8public class MySelfDescribing implements SelfDescribing {9}10import org.hamcrest.TypeSafeMatcher;11public class MyTypeSafeMatcher implements TypeSafeMatcher {12}13import org.hamcrest.TypeSafeDiagnosingMatcher;14public class MyTypeSafeDiagnosingMatcher implements TypeSafeDiagnosingMatcher {15}16import org.hamcrest.BaseMatcher;17public class MyBaseMatcher implements BaseMatcher {18}19import org.hamcrest.CoreMatchers;20public class MyCoreMatchers implements CoreMatchers {21}22import org.hamcrest.Describable;23public class MyDescribable implements Describable {24}25import org.hamcrest.MatcherAssert;26public class MyMatcherAssert implements MatcherAssert {27}28import org.hamcrest.Matchers;29public class MyMatchers implements Matchers {30}31import org.hamcrest.StringDescription;32public class MyStringDescription implements StringDescription {33}34import org.hamcrest.TypeSafeDiagnosingMatcher;1Objects.requireNonNull(someObject);2someObject.doCalc();3LambdaTest 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!!
