How to use Annotation Type Test class of org.junit package

Best junit code snippet using org.junit.Annotation Type Test

Source:AnnotationProcessingUtilsTest.java Github

copy

Full Screen

1// Copyright 2017 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4package org.chromium.base.test.util;5import static org.hamcrest.Matchers.contains;6import static org.junit.Assert.assertEquals;7import static org.junit.Assert.assertNotNull;8import static org.junit.Assert.assertNull;9import static org.junit.Assert.assertThat;10import static org.junit.Assert.fail;11import static org.junit.runner.Description.createTestDescription;12import org.junit.Ignore;13import org.junit.Rule;14import org.junit.Test;15import org.junit.rules.TestRule;16import org.junit.runner.Description;17import org.junit.runner.RunWith;18import org.junit.runners.BlockJUnit4ClassRunner;19import org.junit.runners.model.FrameworkMethod;20import org.junit.runners.model.InitializationError;21import org.junit.runners.model.Statement;22import org.chromium.base.test.util.AnnotationProcessingUtils.AnnotationExtractor;23import java.lang.annotation.Annotation;24import java.lang.annotation.ElementType;25import java.lang.annotation.Retention;26import java.lang.annotation.RetentionPolicy;27import java.lang.annotation.Target;28import java.util.Arrays;29import java.util.Comparator;30import java.util.List;31/** Test for {@link AnnotationProcessingUtils}. */32@RunWith(BlockJUnit4ClassRunner.class)33public class AnnotationProcessingUtilsTest {34 @Test35 public void testGetTargetAnnotation_NotOnClassNorMethod() {36 TargetAnnotation retrievedAnnotation;37 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(38 createTestDescription(39 ClassWithoutTargetAnnotation.class, "methodWithoutAnnotation"),40 TargetAnnotation.class);41 assertNull(retrievedAnnotation);42 }43 @Test44 public void testGetTargetAnnotation_NotOnClassButOnMethod() {45 TargetAnnotation retrievedAnnotation;46 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(47 getTest(ClassWithoutTargetAnnotation.class, "methodWithTargetAnnotation"),48 TargetAnnotation.class);49 assertNotNull(retrievedAnnotation);50 }51 @Test52 public void testGetTargetAnnotation_NotOnClassDifferentOneOnMethod() {53 TargetAnnotation retrievedAnnotation;54 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(55 getTest(ClassWithoutTargetAnnotation.class, "methodWithAnnotatedAnnotation"),56 TargetAnnotation.class);57 assertNull(retrievedAnnotation);58 }59 @Test60 public void testGetTargetAnnotation_OnClassButNotOnMethod() {61 TargetAnnotation retrievedAnnotation;62 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(63 getTest(ClassWithAnnotation.class, "methodWithoutAnnotation"),64 TargetAnnotation.class);65 assertNotNull(retrievedAnnotation);66 assertEquals(Location.Class, retrievedAnnotation.value());67 }68 @Test69 public void testGetTargetAnnotation_OnClassAndMethod() {70 TargetAnnotation retrievedAnnotation;71 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(72 getTest(ClassWithAnnotation.class, "methodWithTargetAnnotation"),73 TargetAnnotation.class);74 assertNotNull(retrievedAnnotation);75 assertEquals(Location.Method, retrievedAnnotation.value());76 }77 @Test78 @Ignore("Rules not supported yet.")79 public void testGetTargetAnnotation_OnRuleButNotOnMethod() {80 TargetAnnotation retrievedAnnotation;81 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(82 getTest(ClassWithRule.class, "methodWithoutAnnotation"), TargetAnnotation.class);83 assertNotNull(retrievedAnnotation);84 assertEquals(Location.Rule, retrievedAnnotation.value());85 }86 @Test87 @Ignore("Rules not supported yet.")88 public void testGetTargetAnnotation_OnRuleAndMethod() {89 TargetAnnotation retrievedAnnotation;90 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(91 getTest(ClassWithRule.class, "methodWithTargetAnnotation"), TargetAnnotation.class);92 assertNotNull(retrievedAnnotation);93 assertEquals(Location.Method, retrievedAnnotation.value());94 }95 @Test96 public void testGetMetaAnnotation_Indirectly() {97 MetaAnnotation retrievedAnnotation;98 retrievedAnnotation = AnnotationProcessingUtils.getAnnotation(99 getTest(ClassWithoutTargetAnnotation.class, "methodWithAnnotatedAnnotation"),100 MetaAnnotation.class);101 assertNotNull(retrievedAnnotation);102 }103 @Test104 public void testGetAllTargetAnnotations() {105 List<TargetAnnotation> retrievedAnnotations;106 retrievedAnnotations = AnnotationProcessingUtils.getAnnotations(107 getTest(ClassWithAnnotation.class, "methodWithTargetAnnotation"),108 TargetAnnotation.class);109 assertEquals(2, retrievedAnnotations.size());110 assertEquals(Location.Class, retrievedAnnotations.get(0).value());111 assertEquals(Location.Method, retrievedAnnotations.get(1).value());112 }113 @Test114 public void testGetAllTargetAnnotations_OnParentClass() {115 List<TargetAnnotation> retrievedAnnotations;116 retrievedAnnotations = AnnotationProcessingUtils.getAnnotations(117 getTest(DerivedClassWithoutAnnotation.class, "newMethodWithoutAnnotation"),118 TargetAnnotation.class);119 assertEquals(1, retrievedAnnotations.size());120 assertEquals(Location.Class, retrievedAnnotations.get(0).value());121 }122 @Test123 public void testGetAllTargetAnnotations_OnDerivedMethodAndParentClass() {124 List<TargetAnnotation> retrievedAnnotations;125 retrievedAnnotations = AnnotationProcessingUtils.getAnnotations(126 getTest(DerivedClassWithoutAnnotation.class, "newMethodWithTargetAnnotation"),127 TargetAnnotation.class);128 assertEquals(2, retrievedAnnotations.size());129 assertEquals(Location.Class, retrievedAnnotations.get(0).value());130 assertEquals(Location.DerivedMethod, retrievedAnnotations.get(1).value());131 }132 @Test133 public void testGetAllTargetAnnotations_OnDerivedMethodAndParentClassAndMethod() {134 List<TargetAnnotation> retrievedAnnotations;135 retrievedAnnotations = AnnotationProcessingUtils.getAnnotations(136 getTest(DerivedClassWithoutAnnotation.class, "methodWithTargetAnnotation"),137 TargetAnnotation.class);138 // We should not look at the base implementation of the method. Mostly it should not happen139 // in the context of tests.140 assertEquals(2, retrievedAnnotations.size());141 assertEquals(Location.Class, retrievedAnnotations.get(0).value());142 assertEquals(Location.DerivedMethod, retrievedAnnotations.get(1).value());143 }144 @Test145 public void testGetAllTargetAnnotations_OnDerivedParentAndParentClass() {146 List<TargetAnnotation> retrievedAnnotations;147 retrievedAnnotations = AnnotationProcessingUtils.getAnnotations(148 getTest(DerivedClassWithAnnotation.class, "methodWithoutAnnotation"),149 TargetAnnotation.class);150 assertEquals(2, retrievedAnnotations.size());151 assertEquals(Location.Class, retrievedAnnotations.get(0).value());152 assertEquals(Location.DerivedClass, retrievedAnnotations.get(1).value());153 }154 @Test155 public void testGetAllAnnotations() {156 List<Annotation> annotations;157 AnnotationExtractor annotationExtractor = new AnnotationExtractor(158 TargetAnnotation.class, MetaAnnotation.class, AnnotatedAnnotation.class);159 annotations = annotationExtractor.getMatchingAnnotations(160 getTest(DerivedClassWithAnnotation.class, "methodWithTwoAnnotations"));161 assertEquals(5, annotations.size());162 // Retrieved annotation order:163 // On Parent Class164 assertEquals(TargetAnnotation.class, annotations.get(0).annotationType());165 assertEquals(Location.Class, ((TargetAnnotation) annotations.get(0)).value());166 // On Class167 assertEquals(TargetAnnotation.class, annotations.get(1).annotationType());168 assertEquals(Location.DerivedClass, ((TargetAnnotation) annotations.get(1)).value());169 // Meta-annotations from method170 assertEquals(MetaAnnotation.class, annotations.get(2).annotationType());171 // On Method172 assertEquals(AnnotatedAnnotation.class, annotations.get(3).annotationType());173 assertEquals(TargetAnnotation.class, annotations.get(4).annotationType());174 assertEquals(Location.DerivedMethod, ((TargetAnnotation) annotations.get(4)).value());175 }176 @SuppressWarnings("unchecked")177 @Test178 public void testAnnotationExtractorSortOrder_UnknownAnnotations() {179 AnnotationExtractor annotationExtractor = new AnnotationExtractor(Target.class);180 Comparator<Class<? extends Annotation>> comparator =181 annotationExtractor.getTypeComparator();182 List<Class<? extends Annotation>> testList =183 Arrays.asList(Rule.class, Test.class, Override.class, Target.class, Rule.class);184 testList.sort(comparator);185 assertThat("Unknown annotations should not be reordered and come before the known ones.",186 testList,187 contains(Rule.class, Test.class, Override.class, Rule.class, Target.class));188 }189 @SuppressWarnings("unchecked")190 @Test191 public void testAnnotationExtractorSortOrder_KnownAnnotations() {192 AnnotationExtractor annotationExtractor =193 new AnnotationExtractor(Test.class, Target.class, Rule.class);194 Comparator<Class<? extends Annotation>> comparator =195 annotationExtractor.getTypeComparator();196 List<Class<? extends Annotation>> testList =197 Arrays.asList(Rule.class, Test.class, Override.class, Target.class, Rule.class);198 testList.sort(comparator);199 assertThat(200 "Known annotations should be sorted in the same order as provided to the extractor",201 testList,202 contains(Override.class, Test.class, Target.class, Rule.class, Rule.class));203 }204 private static Description getTest(Class<?> klass, String testName) {205 Description description = null;206 try {207 description = new DummyTestRunner(klass).describe(testName);208 } catch (InitializationError initializationError) {209 initializationError.printStackTrace();210 fail("DummyTestRunner initialization failed:" + initializationError.getMessage());211 }212 if (description == null) {213 fail("Not test named '" + testName + "' in class" + klass.getSimpleName());214 }215 return description;216 }217 // region Test Data: Annotations and dummy test classes218 private enum Location { Unspecified, Class, Method, Rule, DerivedClass, DerivedMethod }219 @Retention(RetentionPolicy.RUNTIME)220 @Target({ElementType.TYPE, ElementType.METHOD})221 private @interface TargetAnnotation {222 Location value() default Location.Unspecified;223 }224 @Retention(RetentionPolicy.RUNTIME)225 @Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD})226 private @interface MetaAnnotation {}227 @Retention(RetentionPolicy.RUNTIME)228 @Target({ElementType.TYPE, ElementType.METHOD})229 @MetaAnnotation230 private @interface AnnotatedAnnotation {}231 private @interface SimpleAnnotation {}232 @SimpleAnnotation233 private static class ClassWithoutTargetAnnotation {234 @Test235 public void methodWithoutAnnotation() {}236 @Test237 @TargetAnnotation238 public void methodWithTargetAnnotation() {}239 @Test240 @AnnotatedAnnotation241 public void methodWithAnnotatedAnnotation() {}242 }243 @TargetAnnotation(Location.Class)244 private static class ClassWithAnnotation {245 @Test246 public void methodWithoutAnnotation() {}247 @Test248 @TargetAnnotation(Location.Method)249 public void methodWithTargetAnnotation() {}250 @Test251 @MetaAnnotation252 public void methodWithMetaAnnotation() {}253 @Test254 @AnnotatedAnnotation255 public void methodWithAnnotatedAnnotation() {}256 }257 private static class DerivedClassWithoutAnnotation extends ClassWithAnnotation {258 @Test259 public void newMethodWithoutAnnotation() {}260 @Test261 @TargetAnnotation(Location.DerivedMethod)262 public void newMethodWithTargetAnnotation() {}263 @Test264 @Override265 @TargetAnnotation(Location.DerivedMethod)266 public void methodWithTargetAnnotation() {}267 }268 @TargetAnnotation(Location.DerivedClass)269 private static class DerivedClassWithAnnotation extends ClassWithAnnotation {270 @Test271 public void newMethodWithoutAnnotation() {}272 @Test273 @AnnotatedAnnotation274 @TargetAnnotation(Location.DerivedMethod)275 public void methodWithTwoAnnotations() {}276 }277 private static class ClassWithRule {278 @Rule279 Rule1 mRule = new Rule1();280 @Test281 public void methodWithoutAnnotation() {}282 @Test283 @TargetAnnotation284 public void methodWithTargetAnnotation() {}285 }286 @TargetAnnotation(Location.Rule)287 @MetaAnnotation288 private static class Rule1 implements TestRule {289 @Override290 public Statement apply(Statement statement, Description description) {291 return null;292 }293 }294 private static class DummyTestRunner extends BlockJUnit4ClassRunner {295 public DummyTestRunner(Class<?> klass) throws InitializationError {296 super(klass);297 }298 @Override299 protected void collectInitializationErrors(List<Throwable> errors) {300 // Do nothing. BlockJUnit4ClassRunner requires the class to be public, but we don't301 // want/need it.302 }303 public Description describe(String testName) {304 List<FrameworkMethod> tests = getTestClass().getAnnotatedMethods(Test.class);305 for (FrameworkMethod testMethod : tests) {306 if (testMethod.getName().equals(testName)) return describeChild(testMethod);307 }308 return null;309 }310 }311 // endregion312 }...

