How to use Annotation Type Factory class of org.hamcrest package

Best junit code snippet using org.hamcrest.Annotation Type Factory

Source:AnnotationBuilderBehaviour.java Github

copy

Full Screen

1package org.jbehave.core.configuration;2import org.hamcrest.Matchers;3import org.jbehave.core.ConfigurableEmbedder;4import org.jbehave.core.InjectableEmbedder;5import org.jbehave.core.annotations.Configure;6import org.jbehave.core.annotations.UsingEmbedder;7import org.jbehave.core.annotations.UsingPaths;8import org.jbehave.core.annotations.UsingSteps;9import org.jbehave.core.configuration.AnnotationBuilder.InstantiationFailed;10import org.jbehave.core.embedder.Embedder;11import org.jbehave.core.embedder.EmbedderControls;12import org.jbehave.core.i18n.LocalizedKeywords;13import org.jbehave.core.steps.CandidateSteps;14import org.jbehave.core.steps.ParameterConverters.ParameterConverter;15import org.jbehave.core.steps.Steps;16import org.junit.Test;17import java.io.ByteArrayOutputStream;18import java.io.PrintStream;19import java.lang.reflect.Type;20import java.util.List;21import static java.util.Arrays.asList;22import static org.hamcrest.MatcherAssert.assertThat;23import static org.hamcrest.Matchers.containsString;24import static org.hamcrest.Matchers.equalTo;25import static org.hamcrest.Matchers.greaterThan;26import static org.hamcrest.Matchers.instanceOf;27import static org.hamcrest.Matchers.is;28import static org.hamcrest.Matchers.notNullValue;29public class AnnotationBuilderBehaviour {30 @Test31 public void shouldReturnDependencies() {32 AnnotationBuilder annotated = new AnnotationBuilder(Annotated.class);33 assertThat(annotated.annotatedClass().getName(), equalTo(Annotated.class.getName()));34 assertThat(annotated.annotationFinder(), instanceOf(AnnotationFinder.class));35 assertThat(annotated.annotationMonitor(), instanceOf(PrintStreamAnnotationMonitor.class));36 }37 @Test38 public void shouldBuildDefaultEmbedderIfAnnotationNotPresent() {39 AnnotationBuilder notAnnotated = new AnnotationBuilder(NotAnnotated.class);40 assertThat(notAnnotated.buildEmbedder(), is(notNullValue()));41 }42 @Test43 public void shouldBuildEmbedderWithAnnotatedControls() {44 AnnotationBuilder annotated = new AnnotationBuilder(AnnotedEmbedderControls.class);45 EmbedderControls embedderControls = annotated.buildEmbedder().embedderControls();46 assertThat(embedderControls.batch(), is(true));47 assertThat(embedderControls.generateViewAfterStories(), is(true));48 assertThat(embedderControls.ignoreFailureInStories(), is(true));49 assertThat(embedderControls.ignoreFailureInView(), is(true));50 assertThat(embedderControls.skip(), is(true));51 assertThat(embedderControls.storyTimeoutInSecs(), equalTo(100L));52 assertThat(embedderControls.threads(), equalTo(2));53 assertThat(embedderControls.verboseFailures(), is(true));54 assertThat(embedderControls.verboseFiltering(), is(true));55 }56 @Test57 public void shouldBuildWithCustomConfiguration() {58 AnnotationBuilder annotated = new AnnotationBuilder(AnnotatedCustomConfiguration.class);59 assertThat(annotated.buildConfiguration(), instanceOf(MyConfiguration.class));60 }61 @Test62 public void shouldBuildCandidateSteps() {63 AnnotationBuilder annotated = new AnnotationBuilder(Annotated.class);64 assertThatStepsInstancesAre(annotated.buildCandidateSteps(), MySteps.class, MyOtherSteps.class);65 }66 @Test67 public void shouldBuildCandidateStepsAsEmptyListIfAnnotationOrAnnotatedValuesNotPresent() {68 ByteArrayOutputStream baos = new ByteArrayOutputStream();69 AnnotationBuilder notAnnotated = new AnnotationBuilder(NotAnnotated.class, new PrintStreamAnnotationMonitor(70 new PrintStream(baos)));71 assertThatStepsInstancesAre(notAnnotated.buildCandidateSteps());72 AnnotationBuilder annotatedWithoutSteps = new AnnotationBuilder(AnnotatedWithoutSteps.class);73 assertThatStepsInstancesAre(annotatedWithoutSteps.buildCandidateSteps());74 assertThat(baos.toString().trim(), is(equalTo("Annotation " + UsingSteps.class + " not found in "75 + NotAnnotated.class)));76 }77 @Test78 public void shouldInheritStepsInstances() {79 AnnotationBuilder annotated = new AnnotationBuilder(AnnotatedInheriting.class);80 assertThatStepsInstancesAre(annotated.buildCandidateSteps(), MyOtherOtherSteps.class, MySteps.class,81 MyOtherSteps.class);82 }83 @Test84 public void shouldNotInheritStepsInstances() {85 AnnotationBuilder builderAnnotated = new AnnotationBuilder(AnnotatedNotInheriting.class);86 assertThatStepsInstancesAre(builderAnnotated.buildCandidateSteps(), MyOtherOtherSteps.class);87 }88 @Test89 public void shouldNotIgnoreFailingStepsInstances() {90 ByteArrayOutputStream baos = new ByteArrayOutputStream();91 AnnotationBuilder annotatedFailing = new AnnotationBuilder(AnnotatedFailing.class,92 new PrintStreamAnnotationMonitor(new PrintStream(baos)));93 try {94 assertThatStepsInstancesAre(annotatedFailing.buildCandidateSteps(), MySteps.class);95 } catch (RuntimeException e) {96 assertThat(baos.toString(), containsString("Element creation failed"));97 assertThat(baos.toString(), containsString("RuntimeException"));98 }99 }100 private void assertThatStepsInstancesAre(List<CandidateSteps> candidateSteps, Class<?>... stepsClasses) {101 for (Class<?> stepsClass : stepsClasses) {102 boolean found = false;103 for (CandidateSteps steps : candidateSteps) {104 Object instance = ((Steps) steps).instance();105 if (instance.getClass() == stepsClass) {106 found = true;107 }108 }109 assertThat(found, is(true));110 }111 }112 @Test113 public void shouldCreateEmbeddableInstanceFromInjectableEmbedder() {114 AnnotationBuilder annotatedInjectable = new AnnotationBuilder(AnnotedInjectable.class);115 Object instance = annotatedInjectable.embeddableInstance();116 assertThat(instance, Matchers.instanceOf(InjectableEmbedder.class));117 Embedder embedder = ((InjectableEmbedder) instance).injectedEmbedder();118 assertThat(embedder.configuration().keywords(), instanceOf(MyKeywords.class));119 assertThat(embedder.metaFilters(), equalTo(asList("+embedder injectable")));120 assertThat(embedder.systemProperties().getProperty("one"), equalTo("One"));121 assertThat(embedder.systemProperties().getProperty("two"), equalTo("Two"));122 assertThatStepsInstancesAre(embedder.stepsFactory().createCandidateSteps(), MySteps.class);123 }124 @Test125 public void shouldCreateEmbeddableInstanceFromInjectableEmbedderWithoutStepsFactory() {126 AnnotationBuilder annotatedInjectable = new AnnotationBuilder(AnnotedInjectableWithoutStepsFactory.class);127 Object instance = annotatedInjectable.embeddableInstance();128 assertThat(instance, Matchers.instanceOf(InjectableEmbedder.class));129 Embedder embedder = ((InjectableEmbedder) instance).injectedEmbedder();130 assertThat(embedder.configuration().keywords(), instanceOf(MyKeywords.class));131 assertThat(embedder.metaFilters(), equalTo(asList("+embedder injectable")));132 assertThatStepsInstancesAre(embedder.candidateSteps(), MySteps.class);133 }134 @Test135 public void shouldCreateEmbeddableInstanceFromConfigurableEmbedder() {136 AnnotationBuilder annotatedConfigurable = new AnnotationBuilder(AnnotedConfigurable.class);137 Object instance = annotatedConfigurable.embeddableInstance();138 assertThat(instance, Matchers.instanceOf(ConfigurableEmbedder.class));139 Embedder embedder = ((ConfigurableEmbedder) instance).configuredEmbedder();140 assertThat(embedder.configuration().keywords(), instanceOf(MyKeywords.class));141 assertThat(embedder.metaFilters(), equalTo(asList("+embedder configurable")));142 assertThatStepsInstancesAre(embedder.stepsFactory().createCandidateSteps(), MySteps.class);143 }144 @Test145 public void shouldCreateEmbeddableInstanceFromConfigurableEmbedderWithoutStepsFactory() {146 AnnotationBuilder annotatedConfigurable = new AnnotationBuilder(AnnotedConfigurableWithoutStepsFactory.class);147 Object instance = annotatedConfigurable.embeddableInstance();148 assertThat(instance, Matchers.instanceOf(ConfigurableEmbedder.class));149 Embedder embedder = ((ConfigurableEmbedder) instance).configuredEmbedder();150 assertThat(embedder.configuration().keywords(), instanceOf(MyKeywords.class));151 assertThat(embedder.metaFilters(), equalTo(asList("+embedder configurable")));152 assertThatStepsInstancesAre(embedder.candidateSteps(), MySteps.class);153 }154 @Test155 public void shouldFindStoryPaths() {156 assertThat(new AnnotationBuilder(AnnotatedWithPaths.class).findPaths().size(), greaterThan(0));157 assertThat(new AnnotationBuilder(AnnotedConfigurable.class).findPaths().size(), equalTo(0));158 }159 @Test160 public void shouldNotCreateEmbeddableInstanceForAnnotatedClassThatIsNotInstantiable() {161 ByteArrayOutputStream baos = new ByteArrayOutputStream();162 AnnotationBuilder annotatedPrivate = new AnnotationBuilder(AnnotatedPrivate.class,163 new PrintStreamAnnotationMonitor(new PrintStream(baos)));164 try {165 annotatedPrivate.embeddableInstance();166 } catch (InstantiationFailed e) {167 assertThat(baos.toString(), containsString("Element creation failed"));168 assertThat(baos.toString(), containsString("IllegalAccessException"));169 }170 }171 @Configure(parameterConverters = { MyParameterConverter.class })172 @UsingSteps(instances = { MySteps.class, MyOtherSteps.class })173 static class Annotated {174 }175 static class MyParameterConverter implements ParameterConverter {176 public boolean accept(Type type) {177 return true;178 }179 public Object convertValue(String value, Type type) {180 return value + "Converted";181 }182 }183 @UsingSteps(instances = { MyOtherOtherSteps.class })184 static class AnnotatedInheriting extends Annotated {185 }186 @UsingSteps(instances = { MyOtherOtherSteps.class }, inheritInstances = false)187 static class AnnotatedNotInheriting extends Annotated {188 }189 @UsingSteps(instances = { MySteps.class, MyFailingSteps.class })190 static class AnnotatedFailing {191 }192 @UsingSteps()193 static class AnnotatedWithoutSteps {194 }195 static class NotAnnotated {196 }197 static class MySteps {198 }199 static class MyOtherSteps {200 }201 static class MyOtherOtherSteps {202 }203 static class MyFailingSteps {204 public MyFailingSteps() {205 throw new RuntimeException();206 }207 }208 @Configure(using = MyConfiguration.class)209 static class AnnotatedCustomConfiguration extends InjectableEmbedder {210 public void run() throws Throwable {211 }212 }213 static class MyConfiguration extends Configuration {214 }215 @UsingEmbedder(batch = true, generateViewAfterStories = true, ignoreFailureInStories = true, ignoreFailureInView = true, skip = true, verboseFailures = true, verboseFiltering = true, storyTimeoutInSecs = 100, threads = 2)216 @UsingSteps(instances = { MySteps.class })217 static class AnnotedEmbedderControls extends InjectableEmbedder {218 public void run() throws Throwable {219 }220 }221 @Configure(keywords = MyKeywords.class)222 @UsingEmbedder(metaFilters = "+embedder injectable", systemProperties = "one=One,two=Two")223 @UsingSteps(instances = { MySteps.class })224 static class AnnotedInjectable extends InjectableEmbedder {225 public void run() throws Throwable {226 }227 }228 @Configure(keywords = MyKeywords.class)229 @UsingEmbedder(metaFilters = "+embedder injectable", stepsFactory = false)230 @UsingSteps(instances = { MySteps.class })231 static class AnnotedInjectableWithoutStepsFactory extends InjectableEmbedder {232 public void run() throws Throwable {233 }234 }235 @Configure(keywords = MyKeywords.class)236 @UsingEmbedder(metaFilters = "+embedder configurable")237 @UsingSteps(instances = { MySteps.class })238 static class AnnotedConfigurable extends ConfigurableEmbedder {239 public void run() throws Throwable {240 }241 }242 @Configure(keywords = MyKeywords.class)243 @UsingEmbedder(metaFilters = "+embedder configurable", stepsFactory = false)244 @UsingSteps(instances = { MySteps.class })245 static class AnnotedConfigurableWithoutStepsFactory extends ConfigurableEmbedder {246 public void run() throws Throwable {247 }248 }249 static class MyKeywords extends LocalizedKeywords {250 }251 @Configure()252 @UsingEmbedder()253 @UsingSteps(instances = { MySteps.class })254 private static class AnnotatedPrivate extends ConfigurableEmbedder {255 public void run() throws Throwable {256 }257 }258 @UsingPaths(searchIn = "src/test/java", includes = { "**/stories/*story" })259 private static class AnnotatedWithPaths {260 }261}...

