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

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

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:RuleFieldValidator.java Github

copy

Full Screen

1package org.junit.internal.runners.rules;2import java.lang.annotation.Annotation;3import java.util.List;4import org.junit.ClassRule;5import org.junit.Rule;6import org.junit.rules.MethodRule;7import org.junit.rules.TestRule;8import org.junit.runners.model.FrameworkMember;9import org.junit.runners.model.TestClass;10/**11 * A RuleFieldValidator validates the rule fields of a12 * {@link org.junit.runners.model.TestClass}. All reasons for rejecting the13 * {@code TestClass} are written to a list of errors.14 *15 * There are four slightly different validators. The {@link #CLASS_RULE_VALIDATOR}16 * validates fields with a {@link ClassRule} annotation and the17 * {@link #RULE_VALIDATOR} validates fields with a {@link Rule} annotation.18 *19 * The {@link #CLASS_RULE_METHOD_VALIDATOR}20 * validates methods with a {@link ClassRule} annotation and the21 * {@link #RULE_METHOD_VALIDATOR} validates methods with a {@link Rule} annotation.22 */23public enum RuleFieldValidator {24 /**25 * Validates fields with a {@link ClassRule} annotation.26 */27 CLASS_RULE_VALIDATOR(ClassRule.class, false, true),28 /**29 * Validates fields with a {@link Rule} annotation.30 */31 RULE_VALIDATOR(Rule.class, false, false),32 /**33 * Validates methods with a {@link ClassRule} annotation.34 */35 CLASS_RULE_METHOD_VALIDATOR(ClassRule.class, true, true),36 /**37 * Validates methods with a {@link Rule} annotation.38 */39 RULE_METHOD_VALIDATOR(Rule.class, true, false);40 private final Class<? extends Annotation> fAnnotation;41 private final boolean fStaticMembers;42 private final boolean fMethods;43 private RuleFieldValidator(Class<? extends Annotation> annotation,44 boolean methods, boolean fStaticMembers) {45 this.fAnnotation = annotation;46 this.fStaticMembers = fStaticMembers;47 this.fMethods = methods;48 }49 /**50 * Validate the {@link org.junit.runners.model.TestClass} and adds reasons51 * for rejecting the class to a list of errors.52 *53 * @param target the {@code TestClass} to validate.54 * @param errors the list of errors.55 */56 public void validate(TestClass target, List<Throwable> errors) {57 List<? extends FrameworkMember<?>> members = fMethods ? target.getAnnotatedMethods(fAnnotation)58 : target.getAnnotatedFields(fAnnotation);59 for (FrameworkMember<?> each : members) {60 validateMember(each, errors);61 }62 }63 private void validateMember(FrameworkMember<?> member, List<Throwable> errors) {64 validateStatic(member, errors);65 validatePublic(member, errors);66 validateTestRuleOrMethodRule(member, errors);67 }68 private void validateStatic(FrameworkMember<?> member,69 List<Throwable> errors) {70 if (fStaticMembers && !member.isStatic()) {71 addError(errors, member, "must be static.");72 }73 if (!fStaticMembers && member.isStatic()) {74 addError(errors, member, "must not be static.");75 }76 }77 private void validatePublic(FrameworkMember<?> member, List<Throwable> errors) {78 if (!member.isPublic()) {79 addError(errors, member, "must be public.");80 }81 }82 private void validateTestRuleOrMethodRule(FrameworkMember<?> member,83 List<Throwable> errors) {84 if (!isMethodRule(member) && !isTestRule(member)) {85 addError(errors, member, fMethods ?86 "must return an implementation of MethodRule or TestRule." :87 "must implement MethodRule or TestRule.");88 }89 }90 private boolean isTestRule(FrameworkMember<?> member) {91 return TestRule.class.isAssignableFrom(member.getType());92 }93 @SuppressWarnings("deprecation")94 private boolean isMethodRule(FrameworkMember<?> member) {95 return MethodRule.class.isAssignableFrom(member.getType());96 }97 private void addError(List<Throwable> errors, FrameworkMember<?> member,98 String suffix) {99 String message = "The @" + fAnnotation.getSimpleName() + " '"100 + member.getName() + "' " + suffix;101 errors.add(new Exception(message));102 }103}...

Full Screen

Full Screen

Annotation Type Rule

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.ExpectedException;4public class TestExceptionRule {5 public ExpectedException thrown = ExpectedException.none();6 public void throwsNothing() {7 }8 public void throwsNullPointerException() {9 thrown.expect(NullPointerException.class);10 throw new NullPointerException();11 }12 public void throwsNullPointerExceptionWithMessage() {13 thrown.expect(NullPointerException.class);14 thrown.expectMessage("Hello World");15 throw new NullPointerException("Hello World");16 }17}

Full Screen

Full Screen

Annotation Type Rule

Using AI Code Generation

copy

Full Screen