Full Screen

Full Screen

Source:RuleMemberValidator.java Github

copy

Full Screen

1package org.junit.internal.runners.rules;2import org.junit.ClassRule;3import org.junit.Rule;4import org.junit.rules.MethodRule;5import org.junit.rules.TestRule;6import org.junit.runners.model.FrameworkMember;7import org.junit.runners.model.TestClass;8import java.lang.annotation.Annotation;9import java.lang.reflect.Modifier;10import java.util.ArrayList;11import java.util.List;12/**13 * A RuleMemberValidator validates the rule fields/methods of a14 * {@link org.junit.runners.model.TestClass}. All reasons for rejecting the15 * {@code TestClass} are written to a list of errors.16 *17 * <p>There are four slightly different validators. The {@link #CLASS_RULE_VALIDATOR}18 * validates fields with a {@link ClassRule} annotation and the19 * {@link #RULE_VALIDATOR} validates fields with a {@link Rule} annotation.</p>20 *21 * <p>The {@link #CLASS_RULE_METHOD_VALIDATOR}22 * validates methods with a {@link ClassRule} annotation and the23 * {@link #RULE_METHOD_VALIDATOR} validates methods with a {@link Rule} annotation.</p>24 */25public class RuleMemberValidator {26 /**27 * Validates fields with a {@link ClassRule} annotation.28 */29 public static final RuleMemberValidator CLASS_RULE_VALIDATOR =30 classRuleValidatorBuilder()31 .withValidator(new DeclaringClassMustBePublic())32 .withValidator(new MemberMustBeStatic())33 .withValidator(new MemberMustBePublic())34 .withValidator(new FieldMustBeATestRule())35 .build();36 /**37 * Validates fields with a {@link Rule} annotation.38 */39 public static final RuleMemberValidator RULE_VALIDATOR =40 testRuleValidatorBuilder()41 .withValidator(new MemberMustBeNonStaticOrAlsoClassRule())42 .withValidator(new MemberMustBePublic())43 .withValidator(new FieldMustBeARule())44 .build();45 /**46 * Validates methods with a {@link ClassRule} annotation.47 */48 public static final RuleMemberValidator CLASS_RULE_METHOD_VALIDATOR =49 classRuleValidatorBuilder()50 .forMethods()51 .withValidator(new DeclaringClassMustBePublic())52 .withValidator(new MemberMustBeStatic())53 .withValidator(new MemberMustBePublic())54 .withValidator(new MethodMustBeATestRule())55 .build();56 /**57 * Validates methods with a {@link Rule} annotation.58 */59 public static final RuleMemberValidator RULE_METHOD_VALIDATOR =60 testRuleValidatorBuilder()61 .forMethods()62 .withValidator(new MemberMustBeNonStaticOrAlsoClassRule())63 .withValidator(new MemberMustBePublic())64 .withValidator(new MethodMustBeARule())65 .build();66 private final Class<? extends Annotation> annotation;67 private final boolean methods;68 private final List<RuleValidator> validatorStrategies;69 RuleMemberValidator(Builder builder) {70 this.annotation = builder.annotation;71 this.methods = builder.methods;72 this.validatorStrategies = builder.validators;73 }74 /**75 * Validate the {@link org.junit.runners.model.TestClass} and adds reasons76 * for rejecting the class to a list of errors.77 *78 * @param target the {@code TestClass} to validate.79 * @param errors the list of errors.80 */81 public void validate(TestClass target, List<Throwable> errors) {82 List<? extends FrameworkMember<?>> members = methods ? target.getAnnotatedMethods(annotation)83 : target.getAnnotatedFields(annotation);84 for (FrameworkMember<?> each : members) {85 validateMember(each, errors);86 }87 }88 private void validateMember(FrameworkMember<?> member, List<Throwable> errors) {89 for (RuleValidator strategy : validatorStrategies) {90 strategy.validate(member, annotation, errors);91 }92 }93 private static Builder classRuleValidatorBuilder() {94 return new Builder(ClassRule.class);95 }96 private static Builder testRuleValidatorBuilder() {97 return new Builder(Rule.class);98 }99 private static class Builder {100 private final Class<? extends Annotation> annotation;101 private boolean methods;102 private final List<RuleValidator> validators;103 private Builder(Class<? extends Annotation> annotation) {104 this.annotation = annotation;105 this.methods = false;106 this.validators = new ArrayList<RuleValidator>();107 }108 Builder forMethods() {109 methods = true;110 return this;111 }112 Builder withValidator(RuleValidator validator) {113 validators.add(validator);114 return this;115 }116 RuleMemberValidator build() {117 return new RuleMemberValidator(this);118 }119 }120 private static boolean isRuleType(FrameworkMember<?> member) {121 return isMethodRule(member) || isTestRule(member);122 }123 private static boolean isTestRule(FrameworkMember<?> member) {124 return TestRule.class.isAssignableFrom(member.getType());125 }126 private static boolean isMethodRule(FrameworkMember<?> member) {127 return MethodRule.class.isAssignableFrom(member.getType());128 }129 /**130 * Encapsulates a single piece of validation logic, used to determine if {@link org.junit.Rule} and131 * {@link org.junit.ClassRule} annotations have been used correctly132 */133 interface RuleValidator {134 /**135 * Examine the given member and add any violations of the strategy's validation logic to the given list of errors136 * @param member The member (field or member) to examine137 * @param annotation The type of rule annotation on the member138 * @param errors The list of errors to add validation violations to139 */140 void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors);141 }142 /**143 * Requires the validated member to be non-static144 */145 private static final class MemberMustBeNonStaticOrAlsoClassRule implements RuleValidator {146 public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {147 boolean isMethodRuleMember = isMethodRule(member);148 boolean isClassRuleAnnotated = (member.getAnnotation(ClassRule.class) != null);149 // We disallow:150 // - static MethodRule members151 // - static @Rule annotated members152 // - UNLESS they're also @ClassRule annotated153 // Note that MethodRule cannot be annotated with @ClassRule154 if (member.isStatic() && (isMethodRuleMember || !isClassRuleAnnotated)) {155 String message;156 if (isMethodRule(member)) {157 message = "must not be static.";158 } else {159 message = "must not be static or it must be annotated with @ClassRule.";160 }161 errors.add(new ValidationError(member, annotation, message));162 }163 }164 }165 /**166 * Requires the member to be static167 */168 private static final class MemberMustBeStatic implements RuleValidator {169 public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {170 if (!member.isStatic()) {171 errors.add(new ValidationError(member, annotation,172 "must be static."));173 }174 }175 }176 /**177 * Requires the member's declaring class to be public178 */179 private static final class DeclaringClassMustBePublic implements RuleValidator {180 public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {181 if (!isDeclaringClassPublic(member)) {182 errors.add(new ValidationError(member, annotation,183 "must be declared in a public class."));184 }185 }186 private boolean isDeclaringClassPublic(FrameworkMember<?> member) {187 return Modifier.isPublic(member.getDeclaringClass().getModifiers());188 }189 }190 /**191 * Requires the member to be public192 */193 private static final class MemberMustBePublic implements RuleValidator {194 public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {195 if (!member.isPublic()) {196 errors.add(new ValidationError(member, annotation,197 "must be public."));198 }199 }200 }201 /**202 * Requires the member is a field implementing {@link org.junit.rules.MethodRule} or {@link org.junit.rules.TestRule}203 */204 private static final class FieldMustBeARule implements RuleValidator {205 public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {206 if (!isRuleType(member)) {207 errors.add(new ValidationError(member, annotation,208 "must implement MethodRule or TestRule."));209 }210 }211 }212 /**213 * Require the member to return an implementation of {@link org.junit.rules.MethodRule} or214 * {@link org.junit.rules.TestRule}215 */216 private static final class MethodMustBeARule implements RuleValidator {217 public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {218 if (!isRuleType(member)) {219 errors.add(new ValidationError(member, annotation,220 "must return an implementation of MethodRule or TestRule."));221 }222 }223 }224 225 /**226 * Require the member to return an implementation of {@link org.junit.rules.TestRule}227 */228 private static final class MethodMustBeATestRule implements RuleValidator {229 public void validate(FrameworkMember<?> member,230 Class<? extends Annotation> annotation, List<Throwable> errors) {231 if (!isTestRule(member)) {232 errors.add(new ValidationError(member, annotation, 233 "must return an implementation of TestRule."));234 }235 }236 }237 238 /**239 * Requires the member is a field implementing {@link org.junit.rules.TestRule}240 */241 private static final class FieldMustBeATestRule implements RuleValidator {242 public void validate(FrameworkMember<?> member,243 Class<? extends Annotation> annotation, List<Throwable> errors) {244 if (!isTestRule(member)) {245 errors.add(new ValidationError(member, annotation,246 "must implement TestRule."));247 }248 }249 }250}...

Full Screen

Full Screen

Source:BlockJUnit4ClassRunnerWithParameters.java Github

copy

Full Screen

1package org.junit.runners.parameterized;2import java.lang.annotation.Annotation;3import java.lang.reflect.Field;4import java.util.List;5import org.junit.internal.runners.statements.RunAfters;6import org.junit.internal.runners.statements.RunBefores;7import org.junit.runner.RunWith;8import org.junit.runner.notification.RunNotifier;9import org.junit.runners.BlockJUnit4ClassRunner;10import org.junit.runners.Parameterized;11import org.junit.runners.Parameterized.Parameter;12import org.junit.runners.model.FrameworkField;13import org.junit.runners.model.FrameworkMethod;14import org.junit.runners.model.InitializationError;15import org.junit.runners.model.Statement;16/**17 * A {@link BlockJUnit4ClassRunner} with parameters support. Parameters can be18 * injected via constructor or into annotated fields.19 */20public class BlockJUnit4ClassRunnerWithParameters extends21 BlockJUnit4ClassRunner {22 private enum InjectionType {23 CONSTRUCTOR, FIELD24 }25 private final Object[] parameters;26 private final String name;27 public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test)28 throws InitializationError {29 super(test.getTestClass());30 parameters = test.getParameters().toArray(31 new Object[test.getParameters().size()]);32 name = test.getName();33 }34 @Override35 public Object createTest() throws Exception {36 InjectionType injectionType = getInjectionType();37 switch (injectionType) {38 case CONSTRUCTOR:39 return createTestUsingConstructorInjection();40 case FIELD:41 return createTestUsingFieldInjection();42 default:43 throw new IllegalStateException("The injection type "44 + injectionType + " is not supported.");45 }46 }47 private Object createTestUsingConstructorInjection() throws Exception {48 return getTestClass().getOnlyConstructor().newInstance(parameters);49 }50 private Object createTestUsingFieldInjection() throws Exception {51 List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();52 if (annotatedFieldsByParameter.size() != parameters.length) {53 throw new Exception(54 "Wrong number of parameters and @Parameter fields."55 + " @Parameter fields counted: "56 + annotatedFieldsByParameter.size()57 + ", available parameters: " + parameters.length58 + ".");59 }60 Object testClassInstance = getTestClass().getJavaClass().newInstance();61 for (FrameworkField each : annotatedFieldsByParameter) {62 Field field = each.getField();63 Parameter annotation = field.getAnnotation(Parameter.class);64 int index = annotation.value();65 try {66 field.set(testClassInstance, parameters[index]);67 } catch (IllegalAccessException e) {68 IllegalAccessException wrappedException = new IllegalAccessException(69 "Cannot set parameter '" + field.getName()70 + "'. Ensure that the field '" + field.getName()71 + "' is public.");72 wrappedException.initCause(e);73 throw wrappedException;74 } catch (IllegalArgumentException iare) {75 throw new Exception(getTestClass().getName()76 + ": Trying to set " + field.getName()77 + " with the value " + parameters[index]78 + " that is not the right type ("79 + parameters[index].getClass().getSimpleName()80 + " instead of " + field.getType().getSimpleName()81 + ").", iare);82 }83 }84 return testClassInstance;85 }86 @Override87 protected String getName() {88 return name;89 }90 @Override91 protected String testName(FrameworkMethod method) {92 return method.getName() + getName();93 }94 @Override95 protected void validateConstructor(List<Throwable> errors) {96 validateOnlyOneConstructor(errors);97 if (getInjectionType() != InjectionType.CONSTRUCTOR) {98 validateZeroArgConstructor(errors);99 }100 }101 @Override102 protected void validateFields(List<Throwable> errors) {103 super.validateFields(errors);104 if (getInjectionType() == InjectionType.FIELD) {105 List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();106 int[] usedIndices = new int[annotatedFieldsByParameter.size()];107 for (FrameworkField each : annotatedFieldsByParameter) {108 int index = each.getField().getAnnotation(Parameter.class)109 .value();110 if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {111 errors.add(new Exception("Invalid @Parameter value: "112 + index + ". @Parameter fields counted: "113 + annotatedFieldsByParameter.size()114 + ". Please use an index between 0 and "115 + (annotatedFieldsByParameter.size() - 1) + "."));116 } else {117 usedIndices[index]++;118 }119 }120 for (int index = 0; index < usedIndices.length; index++) {121 int numberOfUse = usedIndices[index];122 if (numberOfUse == 0) {123 errors.add(new Exception("@Parameter(" + index124 + ") is never used."));125 } else if (numberOfUse > 1) {126 errors.add(new Exception("@Parameter(" + index127 + ") is used more than once (" + numberOfUse + ")."));128 }129 }130 }131 }132 @Override133 protected Statement classBlock(RunNotifier notifier) {134 Statement statement = childrenInvoker(notifier);135 statement = withBeforeParams(statement);136 statement = withAfterParams(statement);137 return statement;138 }139 private Statement withBeforeParams(Statement statement) {140 List<FrameworkMethod> befores = getTestClass()141 .getAnnotatedMethods(Parameterized.BeforeParam.class);142 return befores.isEmpty() ? statement : new RunBeforeParams(statement, befores);143 }144 private class RunBeforeParams extends RunBefores {145 RunBeforeParams(Statement next, List<FrameworkMethod> befores) {146 super(next, befores, null);147 }148 @Override149 protected void invokeMethod(FrameworkMethod method) throws Throwable {150 int paramCount = method.getMethod().getParameterTypes().length;151 method.invokeExplosively(null, paramCount == 0 ? (Object[]) null : parameters);152 }153 }154 private Statement withAfterParams(Statement statement) {155 List<FrameworkMethod> afters = getTestClass()156 .getAnnotatedMethods(Parameterized.AfterParam.class);157 return afters.isEmpty() ? statement : new RunAfterParams(statement, afters);158 }159 private class RunAfterParams extends RunAfters {160 RunAfterParams(Statement next, List<FrameworkMethod> afters) {161 super(next, afters, null);162 }163 @Override164 protected void invokeMethod(FrameworkMethod method) throws Throwable {165 int paramCount = method.getMethod().getParameterTypes().length;166 method.invokeExplosively(null, paramCount == 0 ? (Object[]) null : parameters);167 }168 }169 @Override170 protected Annotation[] getRunnerAnnotations() {171 Annotation[] allAnnotations = super.getRunnerAnnotations();172 Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1];173 int i = 0;174 for (Annotation annotation: allAnnotations) {175 if (!annotation.annotationType().equals(RunWith.class)) {176 annotationsWithoutRunWith[i] = annotation;177 ++i;178 }179 }180 return annotationsWithoutRunWith;181 }182 private List<FrameworkField> getAnnotatedFieldsByParameter() {183 return getTestClass().getAnnotatedFields(Parameter.class);184 }185 private InjectionType getInjectionType() {186 if (fieldsAreAnnotated()) {187 return InjectionType.FIELD;188 } else {189 return InjectionType.CONSTRUCTOR;190 }191 }192 private boolean fieldsAreAnnotated() {193 return !getAnnotatedFieldsByParameter().isEmpty();194 }195}...