Full Screen

Full Screen

Source:ReflectiveFactoryReader.java Github

copy

Full Screen

1package org.hamcrest.generator;2import java.lang.annotation.Annotation;3import java.lang.reflect.Method;4import static java.lang.reflect.Modifier.isPublic;5import static java.lang.reflect.Modifier.isStatic;6import java.lang.reflect.ParameterizedType;7import java.lang.reflect.Type;8import java.lang.reflect.TypeVariable;9import java.util.Iterator;10/**11 * Reads a list of Hamcrest factory methods from a class, using standard Java reflection.12 * <h3>Usage</h3>13 * <pre>14 * for (FactoryMethod method : new ReflectiveFactoryReader(MyMatchers.class)) {15 * ...16 * }17 * </pre>18 * <p>All methods matching signature '@Factory public static Matcher<blah> blah(blah)' will be19 * treated as factory methods. To change this behavior, override {@link #isFactoryMethod(Method)}.20 * <p>Caveat: Reflection is hassle-free, but unfortunately cannot expose method parameter names or JavaDoc21 * comments, making the sugar slightly more obscure.22 *23 * @author Joe Walnes24 * @see SugarGenerator25 * @see FactoryMethod26 */27public class ReflectiveFactoryReader implements Iterable<FactoryMethod> {28 private final Class<?> cls;29 private final ClassLoader classLoader;30 public ReflectiveFactoryReader(Class<?> cls) {31 this.cls = cls;32 this.classLoader = cls.getClassLoader();33 }34 @Override35 public Iterator<FactoryMethod> iterator() {36 return new Iterator<FactoryMethod>() {37 private int currentMethod = -1;38 private Method[] allMethods = cls.getMethods();39 @Override40 public boolean hasNext() {41 while (true) {42 currentMethod++;43 if (currentMethod >= allMethods.length) {44 return false;45 } else if (isFactoryMethod(allMethods[currentMethod])) {46 return true;47 } // else carry on looping and try the next one.48 }49 }50 @Override51 public FactoryMethod next() {52 if (outsideArrayBounds()) {53 throw new IllegalStateException("next() called without hasNext() check.");54 }55 return buildFactoryMethod(allMethods[currentMethod]);56 }57 @Override58 public void remove() {59 throw new UnsupportedOperationException();60 }61 private boolean outsideArrayBounds() {62 return currentMethod < 0 || allMethods.length <= currentMethod;63 }64 };65 }66 /**67 * Determine whether a particular method is classified as a matcher factory method.68 * <p/>69 * <p>The rules for determining this are:70 * 1. The method must be public static.71 * 2. It must have a return type of org.hamcrest.Matcher (or something that extends this).72 * 3. It must be marked with the org.hamcrest.Factory annotation.73 * <p/>74 * <p>To use another set of rules, override this method.75 */76 protected boolean isFactoryMethod(Method javaMethod) {77 return isStatic(javaMethod.getModifiers())78 && isPublic(javaMethod.getModifiers())79 && hasFactoryAnnotation(javaMethod)80 && !Void.TYPE.equals(javaMethod.getReturnType());81 }82 @SuppressWarnings("unchecked")83 private boolean hasFactoryAnnotation(Method javaMethod) {84 // We dynamically load the Factory class, to avoid a compile time85 // dependency on org.hamcrest.Factory. This gets around86 // a circular bootstrap issue (because generator is required to87 // compile core).88 try {89 final Class<?> factoryClass = classLoader.loadClass("org.hamcrest.Factory");90 if (!Annotation.class.isAssignableFrom(factoryClass)) {91 throw new RuntimeException("Not an annotation class: " + factoryClass.getCanonicalName());92 }93 return javaMethod.getAnnotation((Class<? extends Annotation>)factoryClass) != null; 94 } catch (ClassNotFoundException e) {95 throw new RuntimeException("Cannot load hamcrest core", e);96 }97 }98 99 private static FactoryMethod buildFactoryMethod(Method javaMethod) {100 FactoryMethod result = new FactoryMethod(101 classToString(javaMethod.getDeclaringClass()),102 javaMethod.getName(), 103 classToString(javaMethod.getReturnType()));104 for (TypeVariable<Method> typeVariable : javaMethod.getTypeParameters()) {105 boolean hasBound = false;106 StringBuilder s = new StringBuilder(typeVariable.getName());107 for (Type bound : typeVariable.getBounds()) {108 if (bound != Object.class) {109 if (hasBound) {110 s.append(" & ");111 } else {112 s.append(" extends ");113 hasBound = true;114 }115 s.append(typeToString(bound));116 }117 }118 result.addGenericTypeParameter(s.toString());119 }120 Type returnType = javaMethod.getGenericReturnType();121 if (returnType instanceof ParameterizedType) {122 ParameterizedType parameterizedType = (ParameterizedType) returnType;123 Type generifiedType = parameterizedType.getActualTypeArguments()[0];124 result.setGenerifiedType(typeToString(generifiedType));125 }126 int paramNumber = 0;127 for (Type paramType : javaMethod.getGenericParameterTypes()) {128 String type = typeToString(paramType);129 // Special case for var args methods.... String[] -> String...130 if (javaMethod.isVarArgs()131 && paramNumber == javaMethod.getParameterTypes().length - 1) {132 type = type.replaceFirst("\\[\\]$", "...");133 }134 result.addParameter(type, "param" + (++paramNumber));135 }136 for (Class<?> exception : javaMethod.getExceptionTypes()) {137 result.addException(typeToString(exception));138 }139 return result;140 }141 /*142 * Get String representation of Type (e.g. java.lang.String or Map&lt;Stuff,? extends Cheese&gt;).143 * <p/>144 * Annoyingly this method wouldn't be needed if java.lang.reflect.Type.toString() behaved consistently145 * across implementations. Rock on Liskov.146 */147 private static String typeToString(Type type) {148 return type instanceof Class<?> ? classToString((Class<?>) type): type.toString();149 }150 private static String classToString(Class<?> cls) {151 final String name = cls.isArray() ? cls.getComponentType().getName() + "[]" : cls.getName();152 return name.replace('$', '.');153 }154}...

Full Screen

Full Screen

Source:TransactionalUserServiceTest.java Github

copy

Full Screen

1package com.bobocode;2import com.bobocode.config.RootConfig;3import com.bobocode.dao.UserDao;4import com.bobocode.dao.impl.JpaUserDao;5import com.bobocode.model.jpa.Role;6import com.bobocode.model.jpa.RoleType;7import com.bobocode.model.jpa.User;8import com.bobocode.service.UserService;9import org.junit.jupiter.api.Test;10import org.springframework.beans.factory.annotation.Autowired;11import org.springframework.context.ApplicationContext;12import org.springframework.context.annotation.Bean;13import org.springframework.context.annotation.Configuration;14import org.springframework.stereotype.Repository;15import org.springframework.stereotype.Service;16import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;17import org.springframework.transaction.PlatformTransactionManager;18import org.springframework.transaction.annotation.Transactional;19import javax.persistence.EntityManagerFactory;20import java.util.List;21import java.util.stream.Stream;22import static java.util.stream.Collectors.toList;23import static org.hamcrest.MatcherAssert.assertThat;24import static org.hamcrest.Matchers.contains;25import static org.hamcrest.Matchers.containsInAnyOrder;26import static org.hamcrest.Matchers.hasProperty;27import static org.hamcrest.Matchers.is;28import static org.hamcrest.core.IsCollectionContaining.hasItem;29import static org.hamcrest.core.IsNull.notNullValue;30@SpringJUnitConfig(RootConfig.class)31@Transactional32class TransactionalUserServiceTest {33 @Configuration34 static class TestConfig {35 @Bean36 TestDataGenerator dataGenerator() {37 return new TestDataGenerator();38 }39 }40 @Autowired41 private ApplicationContext applicationContext;42 @Autowired43 private UserService userService;44 @Autowired45 private UserDao userDao;46 @Autowired47 private TestDataGenerator dataGenerator;48 @Test49 void testTxManagerBeanName() {50 PlatformTransactionManager transactionManager = applicationContext.getBean(PlatformTransactionManager.class, "transactionManager");51 assertThat(transactionManager, notNullValue());52 }53 @Test54 void testUserDaoBeanName() {55 UserDao userDao = applicationContext.getBean(UserDao.class, "userDao");56 assertThat(userDao, notNullValue());57 }58 @Test59 void testEntityManagerFactoryBeanName() {60 EntityManagerFactory entityManagerFactory = applicationContext.getBean(EntityManagerFactory.class, "entityManagerFactory");61 assertThat(entityManagerFactory, notNullValue());62 }63 @Test64 void testUserServiceIsMarkedAsService() {65 Service service = UserService.class.getAnnotation(Service.class);66 assertThat(service, notNullValue());67 }68 @Test69 void testUserDaoIsMarkedAsRepository() {70 Repository repository = JpaUserDao.class.getAnnotation(Repository.class);71 assertThat(repository, notNullValue());72 }73 @Test74 void testUserServiceIsTransactional() {75 Transactional transactional = UserService.class.getAnnotation(Transactional.class);76 assertThat(transactional, notNullValue());77 }78 @Test79 void testUserServiceGetAllIsReadOnly() throws NoSuchMethodException {80 Transactional transactional = UserService.class.getDeclaredMethod("getAll").getAnnotation(Transactional.class);81 assertThat(transactional.readOnly(), is(true));82 }83 @Test84 void testUserServiceGetAllAdminsIsReadOnly() throws NoSuchMethodException {85 Transactional transactional = UserService.class.getDeclaredMethod("getAllAdmins").getAnnotation(Transactional.class);86 assertThat(transactional.readOnly(), is(true));87 }88 @Test89 void testUserDaoIsTransactional() {90 Transactional transactional = JpaUserDao.class.getAnnotation(Transactional.class);91 assertThat(transactional, notNullValue());92 }93 @Test94 void testSaveUser() {95 User user = dataGenerator.generateUser();96 userService.save(user);97 assertThat(userDao.findAll(), hasItem(user));98 }99 @Test100 void testGetAllUsers() {101 List<User> userList = generateUserList(10);102 userList.forEach(userService::save);103 List<User> users = userService.getAll();104 assertThat(users, containsInAnyOrder(userList.toArray()));105 }106 private List<User> generateUserList(int size) {107 return Stream.generate(dataGenerator::generateUser)108 .limit(size)109 .collect(toList());110 }111 @Test112 void testGetAllAdmins() {113 List<User> userList = generateUserList(20);114 userList.forEach(userService::save);115 List<User> admins = userService.getAllAdmins();116 assertThat(admins, containsInAnyOrder(findAdmins(userList).toArray()));117 }118 private List<User> findAdmins(List<User> users) {119 return users.stream()120 .filter(user -> user.getRoles().stream()121 .map(Role::getRoleType)122 .anyMatch(roleType -> roleType.equals(RoleType.ADMIN)))123 .collect(toList());124 }125 @Test126 void testAddNewRole() {127 User user = dataGenerator.generateUser(RoleType.USER);128 userService.save(user);129 userService.addRole(user.getId(), RoleType.ADMIN);130 User loadedUser = userDao.findById(user.getId());131 assertThat(loadedUser.getRoles(), contains(132 hasProperty("roleType", is(RoleType.USER)),133 hasProperty("roleType", is(RoleType.ADMIN)))134 );135 }136}...

Full Screen

Full Screen

Source:EnableAutoConfigurationImportSelectorTests.java Github

copy

Full Screen

1/*2 * Copyright 2012-2015 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.springframework.boot.autoconfigure;17import java.util.List;18import org.junit.Before;19import org.junit.Test;20import org.junit.runner.RunWith;21import org.mockito.Mock;22import org.mockito.runners.MockitoJUnitRunner;23import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;24import org.springframework.beans.factory.support.DefaultListableBeanFactory;25import org.springframework.boot.autoconfigure.condition.ConditionEvaluationReport;26import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;27import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration;28import org.springframework.core.annotation.AnnotationAttributes;29import org.springframework.core.io.DefaultResourceLoader;30import org.springframework.core.io.support.SpringFactoriesLoader;31import org.springframework.core.type.AnnotationMetadata;32import static org.hamcrest.Matchers.contains;33import static org.hamcrest.Matchers.containsInAnyOrder;34import static org.hamcrest.Matchers.equalTo;35import static org.hamcrest.Matchers.hasSize;36import static org.hamcrest.Matchers.is;37import static org.junit.Assert.assertThat;38import static org.mockito.BDDMockito.given;39/**40 * Tests for {@link EnableAutoConfigurationImportSelector}41 *42 * @author Andy Wilkinson43 * @author Stephane Nicoll44 */45@RunWith(MockitoJUnitRunner.class)46public class EnableAutoConfigurationImportSelectorTests {47 private final EnableAutoConfigurationImportSelector importSelector = new EnableAutoConfigurationImportSelector();48 private final ConfigurableListableBeanFactory beanFactory = new DefaultListableBeanFactory();49 @Mock50 private AnnotationMetadata annotationMetadata;51 @Mock52 private AnnotationAttributes annotationAttributes;53 @Before54 public void configureImportSelector() {55 this.importSelector.setBeanFactory(this.beanFactory);56 this.importSelector.setResourceLoader(new DefaultResourceLoader());57 }58 @Test59 public void importsAreSelected() {60 configureExclusions(new String[0], new String[0]);61 String[] imports = this.importSelector.selectImports(this.annotationMetadata);62 assertThat(63 imports.length,64 is(equalTo(SpringFactoriesLoader.loadFactoryNames(65 EnableAutoConfiguration.class, getClass().getClassLoader())66 .size())));67 assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(),68 hasSize(0));69 }70 @Test71 public void classExclusionsAreApplied() {72 configureExclusions(new String[] { FreeMarkerAutoConfiguration.class.getName() },73 new String[0]);74 String[] imports = this.importSelector.selectImports(this.annotationMetadata);75 assertThat(imports.length,76 is(equalTo(getAutoConfigurationClassNames().size() - 1)));77 assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(),78 contains(FreeMarkerAutoConfiguration.class.getName()));79 }80 @Test81 public void classNamesExclusionsAreApplied() {82 configureExclusions(new String[0],83 new String[] { VelocityAutoConfiguration.class.getName() });84 String[] imports = this.importSelector.selectImports(this.annotationMetadata);85 assertThat(imports.length,86 is(equalTo(getAutoConfigurationClassNames().size() - 1)));87 assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(),88 contains(VelocityAutoConfiguration.class.getName()));89 }90 @Test91 public void bothExclusionsAreApplied() {92 configureExclusions(new String[] { VelocityAutoConfiguration.class.getName() },93 new String[] { FreeMarkerAutoConfiguration.class.getName() });94 String[] imports = this.importSelector.selectImports(this.annotationMetadata);95 assertThat(imports.length,96 is(equalTo(getAutoConfigurationClassNames().size() - 2)));97 assertThat(98 ConditionEvaluationReport.get(this.beanFactory).getExclusions(),99 containsInAnyOrder(FreeMarkerAutoConfiguration.class.getName(),100 VelocityAutoConfiguration.class.getName()));101 }102 private void configureExclusions(String[] classExclusion, String[] nameExclusion) {103 given(104 this.annotationMetadata.getAnnotationAttributes(105 EnableAutoConfiguration.class.getName(), true)).willReturn(106 this.annotationAttributes);107 given(this.annotationAttributes.getStringArray("exclude")).willReturn(108 classExclusion);109 given(this.annotationAttributes.getStringArray("excludeName")).willReturn(110 nameExclusion);111 }112 private List<String> getAutoConfigurationClassNames() {113 return SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,114 getClass().getClassLoader());115 }116}...

Full Screen

Full Screen

Source:SpringStepsFactoryAOPBehaviour.java Github

copy

Full Screen

1package org.jbehave.core.steps.spring;2import static org.hamcrest.MatcherAssert.assertThat;3import static org.hamcrest.Matchers.equalTo;4import static org.hamcrest.Matchers.hasItem;5import static org.hamcrest.Matchers.not;6import java.util.List;7import java.util.concurrent.atomic.AtomicInteger;8import org.aspectj.lang.ProceedingJoinPoint;9import org.aspectj.lang.annotation.Around;10import org.aspectj.lang.annotation.Aspect;11import org.hamcrest.BaseMatcher;12import org.hamcrest.Description;13import org.jbehave.core.annotations.Given;14import org.jbehave.core.configuration.MostUsefulConfiguration;15import org.jbehave.core.steps.CandidateSteps;16import org.jbehave.core.steps.Steps;17import org.jbehave.core.steps.spring.SpringStepsFactoryBehaviour.FooSteps;18import org.junit.jupiter.api.Test;19import org.springframework.context.ApplicationContext;20import org.springframework.context.annotation.Bean;21import org.springframework.context.annotation.Configuration;22import org.springframework.context.annotation.EnableAspectJAutoProxy;23import org.springframework.context.annotation.Scope;24import org.springframework.context.annotation.ScopedProxyMode;25class SpringStepsFactoryAOPBehaviour {26 @Test27 void aopEnvelopedStepsCanBeCreated() {28 // Given29 ApplicationContext context = createApplicationContext(StepsWithAOPAnnotationConfiguration.class30 .getName());31 SpringStepsFactory factory = new SpringStepsFactory(32 new MostUsefulConfiguration(), context);33 // When34 List<CandidateSteps> steps = factory.createCandidateSteps();35 // Then36 assertAOPFooStepsFound(steps);37 }38 private void assertAOPFooStepsFound(List<CandidateSteps> steps) {39 // // Only one returned, the IFooSteps will not be detected40 assertThat(steps.size(), equalTo(1));41 assertThat(steps, hasItem(isCandidateStepInstanceOf(FooSteps.class)));42 // Make it explicit that the steps bean with the annotation in the43 // interface is not provided44 assertThat(steps,45 not(hasItem(isCandidateStepInstanceOf(IFooSteps.class))));46 }47 private ApplicationContext createApplicationContext(String... resources) {48 return new SpringApplicationContextFactory(resources)49 .createApplicationContext();50 }51 @Configuration52 @EnableAspectJAutoProxy53 public static class StepsWithAOPAnnotationConfiguration {54 @Bean55 public FooAspect fooAspect() {56 return new FooAspect();57 }58 // JDK Proxy59 @SuppressWarnings("checkstyle:MethodName")60 @Bean61 @Scope(proxyMode = ScopedProxyMode.INTERFACES)62 public SpringStepsFactoryAOPBehaviour.IFooSteps iFooSteps() {63 return new SpringStepsFactoryAOPBehaviour.FooStepsImpl();64 }65 // CGLIB-based66 @Bean67 @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)68 public SpringStepsFactoryBehaviour.FooSteps fooSteps() {69 return new SpringStepsFactoryBehaviour.FooSteps();70 }71 }72 @Aspect73 public static class FooAspect {74 public final AtomicInteger executions = new AtomicInteger(0);75 @Around(value = "bean(fooSteps) || bean(iFooSteps)")76 public Object around(ProceedingJoinPoint pjp) throws Throwable {77 try {78 return pjp.proceed();79 } finally {80 System.err.println("Accounted for "81 + executions.incrementAndGet() + " executions");82 }83 }84 }85 public static interface IFooSteps {86 @Given("a step declared in an interface, with a $param")87 void stepWithAParam(String param);88 }89 public static class FooStepsImpl implements IFooSteps {90 @Override91 public void stepWithAParam(String param) {92 }93 }94 public static CandidateStepsInstanceOfMatcher isCandidateStepInstanceOf(95 Class<?> target) {96 return new CandidateStepsInstanceOfMatcher(target);97 }98 private static class CandidateStepsInstanceOfMatcher extends99 BaseMatcher<CandidateSteps> {100 private final Class<?> target;101 public CandidateStepsInstanceOfMatcher(Class<?> target) {102 this.target = target;103 }104 @Override105 public boolean matches(Object item) {106 if (item instanceof CandidateSteps) {107 Object instance = ((Steps) item).instance();108 return target.isAssignableFrom(instance.getClass());109 }110 return false;111 }112 @Override113 public void describeTo(Description description) {114 description115 .appendText("Step class instantiated from this CandidateStep is of type "116 + target.getName());117 }118 }119}...

Full Screen

Full Screen

Source:ImportBeanDefinitionRegistrarTests.java Github

copy

Full Screen

1/*2 * Copyright 2002-2019 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * https://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.springframework.context.annotation;17import java.lang.annotation.ElementType;18import java.lang.annotation.Retention;19import java.lang.annotation.RetentionPolicy;20import java.lang.annotation.Target;21import org.junit.Test;22import org.springframework.beans.BeansException;23import org.springframework.beans.factory.BeanClassLoaderAware;24import org.springframework.beans.factory.BeanFactory;25import org.springframework.beans.factory.BeanFactoryAware;26import org.springframework.beans.factory.support.BeanDefinitionRegistry;27import org.springframework.context.EnvironmentAware;28import org.springframework.context.MessageSource;29import org.springframework.context.ResourceLoaderAware;30import org.springframework.core.env.Environment;31import org.springframework.core.io.ResourceLoader;32import org.springframework.core.type.AnnotationMetadata;33import static org.hamcrest.CoreMatchers.is;34import static org.hamcrest.CoreMatchers.notNullValue;35import static org.hamcrest.MatcherAssert.assertThat;36/**37 * Integration tests for {@link ImportBeanDefinitionRegistrar}.38 *39 * @author Oliver Gierke40 * @author Chris Beams41 */42public class ImportBeanDefinitionRegistrarTests {43 @Test44 public void shouldInvokeAwareMethodsInImportBeanDefinitionRegistrar() {45 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);46 context.getBean(MessageSource.class);47 assertThat(SampleRegistrar.beanFactory, is(context.getBeanFactory()));48 assertThat(SampleRegistrar.classLoader, is(context.getBeanFactory().getBeanClassLoader()));49 assertThat(SampleRegistrar.resourceLoader, is(notNullValue()));50 assertThat(SampleRegistrar.environment, is(context.getEnvironment()));51 }52 @Sample53 @Configuration54 static class Config {55 }56 @Target(ElementType.TYPE)57 @Retention(RetentionPolicy.RUNTIME)58 @Import(SampleRegistrar.class)59 public @interface Sample {60 }61 private static class SampleRegistrar implements ImportBeanDefinitionRegistrar,62 BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware {63 static ClassLoader classLoader;64 static ResourceLoader resourceLoader;65 static BeanFactory beanFactory;66 static Environment environment;67 @Override68 public void setBeanClassLoader(ClassLoader classLoader) {69 SampleRegistrar.classLoader = classLoader;70 }71 @Override72 public void setBeanFactory(BeanFactory beanFactory) throws BeansException {73 SampleRegistrar.beanFactory = beanFactory;74 }75 @Override76 public void setResourceLoader(ResourceLoader resourceLoader) {77 SampleRegistrar.resourceLoader = resourceLoader;78 }79 @Override80 public void setEnvironment(Environment environment) {81 SampleRegistrar.environment = environment;82 }83 @Override84 public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,85 BeanDefinitionRegistry registry) {86 }87 }88}...

Full Screen

Full Screen

Source:ObjectTypeAnnotationFacetFactoryTest.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,13 * software distributed under the License is distributed on an14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 * KIND, either express or implied. See the License for the16 * specific language governing permissions and limitations17 * under the License.18 */19package org.apache.isis.core.metamodel.facets.object.domainobject;20import org.junit.Before;21import org.junit.Test;22import static org.hamcrest.CoreMatchers.is;23import static org.hamcrest.CoreMatchers.not;24import static org.hamcrest.CoreMatchers.nullValue;25import static org.hamcrest.MatcherAssert.assertThat;26import org.apache.isis.applib.annotation.DomainObject;27import org.apache.isis.core.metamodel.facets.AbstractFacetFactoryJUnit4TestCase;28import org.apache.isis.core.metamodel.facets.ObjectTypeFacetFactory.ProcessObjectTypeContext;29import org.apache.isis.core.metamodel.facets.object.domainobject.logicaltype.LogicalTypeFacetForDomainObjectAnnotation;30import org.apache.isis.core.metamodel.facets.object.logicaltype.LogicalTypeFacet;31import org.apache.isis.core.metamodel.methods.MethodByClassMap;32import lombok.val;33public class ObjectTypeAnnotationFacetFactoryTest extends AbstractFacetFactoryJUnit4TestCase {34 private DomainObjectAnnotationFacetFactory facetFactory;35 @Before36 public void setUp() throws Exception {37 facetFactory = new DomainObjectAnnotationFacetFactory(metaModelContext, new MethodByClassMap());38 }39 @Test40 public void logicalTypeNameAnnotationPickedUpOnClass() {41 @DomainObject(logicalTypeName = "CUS")42 class Customer {43 }44 expectNoMethodsRemoved();45 val context = new ProcessObjectTypeContext(Customer.class, facetHolder);46 facetFactory.processLogicalTypeName(context.synthesizeOnType(DomainObject.class), context);47 final LogicalTypeFacet facet = facetHolder.getFacet(LogicalTypeFacet.class);48 assertThat(facet, is(not(nullValue())));49 assertThat(facet instanceof LogicalTypeFacetForDomainObjectAnnotation, is(true));50 assertThat(facet.value(), is("CUS"));51 }52}...

Full Screen

Full Screen

Source:SpiConfigurationTest.java Github

copy

Full Screen

1package lu.mms.common.quality.junit.platform;2import lu.mms.common.quality.assets.AssetFactory;3import org.junit.jupiter.api.Test;4import org.reflections.Reflections;5import java.lang.annotation.Annotation;6import java.util.Map;7import java.util.Set;8import static lu.mms.common.quality.junit.platform.SpiConfiguration.ROOT_PACKAGE;9import static lu.mms.common.quality.junit.platform.SpiConfiguration.retrieveFactories;10import static org.hamcrest.MatcherAssert.assertThat;11import static org.hamcrest.core.IsEqual.equalTo;12import static org.hamcrest.core.IsIterableContaining.hasItem;13import static org.hamcrest.core.IsNull.notNullValue;14import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;15class SpiConfigurationTest {16 @Test17 void shouldConfirmEachFactoryHasBeenProperlyRegistered() {18 // Arrange19 final Reflections reflections = new Reflections(ROOT_PACKAGE);20 final Set<Class<? extends AssetFactory>> factoryClasses = reflections.getSubTypesOf(AssetFactory.class);21 final Set<Class<? extends Annotation>> frameworkAnnotationClasses = reflections.getSubTypesOf(Annotation.class);22 // Act23 final Map<Class<Annotation>, AssetFactory<Annotation>> factories = retrieveFactories();24 // Assert25 assertThat(factories.size(), equalTo(factoryClasses.size()));26 assertThat(factories.size(), lessThanOrEqualTo(frameworkAnnotationClasses.size()));27 factories.entrySet().stream()28 // Keeping only defined annotations29 .filter(entry -> entry.getKey().getPackage().getName().contains(ROOT_PACKAGE))30 .forEach(entry -> {31 assertThat(entry.getKey(), equalTo(entry.getValue().getType()));32 assertThat(frameworkAnnotationClasses, hasItem(entry.getKey()));33 assertThat(entry.getKey(), notNullValue());34 assertThat(factoryClasses, hasItem(entry.getValue().getClass()));35 });36 }37}...

Full Screen

Full Screen

Annotation Type Factory

Using AI Code Generation

copy

Full Screen

1import org.hamcrest.Description;2import org.hamcrest.Matcher;3import org.hamcrest.TypeSafeMatcher;4import org.openqa.selenium.WebElement;5public class CustomMatcher extends TypeSafeMatcher<WebElement> {6 private String expectedText;7 public CustomMatcher(String expectedText) {8 this.expectedText = expectedText;9 }10 protected boolean matchesSafely(WebElement webElement) {11 return webElement.getText().contains(expectedText);12 }13 public void describeTo(Description description) {14 description.appendText("Element text should contain: " + expectedText);15 }16 public static Matcher<WebElement> containsText(String expectedText) {17 return new CustomMatcher(expectedText);18 }19}20import org.hamcrest.Description;21import org.hamcrest.Matcher;22import org.hamcrest.TypeSafeMatcher;23import org.openqa.selenium.WebElement;24public class CustomMatcher extends TypeSafeMatcher<WebElement> {25 private String expectedText;26 public CustomMatcher(String expectedText) {27 this.expectedText = expectedText;28 }29 protected boolean matchesSafely(WebElement webElement) {30 return webElement.getText().contains(expectedText);31 }32 public void describeTo(Description description) {33 description.appendText("Element text should contain: " + expectedText);34 }35 public static Matcher<WebElement> containsText(String expectedText) {36 return new CustomMatcher(expectedText);37 }38}39import org.hamcrest.Description;40import org.hamcrest.Matcher;41import org.hamcrest.TypeSafeMatcher;42import org.openqa.selenium.WebElement;43public class CustomMatcher extends TypeSafeMatcher<WebElement> {44 private String expectedText;45 public CustomMatcher(String expectedText) {46 this.expectedText = expectedText;47 }48 protected boolean matchesSafely(WebElement webElement) {49 return webElement.getText().contains(expectedText);50 }51 public void describeTo(Description description) {52 description.appendText("Element text should contain: " + expectedText);53 }54 public static Matcher<WebElement> containsText(String expectedText) {55 return new CustomMatcher(expectedText);56 }57}58import org.hamcrest.Description;59import org.hamcrest.Matcher;60import org.hamcrest.TypeSafeMatcher;61import org.openqa.selenium.WebElement;

Full Screen

Full Screen

Annotation Type Factory

Using AI Code Generation

copy

Full Screen

1import org.hamcrest.core.IsNot;2import org.hamcrest.core.IsNull;3import org.hamcrest.core.IsSame;4import org.hamcrest.core.IsEqual;5import org.hamcrest.core.IsInstanceOf;6import org.hamcrest.core.IsCollectionContaining;7import org.hamcrest.core.Is;8import org.hamcrest.core.IsAnything;9import org.hamcrest.core.IsNot;10import org.hamcrest.core.IsNull;11import org.hamcrest.core.IsSame;12import org.hamcrest.core.IsEqual;13import org.hamcrest.core.IsInstanceOf;14import org.hamcrest.core.IsCollectionContaining;15import org.hamcrest.core.Is;16import org.hamcrest.core.IsAnything;17import org.hamcrest.core.IsNot;18import org.hamcrest.core.IsNull;19import org.hamcrest.core.IsSame;20import org.hamcrest.core.IsEqual;21import org.hamcrest.core.IsInstanceOf;22import org.hamcrest.core.IsCollectionContaining;23import org.hamcrest.core.Is;24import org.hamcrest.core.IsAnything;25import org.hamcrest.core.IsNot;26import org.hamcrest.core.IsNull;27import org.hamcrest.core.IsSame;28import org.hamcrest.core.IsEqual;29import org.hamcrest.core.IsInstanceOf;30import org.hamcrest.core.IsCollectionContaining;31import org.hamcrest.core.Is;32import org.hamcrest.core.IsAnything;33import org.hamcrest.core.IsNot;34import org.hamcrest.core.IsNull;35import org.hamcrest.core.IsSame;36import org.hamcrest.core.IsEqual;37import org.hamcrest.core.IsInstanceOf;38import org.hamcrest.core.IsCollectionContaining;39import org.hamcrest.core.Is;40import org.hamcrest.core.IsAnything;41import org.hamcrest.core.IsNot;42import org.hamcrest.core.IsNull;43import org.hamcrest.core.IsSame;44import org.hamcrest.core.IsEqual;45import org.hamcrest.core.IsInstanceOf;46import org.hamcrest.core.IsCollectionContaining;47import org.hamcrest.core.Is;48import org.hamcrest.core.IsAnything;49import org.hamcrest.core.IsNot;50import org.hamcrest.core.IsNull;51import org.hamcrest.core.IsSame;52import org.hamcrest.core.IsEqual;53import org.hamcrest.core.IsInstanceOf;54import org.hamcrest.core.IsCollectionContaining;55import org.hamcrest.core.Is;56import org.hamcrest.core.IsAnything;57import org.hamcrest.core.IsNot;58import org.hamcrest.core.IsNull;59import org.hamcrest.core.IsSame;60import org.hamcrest.core.IsEqual;61import org.hamcrest.core.IsInstanceOf;62import org.hamcrest.core.IsCollectionContaining;63import org.hamcrest.core.Is;64import org.hamcrest.core.IsAnything;65import org.hamcrest.core.IsNot;66import org.hamcrest.core.IsNull;67import org.hamcrest.core.IsSame;68import org.hamcrest.core.IsEqual;69import org.hamcrest.core.IsInstanceOf;70import org.hamcrest.core.IsCollectionContaining;71import org.hamcrest.core.Is;72import org

Full Screen

Full Screen

Annotation Type Factory

Using AI Code Generation

copy

Full Screen

1import org.hamcrest.Description;2import org.hamcrest.Matcher;3import org.hamcrest.TypeSafeMatcher;4import org.hamcrest.core.IsEqual;5public class HasItems<T> extends TypeSafeMatcher<Iterable<? extends T>> {6 private final Matcher<? super T>[] matchers;7 public HasItems(Matcher<? super T>... matchers) {8 this.matchers = matchers;9 }10 @SuppressWarnings("unchecked")11 public HasItems(T... items) {12 this.matchers = new Matcher[items.length];13 for (int i = 0; i < items.length; i++) {14 this.matchers[i] = IsEqual.equalTo(items[i]);15 }16 }17 public void describeTo(Description description) {18 description.appendList("(", ", ", ")", matchers);19 }20 protected boolean matchesSafely(Iterable<? extends T> item) {21 for (Matcher<? super T> matcher : matchers) {22 boolean found = false;23 for (T i : item) {24 if (matcher.matches(i)) {25 found = true;26 break;27 }28 }29 if (!found) {30 return false;31 }32 }33 return true;34 }35 protected void describeMismatchSafely(Iterable<? extends T> item, Description mismatchDescription) {36 mismatchDescription.appendText("was ");37 mismatchDescription.appendValueList("[", ", ", "]", item);38 }39 public static <T> Matcher<Iterable<? extends T>> hasItems(Matcher<? super T>... matchers) {40 return new HasItems<T>(matchers);41 }42 public static <T> Matcher<Iterable<? extends T>> hasItems(T... items) {43 return new HasItems<T>(items);44 }45}46import static org.junit.Assert.assertThat;47import static org.junit.Assert.assertTrue;48import static org.junit.Assert.fail;49import java.util.Arrays;50import java.util.List;51import org.junit.Test;52public class TestHasItems {53 public void testHasItems() {54 List<String> list = Arrays.asList("foo", "bar", "baz");55 assertThat(list, HasItems.hasItems("foo", "bar"));56 assertThat(list, HasItems.hasItems("foo", "bar

Full Screen

Full Screen

Annotation Type Factory

Using AI Code Generation

copy

Full Screen

1import org.hamcrest.MatcherAssert.assertThat;2import org.hamcrest.core.Is;3import org.junit.Test;4public class MyAnnotationTest {5 public void testMyAnnotation() {6 assertThat("This is a test method", Is.is("This is a test method"));7 }8}9import org.hamcrest.MatcherAssert.assertThat;10import org.hamcrest.core.Is;11import org.junit.Test;12import org.junit.runner.RunWith;13import org.junit.runners.JUnit4;14@RunWith(JUnit4.class)15public class MyAnnotationTest {16 public void testMyAnnotation() {17 assertThat("This is a test method", Is.is("This is a test method"));18 }19}20import org.hamcrest.MatcherAssert.assertThat;21import org.hamcrest.core.Is;22import org.junit.Test;23import org.junit.runner.RunWith;24import org.junit.runners.JUnit4;25@RunWith(JUnit4.class)26public class MyAnnotationTest {27 public void testMyAnnotation() {28 assertThat("This is a test method", Is.is("This is a test method"));29 }30}31import org.hamcrest.MatcherAssert.assertThat;32import org.hamcrest.core.Is;33import org.junit.Test;34import org.junit.runner.RunWith;35import org.junit.runners.JUnit4;36@RunWith(JUnit4.class)37public class MyAnnotationTest {

Full Screen

Full Screen

Annotation Type Factory

Using AI Code Generation

copy

Full Screen

1import org.hamcrest.Matcher; 2import org.hamcrest.MatcherAssert; 3import org.hamcrest.Matchers; 4import org.hamcrest.core.Is; 5import org.hamcrest.core.IsEqual; 6import org.hamcrest.core.IsNot; 7import org.junit.Test;

Full Screen

Full Screen
copy
1<build>2 <pluginManagement>3 <plugins>4 <plugin>5 <groupId>org.apache.maven.plugins</groupId>6 <artifactId>maven-compiler-plugin</artifactId>7 <version>3.7.0</version>8 <configuration>9 <compilerArgs>10 <arg>-parameters</arg>11 </compilerArgs>12 </configuration>13 </plugin>14
Full Screen
copy
1@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)2public class SomeClass3
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 Annotation-Type-Factory

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