1package com.journaldev.junit;2import org.junit.rules.TestRule;3import org.junit.runner.Description;4import org.junit.runners.model.Statement;5public class MyRule implements TestRule {6 public Statement apply(Statement base, Description description) {7 return base;8 }9}10package com.journaldev.junit;11import org.junit.rules.TestRule;12import org.junit.runner.Description;13import org.junit.runners.model.Statement;14public class MyRule implements TestRule {15 public Statement apply(Statement base, Description description) {16 return base;17 }18}19package com.journaldev.junit;20import org.junit.rules.TestRule;21import org.junit.runner.Description;22import org.junit.runners.model.Statement;23public class MyRule implements TestRule {24 public Statement apply(Statement base, Description description) {25 return base;26 }27}28package com.journaldev.junit;29import org.junit.rules.TestRule;30import org.junit.runner.Description;31import org.junit.runners.model.Statement;32public class MyRule implements TestRule {33 public Statement apply(Statement base, Description description) {34 return base;35 }36}37package com.journaldev.junit;38import org.junit.rules.TestRule;39import org.junit.runner.Description;40import org.junit.runners.model.Statement;41public class MyRule implements TestRule {42 public Statement apply(Statement base, Description description) {43 return base;44 }45}46package com.journaldev.junit;47import org.junit.rules.TestRule;48import org.junit.runner.Description;49import org.junit.runners.model.Statement;50public class MyRule implements TestRule {51 public Statement apply(Statement base, Description description) {52 return base;53 }54}55package com.journaldev.junit;56import org.junit.rules.TestRule;57import org.junit.runner.Description;58import org.junit.runners.model.Statement;59public class MyRule implements TestRule {60 public Statement apply(Statement base, Description description) {61 return base;62 }63}

Full Screen

Full Screen

Annotation Type Rule

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;7public class TestJunit1 {8 public static void beforeClass() {9 System.out.println("in before class");10 }11 public static void afterClass() {12 System.out.println("in after class");13 }14 public void before() {15 System.out.println("in before");16 }17 public void after() {18 System.out.println("in after");19 }20 public void test() {21 System.out.println("in test");22 }23 public void ignoreTest() {24 System.out.println("in ignore test");25 }26}27public class CustomRule implements TestRule {28 public Statement apply(Statement base, Description description) {29 return statement(base, description);30 }31 private Statement statement(final Statement base, Description description) {32 return new Statement() {33 public void evaluate() throws Throwable {34 System.out.println("in custom rule");35 try {36 base.evaluate();37 } finally {38 System.out.println("in custom rule");39 }40 }41 };42 }43}

Full Screen

Full Screen

Annotation Type Rule

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.Timeout;4public class TimeoutTest {5 public Timeout globalTimeout = new Timeout(2000);6 public void infiniteLoop1() {7 while (true) {8 }9 }10 public void infiniteLoop2() {11 while (true) {12 }13 }14}15 at java.lang.Thread.sleep(Native Method)16 at org.junit.rules.Timeout$1.evaluate(Timeout.java:106)17 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)18 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)19 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)20 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)21 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)22 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)23 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)24 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)25 at org.junit.runners.ParentRunner.run(ParentRunner.java:309)26 at org.junit.runner.JUnitCore.run(JUnitCore.java:160)27 at org.junit.runner.JUnitCore.run(JUnitCore.java:138)28 at org.junit.runner.JUnitCore.runMain(JUnitCore.java:117)29 at org.junit.runner.JUnitCore.main(JUnitCore.java:106)30package com.mkyong.common;31import org.junit.Test;32public class InfiniteLoopTest {33 public void infiniteLoop1() {34 while (true) {35 }36 }37 public void infiniteLoop2() {38 while (true) {39 }40 }41}42 at java.lang.Thread.sleep(Native Method)43 at org.junit.rules.Timeout$1.evaluate(Timeout.java:106)

Full Screen

Full Screen

Annotation Type Rule

Using AI Code Generation

copy

Full Screen

1import org.junit.*;2import org.junit.rules.Timeout;3import org.junit.runner.Description;4public class TestJUnit {5 public Timeout globalTimeout = new Timeout(20);6 public void testInfiniteLoop1() {7 while (true);8 }9 public void testInfiniteLoop2() {10 while (true);11 }12 public void testInfiniteLoop3() {13 while (true);14 }15}

Full Screen

Full Screen
copy
1@Pointcut("if()")2public static boolean isActive() {3 return Aspects.aspectOf(PerformanceMonitorAspect.class).eventJournalService != null;4}56// ...78@AfterReturning(pointcut = "isActive() && anyPublicMethod() && inService() && @annotation(eventJournal) && args(entity,..)", returning = "id")9// ...1011@AfterThrowing(pointcut = "isActive() && anyPublicMethod() && inService() && @annotation(eventJournal) && args(entity,..)", throwing="ex")12// ...13
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-Rule

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