Full Screen

Full Screen

Source:JUnit38ClassRunnerTest.java Github

copy

Full Screen

1package org.junit.tests.junit3compatibility;2import static org.junit.Assert.assertEquals;3import static org.junit.Assert.assertNull;4import static org.junit.Assert.assertNotNull;5import java.lang.annotation.ElementType;6import java.lang.annotation.Retention;7import java.lang.annotation.RetentionPolicy;8import java.lang.annotation.Target;9import junit.extensions.TestDecorator;10import junit.framework.JUnit4TestAdapter;11import junit.framework.TestCase;12import junit.framework.TestSuite;13import org.junit.Assert;14import org.junit.Test;15import org.junit.internal.runners.JUnit38ClassRunner;16import org.junit.runner.Description;17import org.junit.runner.JUnitCore;18import org.junit.runner.Result;19import org.junit.runner.notification.Failure;20import org.junit.runner.notification.RunListener;21import org.junit.runner.manipulation.Filter;22import org.junit.runner.manipulation.NoTestsRemainException;23public class JUnit38ClassRunnerTest {24 public static class MyTest extends TestCase {25 public void testA() {26 }27 }28 @Test29 public void plansDecoratorCorrectly() {30 JUnit38ClassRunner runner = new JUnit38ClassRunner(new TestDecorator(new TestSuite(MyTest.class)));31 assertEquals(1, runner.testCount());32 }33 public static class AnnotatedTest {34 @Test35 public void foo() {36 Assert.fail();37 }38 }39 @Test40 public void canUnadaptAnAdapter() {41 JUnit38ClassRunner runner = new JUnit38ClassRunner(new JUnit4TestAdapter(AnnotatedTest.class));42 Result result = new JUnitCore().run(runner);43 Failure failure = result.getFailures().get(0);44 assertEquals(Description.createTestDescription(AnnotatedTest.class, "foo"), failure.getDescription());45 }46 static int count;47 static public class OneTest extends TestCase {48 public void testOne() {49 }50 }51 @Test52 public void testListener() throws Exception {53 JUnitCore runner = new JUnitCore();54 RunListener listener = new RunListener() {55 @Override56 public void testStarted(Description description) {57 assertEquals(Description.createTestDescription(OneTest.class, "testOne"),58 description);59 count++;60 }61 };62 runner.addListener(listener);63 count = 0;64 Result result = runner.run(OneTest.class);65 assertEquals(1, count);66 assertEquals(1, result.getRunCount());67 }68 public static class ClassWithInvalidMethod extends TestCase {69 @SuppressWarnings("unused")70 private void testInvalid() {71 }72 }73 @Test74 public void invalidTestMethodReportedCorrectly() {75 Result result = JUnitCore.runClasses(ClassWithInvalidMethod.class);76 Failure failure = result.getFailures().get(0);77 assertEquals("warning", failure.getDescription().getMethodName());78 assertEquals("junit.framework.TestSuite$1", failure.getDescription().getClassName());79 }80 @Retention(RetentionPolicy.RUNTIME)81 @Target(ElementType.METHOD)82 public static @interface MyAnnotation {83 }84 public static class JUnit3ClassWithAnnotatedMethod extends TestCase {85 @MyAnnotation86 public void testAnnotated() {87 }88 public void testNotAnnotated() {89 }90 }91 public static class DerivedAnnotatedMethod extends JUnit3ClassWithAnnotatedMethod {92 }93 @Test94 public void getDescriptionWithAnnotation() {95 JUnit38ClassRunner runner = new JUnit38ClassRunner(JUnit3ClassWithAnnotatedMethod.class);96 assertAnnotationFiltering(runner);97 }98 99 @Test100 public void getDescriptionWithAnnotationInSuper() {101 JUnit38ClassRunner runner = new JUnit38ClassRunner(DerivedAnnotatedMethod.class);102 assertAnnotationFiltering(runner);103 }104 private void assertAnnotationFiltering(JUnit38ClassRunner runner) {105 Description d = runner.getDescription();106 assertEquals(2, d.testCount());107 for (Description methodDesc : d.getChildren()) {108 if (methodDesc.getMethodName().equals("testAnnotated")) {109 assertNotNull(methodDesc.getAnnotation(MyAnnotation.class));110 } else {111 assertNull(methodDesc.getAnnotation(MyAnnotation.class));112 }113 }114 }115 public static class RejectAllTestsFilter extends Filter {116 @Override117 public boolean shouldRun(Description description) {118 return description.isSuite();119 }120 @Override121 public String describe() {122 return "filter all";123 }124 }125 /**126 * Test that NoTestsRemainException is thrown when all methods have been filtered.127 */128 @Test(expected = NoTestsRemainException.class) 129 public void filterNoTestsRemain() throws NoTestsRemainException {130 JUnit38ClassRunner runner = new JUnit38ClassRunner(OneTest.class);131 runner.filter(new RejectAllTestsFilter()); 132 }133}...

Full Screen

Full Screen

Source:LifecycleMethodUtils.java Github

copy

Full Screen

1/*2 * Copyright 2015-2019 the original author or authors.3 *4 * All rights reserved. This program and the accompanying materials are5 * made available under the terms of the Eclipse Public License v2.0 which6 * accompanies this distribution and is available at7 *8 * https://www.eclipse.org/legal/epl-v20.html9 */10package org.junit.jupiter.engine.descriptor;11import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedMethods;12import static org.junit.platform.commons.util.ReflectionUtils.returnsVoid;13import java.lang.annotation.Annotation;14import java.lang.reflect.Method;15import java.util.List;16import org.junit.jupiter.api.AfterAll;17import org.junit.jupiter.api.AfterEach;18import org.junit.jupiter.api.BeforeAll;19import org.junit.jupiter.api.BeforeEach;20import org.junit.platform.commons.JUnitException;21import org.junit.platform.commons.util.ReflectionUtils;22import org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode;23/**24 * Collection of utilities for working with test lifecycle methods.25 *26 * @since 5.027 */28final class LifecycleMethodUtils {29 private LifecycleMethodUtils() {30 /* no-op */31 }32 static List<Method> findBeforeAllMethods(Class<?> testClass, boolean requireStatic) {33 return findMethodsAndAssertStatic(testClass, requireStatic, BeforeAll.class, HierarchyTraversalMode.TOP_DOWN);34 }35 static List<Method> findAfterAllMethods(Class<?> testClass, boolean requireStatic) {36 return findMethodsAndAssertStatic(testClass, requireStatic, AfterAll.class, HierarchyTraversalMode.BOTTOM_UP);37 }38 static List<Method> findBeforeEachMethods(Class<?> testClass) {39 return findMethodsAndAssertNonStatic(testClass, BeforeEach.class, HierarchyTraversalMode.TOP_DOWN);40 }41 static List<Method> findAfterEachMethods(Class<?> testClass) {42 return findMethodsAndAssertNonStatic(testClass, AfterEach.class, HierarchyTraversalMode.BOTTOM_UP);43 }44 private static void assertStatic(Class<? extends Annotation> annotationType, Method method) {45 if (ReflectionUtils.isNotStatic(method)) {46 throw new JUnitException(String.format(47 "@%s method '%s' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).",48 annotationType.getSimpleName(), method.toGenericString()));49 }50 }51 private static void assertNonStatic(Class<? extends Annotation> annotationType, Method method) {52 if (ReflectionUtils.isStatic(method)) {53 throw new JUnitException(String.format("@%s method '%s' must not be static.",54 annotationType.getSimpleName(), method.toGenericString()));55 }56 }57 private static void assertVoid(Class<? extends Annotation> annotationType, Method method) {58 if (!returnsVoid(method)) {59 throw new JUnitException(String.format("@%s method '%s' must not return a value.",60 annotationType.getSimpleName(), method.toGenericString()));61 }62 }63 private static List<Method> findMethodsAndAssertStatic(Class<?> testClass, boolean requireStatic,64 Class<? extends Annotation> annotationType, HierarchyTraversalMode traversalMode) {65 List<Method> methods = findMethodsAndCheckVoidReturnType(testClass, annotationType, traversalMode);66 if (requireStatic) {67 methods.forEach(method -> assertStatic(annotationType, method));68 }69 return methods;70 }71 private static List<Method> findMethodsAndAssertNonStatic(Class<?> testClass,72 Class<? extends Annotation> annotationType, HierarchyTraversalMode traversalMode) {73 List<Method> methods = findMethodsAndCheckVoidReturnType(testClass, annotationType, traversalMode);74 methods.forEach(method -> assertNonStatic(annotationType, method));75 return methods;76 }77 private static List<Method> findMethodsAndCheckVoidReturnType(Class<?> testClass,78 Class<? extends Annotation> annotationType, HierarchyTraversalMode traversalMode) {79 List<Method> methods = findAnnotatedMethods(testClass, annotationType, traversalMode);80 methods.forEach(method -> assertVoid(annotationType, method));81 return methods;82 }83}...

Full Screen

Full Screen

Source:TestTypeConstants.java Github

copy

Full Screen

1package org.moreunit.preferences;2import java.util.HashMap;3import java.util.Map;4public class TestTypeConstants5{6 public static final Map<String, String> BEFORE_CLASS_METHOD_ANNOTATION = new HashMap<String, String>();7 public static final Map<String, String> BEFORE_METHOD_ANNOTATION = new HashMap<String, String>();8 public static final Map<String, String> TEARDOWN_METHOD_ANNOTATION = new HashMap<String, String>();9 public static final Map<String, String> AFTER_CLASS_METHOD_ANNOTATION = new HashMap<String, String>();10 public static final Map<String, String> TEST_ANNOTATION = new HashMap<String, String>();11 public static final Map<String, String> STATIC_IMPORT_BASE_CLASS = new HashMap<String, String>();12 static13 {14 BEFORE_CLASS_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_4, "org.junit.BeforeClass"); //$NON-NLS-1$15 BEFORE_CLASS_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_5, "org.junit.jupiter.api.BeforeAll"); //$NON-NLS-1$16 BEFORE_CLASS_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_TESTNG, "org.testng.annotations.BeforeClass"); //$NON-NLS-1$17 BEFORE_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_4, "org.junit.Before"); //$NON-NLS-1$18 BEFORE_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_5, "org.junit.jupiter.api.BeforeEach"); //$NON-NLS-1$19 BEFORE_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_TESTNG, "org.testng.annotations.BeforeMethod"); //$NON-NLS-1$20 TEARDOWN_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_4, "org.junit.After"); //$NON-NLS-1$21 TEARDOWN_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_5, "org.junit.jupiter.api.AfterEach"); //$NON-NLS-1$22 TEARDOWN_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_TESTNG, "org.testng.annotations.AfterMethod"); //$NON-NLS-1$23 AFTER_CLASS_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_4, "org.junit.AfterClass"); //$NON-NLS-1$24 AFTER_CLASS_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_5, "org.junit.jupiter.api.AfterAll"); //$NON-NLS-1$25 AFTER_CLASS_METHOD_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_TESTNG, "org.testng.annotations.AfterClass"); //$NON-NLS-1$26 TEST_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_4, "org.junit.Test"); //$NON-NLS-1$27 TEST_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_5, "org.junit.jupiter.api.Test"); //$NON-NLS-1$28 TEST_ANNOTATION.put(PreferenceConstants.TEST_TYPE_VALUE_TESTNG, "org.testng.annotations.Test"); //$NON-NLS-1$29 STATIC_IMPORT_BASE_CLASS.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_4, "org.junit.Assert"); //$NON-NLS-1$30 STATIC_IMPORT_BASE_CLASS.put(PreferenceConstants.TEST_TYPE_VALUE_JUNIT_5, "org.junit.jupiter.api.Assertions"); //$NON-NLS-1$31 STATIC_IMPORT_BASE_CLASS.put(PreferenceConstants.TEST_TYPE_VALUE_TESTNG, "org.testng.Assert"); //$NON-NLS-1$32 }33}...

Full Screen

Full Screen

Source:BlockJUnit4ClassRunnerWithParametersTest.java Github

copy

Full Screen

1package org.junit.runners.parameterized;2import static java.util.Collections.emptyList;3import static org.hamcrest.CoreMatchers.instanceOf;4import static org.junit.Assert.assertEquals;5import static org.junit.rules.ExpectedException.none;6import java.lang.annotation.Annotation;7import java.lang.annotation.ElementType;8import java.lang.annotation.Retention;9import java.lang.annotation.RetentionPolicy;10import java.lang.annotation.Target;11import java.util.Collections;12import java.util.List;13import org.junit.Rule;14import org.junit.Test;15import org.junit.rules.ExpectedException;16import org.junit.runner.RunWith;17import org.junit.runners.Parameterized;18import org.junit.runners.model.TestClass;19public class BlockJUnit4ClassRunnerWithParametersTest {20 private static final List<Object> NO_PARAMETERS = emptyList();21 @Rule22 public final ExpectedException thrown = none();23 @RunWith(Parameterized.class)24 @DummyAnnotation25 public static class ClassWithParameterizedAnnotation {26 @Test27 public void dummyTest() {28 }29 }30 @Test31 public void hasAllAnnotationsExceptRunWith() throws Exception {32 TestWithParameters testWithParameters = new TestWithParameters(33 "dummy name", new TestClass(34 ClassWithParameterizedAnnotation.class), NO_PARAMETERS);35 BlockJUnit4ClassRunnerWithParameters runner = new BlockJUnit4ClassRunnerWithParameters(36 testWithParameters);37 Annotation[] annotations = runner.getRunnerAnnotations();38 assertEquals(1, annotations.length);39 assertEquals(annotations[0].annotationType(), DummyAnnotation.class);40 }41 @Retention(RetentionPolicy.RUNTIME)42 @Target(ElementType.TYPE)43 private static @interface DummyAnnotation {44 }45 @RunWith(Parameterized.class)46 public static class ClassWithPrivateParameter {47 @Parameterized.Parameter48 private String parameter;49 @Test50 public void dummyTest() {51 }52 }53 @Test54 public void providesHelpfulMessageIfParameterFieldCannotBeSet()55 throws Exception {56 TestWithParameters testWithParameters = new TestWithParameters(57 "dummy name",58 new TestClass(ClassWithPrivateParameter.class),59 Collections.<Object>singletonList("dummy parameter"));60 BlockJUnit4ClassRunnerWithParameters runner = new BlockJUnit4ClassRunnerWithParameters(61 testWithParameters);62 thrown.expect(IllegalAccessException.class);63 thrown.expectCause(instanceOf(IllegalAccessException.class));64 thrown.expectMessage("Cannot set parameter 'parameter'. Ensure that the field 'parameter' is public.");65 runner.createTest();66 }67}...

Full Screen

Full Screen

Source:AnnotatedDescriptionTest.java Github

copy

Full Screen

1package org.junit.tests.description;2import static org.junit.Assert.assertEquals;3import static org.junit.Assert.assertTrue;4import java.lang.annotation.Annotation;5import java.lang.annotation.Retention;6import java.lang.annotation.RetentionPolicy;7import org.junit.Ignore;8import org.junit.Test;9import org.junit.runner.Description;10import org.junit.runner.Request;11public class AnnotatedDescriptionTest {12 @Retention(RetentionPolicy.RUNTIME)13 public @interface MyOwnAnnotation {14 }15 @MyOwnAnnotation16 public static class AnnotatedClass {17 @Test18 public void a() {19 }20 }21 @Test22 public void annotationsExistOnDescriptionsOfClasses() {23 assertTrue((describe(AnnotatedClass.class).getAnnotation(24 MyOwnAnnotation.class) != null));25 }26 @Test27 public void getAnnotationsReturnsAllAnnotations() {28 assertEquals(1, describe(ValueAnnotatedClass.class).getAnnotations()29 .size());30 }31 @Ignore32 public static class IgnoredClass {33 @Test34 public void a() {35 }36 }37 @Test38 public void annotationsExistOnDescriptionsOfIgnoredClass() {39 assertTrue((describe(IgnoredClass.class).getAnnotation(Ignore.class) != null));40 }41 @Retention(RetentionPolicy.RUNTIME)42 public @interface ValuedAnnotation {43 String value();44 }45 @ValuedAnnotation("hello")46 public static class ValueAnnotatedClass {47 @Test48 public void a() {49 }50 }51 @Test52 public void descriptionOfTestClassHasValuedAnnotation() {53 Description description = describe(ValueAnnotatedClass.class);54 assertEquals("hello", description.getAnnotation(ValuedAnnotation.class)55 .value());56 }57 @Test58 public void childlessCopyOfDescriptionStillHasAnnotations() {59 Description description = describe(ValueAnnotatedClass.class);60 assertEquals("hello", description.childlessCopy().getAnnotation(ValuedAnnotation.class)61 .value());62 }63 @Test64 public void characterizeCreatingMyOwnAnnotation() {65 Annotation annotation = new Ignore() {66 public String value() {67 return "message";68 }69 public Class<? extends Annotation> annotationType() {70 return Ignore.class;71 }72 };73 assertEquals(Ignore.class, annotation.annotationType());74 }75 private Description describe(Class<?> testClass) {76 return Request.aClass(testClass).getRunner().getDescription();77 }78}...

Full Screen

Full Screen

Annotation Type Test

Using AI Code Generation

copy

Full Screen

1import org.junit.Test; 2import org.junit.Ignore; 3import org.junit.Before; 4import org.junit.After; 5import org.junit.BeforeClass; 6import org.junit.AfterClass; 7import org.junit.Rule; 8import org.junit.ClassRule; 9import org.junit.runners.MethodSorters; 10import org.junit.FixMethodOrder; 11import org.junit.runner.RunWith; 12import org.junit.runners.JUnit4; 13import org.junit.runner.Description; 14import org.junit.runner.Result; 15import org.junit.runner.notification.Failure; 16import org.junit.runner.notification.RunListener; 17import org.junit.runner.notification.RunNotifier; 18import org.junit.runner.notification.StoppedByUserException; 19import org.junit.runner.manipulation.Filter; 20import org.junit.runner.manipulation.Filterable; 21import org.junit.runner.manipulation.NoTestsRemainException; 22import org.junit.runner.manipulation.Sortable; 23import org.junit.runner.manipulation.Sort

Full Screen

Full Screen

Annotation Type Test

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2public class MyTest {3 public void test() {4 System.out.println("This is a test method");5 }6}7import org.junit.Before;8public class MyTest {9 public void test() {10 System.out.println("This is a test method");11 }12}13import org.junit.After;14public class MyTest {15 public void test() {16 System.out.println("This is a test method");17 }18}19import org.junit.BeforeClass;20public class MyTest {21 public static void test() {22 System.out.println("This is a test method");23 }24}25import org.junit.AfterClass;26public class MyTest {27 public static void test() {28 System.out.println("This is a test method");29 }30}31import org.junit.Ignore;32public class MyTest {33 public void test() {34 System.out.println("This is a test method");35 }36}37import org.junit.Rule;38public class MyTest {39 public void test() {40 System.out.println("This is a test method");41 }42}43import org.junit.Test;44public class MyTest {45 public void test() {46 System.out.println("This is a test method");47 }48}49import org.junit.Test;50public class MyTest {51 public void test() {52 System.out.println("This is a test method");53 }54}55import org.junit.Test;56public class MyTest {57 public void test() {58 System.out.println("This is a test method");59 }60}61import org.junit.Test;62public class MyTest {63 public void test() {

Full Screen

Full Screen

Annotation Type Test

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2public class TestAnnotation {3 public TestAnnotation() {4 }5 public void testMethod() {6 System.out.println("testMethod");7 }8}

Full Screen

Full Screen

Annotation Type Test

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2public class TestDemo {3 public void testAdd() {4 System.out.println("testAdd");5 }6 public void testSub() {7 System.out.println("testSub");8 }9}10The @Test annotation is defined in the org.junit package. So, before using the @Test annotation, we need to import the

Full Screen

Full Screen

Annotation Type Test

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2public class HelloWorld {3 public void testHelloWorld() {4 System.out.println("Hello World!");5 }6}7import org.testng.annotations.Test;8public class HelloWorld {9 public void testHelloWorld() {10 System.out.println("Hello World!");11 }12}13import org.testng.annotations.Test;14public class HelloWorld {15 public void testHelloWorld() {16 System.out.println("Hello World!");17 }18}19import org.testng.annotations.Test;20public class HelloWorld {21 public void testHelloWorld() {22 System.out.println("Hello World!");23 }24}25import org.testng.annotations.Test;26public class HelloWorld {27 public void testHelloWorld() {28 System.out.println("Hello World!");29 }30}31import org.testng.annotations.Test;32public class HelloWorld {33 public void testHelloWorld() {34 System.out.println("Hello World!");35 }36}37import org.testng.annotations.Test;38public class HelloWorld {39 public void testHelloWorld() {40 System.out.println("Hello World!");41 }42}43import org.testng.annotations.Test;44public class HelloWorld {45 public void testHelloWorld() {46 System.out.println("Hello World!");47 }48}49import org.testng.annotations.Test;50public class HelloWorld {51 public void testHelloWorld() {52 System.out.println("Hello World!");53 }54}55import org.testng.annotations.Test;56public class HelloWorld {57 public void testHelloWorld() {58 System.out.println("Hello World!");59 }60}61import org.testng.annotations.Test;62public class HelloWorld {63 public void testHelloWorld() {

Full Screen

Full Screen
copy
1create table test(2 test_id int(11) not null auto_increment,3 primary key(test_id));45create table customer(6 customer_id int(11) not null auto_increment,7 name varchar(50) not null,8 primary key(customer_id));9
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-Test

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