Best junit code snippet using org.junit.runners.model.Test.getAnnotation
Source:Theories.java
...29 }30 private void validateDataPointFields(List<Throwable> errors) {31 Field[] fields = getTestClass().getJavaClass().getDeclaredFields();32 for (Field field : fields) {33 if (field.getAnnotation(DataPoint.class) != null || field.getAnnotation(DataPoints.class) != null) {34 if (!Modifier.isStatic(field.getModifiers())) {35 errors.add(new Error("DataPoint field " + field.getName() + " must be static"));36 }37 if (!Modifier.isPublic(field.getModifiers())) {38 errors.add(new Error("DataPoint field " + field.getName() + " must be public"));39 }40 }41 }42 }43 private void validateDataPointMethods(List<Throwable> errors) {44 Method[] methods = getTestClass().getJavaClass().getDeclaredMethods();45 for (Method method : methods) {46 if (method.getAnnotation(DataPoint.class) != null || method.getAnnotation(DataPoints.class) != null) {47 if (!Modifier.isStatic(method.getModifiers())) {48 errors.add(new Error("DataPoint method " + method.getName() + " must be static"));49 }50 if (!Modifier.isPublic(method.getModifiers())) {51 errors.add(new Error("DataPoint method " + method.getName() + " must be public"));52 }53 }54 }55 }56 /* access modifiers changed from: protected */57 @Override // org.junit.runners.BlockJUnit4ClassRunner58 public void validateConstructor(List<Throwable> errors) {59 validateOnlyOneConstructor(errors);60 }61 /* access modifiers changed from: protected */62 @Override // org.junit.runners.BlockJUnit4ClassRunner63 public void validateTestMethods(List<Throwable> errors) {64 for (FrameworkMethod each : computeTestMethods()) {65 if (each.getAnnotation(Theory.class) != null) {66 each.validatePublicVoid(false, errors);67 each.validateNoTypeParametersOnArgs(errors);68 } else {69 each.validatePublicVoidNoArg(false, errors);70 }71 Iterator<ParameterSignature> it = ParameterSignature.signatures(each.getMethod()).iterator();72 while (it.hasNext()) {73 ParametersSuppliedBy annotation = (ParametersSuppliedBy) it.next().findDeepAnnotation(ParametersSuppliedBy.class);74 if (annotation != null) {75 validateParameterSupplier(annotation.value(), errors);76 }77 }78 }79 }80 private void validateParameterSupplier(Class<? extends ParameterSupplier> supplierClass, List<Throwable> errors) {81 Constructor<?>[] constructors = supplierClass.getConstructors();82 if (constructors.length != 1) {83 errors.add(new Error("ParameterSupplier " + supplierClass.getName() + " must have only one constructor (either empty or taking only a TestClass)"));84 return;85 }86 Class<?>[] paramTypes = constructors[0].getParameterTypes();87 if (paramTypes.length != 0 && !paramTypes[0].equals(TestClass.class)) {88 errors.add(new Error("ParameterSupplier " + supplierClass.getName() + " constructor must take either nothing or a single TestClass instance"));89 }90 }91 /* access modifiers changed from: protected */92 @Override // org.junit.runners.BlockJUnit4ClassRunner93 public List<FrameworkMethod> computeTestMethods() {94 List<FrameworkMethod> testMethods = new ArrayList<>(super.computeTestMethods());95 List<FrameworkMethod> theoryMethods = getTestClass().getAnnotatedMethods(Theory.class);96 testMethods.removeAll(theoryMethods);97 testMethods.addAll(theoryMethods);98 return testMethods;99 }100 @Override // org.junit.runners.BlockJUnit4ClassRunner101 public Statement methodBlock(FrameworkMethod method) {102 return new TheoryAnchor(method, getTestClass());103 }104 public static class TheoryAnchor extends Statement {105 private List<AssumptionViolatedException> fInvalidParameters = new ArrayList();106 private int successes = 0;107 private final TestClass testClass;108 private final FrameworkMethod testMethod;109 public TheoryAnchor(FrameworkMethod testMethod2, TestClass testClass2) {110 this.testMethod = testMethod2;111 this.testClass = testClass2;112 }113 private TestClass getTestClass() {114 return this.testClass;115 }116 @Override // org.junit.runners.model.Statement117 public void evaluate() throws Throwable {118 runWithAssignment(Assignments.allUnassigned(this.testMethod.getMethod(), getTestClass()));119 boolean hasTheoryAnnotation = this.testMethod.getAnnotation(Theory.class) != null;120 if (this.successes == 0 && hasTheoryAnnotation) {121 Assert.fail("Never found parameters that satisfied method assumptions. Violated assumptions: " + this.fInvalidParameters);122 }123 }124 /* access modifiers changed from: protected */125 public void runWithAssignment(Assignments parameterAssignment) throws Throwable {126 if (!parameterAssignment.isComplete()) {127 runWithIncompleteAssignment(parameterAssignment);128 } else {129 runWithCompleteAssignment(parameterAssignment);130 }131 }132 /* access modifiers changed from: protected */133 public void runWithIncompleteAssignment(Assignments incomplete) throws Throwable {134 for (PotentialAssignment source : incomplete.potentialsForNextUnassigned()) {135 runWithAssignment(incomplete.assignNext(source));136 }137 }138 /* access modifiers changed from: protected */139 public void runWithCompleteAssignment(final Assignments complete) throws Throwable {140 new BlockJUnit4ClassRunner(getTestClass().getJavaClass()) {141 /* class org.junit.experimental.theories.Theories.TheoryAnchor.AnonymousClass1 */142 /* access modifiers changed from: protected */143 @Override // org.junit.runners.BlockJUnit4ClassRunner, org.junit.runners.ParentRunner144 public void collectInitializationErrors(List<Throwable> list) {145 }146 @Override // org.junit.runners.BlockJUnit4ClassRunner147 public Statement methodBlock(FrameworkMethod method) {148 final Statement statement = super.methodBlock(method);149 return new Statement() {150 /* class org.junit.experimental.theories.Theories.TheoryAnchor.AnonymousClass1.AnonymousClass1 */151 @Override // org.junit.runners.model.Statement152 public void evaluate() throws Throwable {153 try {154 statement.evaluate();155 TheoryAnchor.this.handleDataPointSuccess();156 } catch (AssumptionViolatedException e) {157 TheoryAnchor.this.handleAssumptionViolation(e);158 } catch (Throwable e2) {159 TheoryAnchor.this.reportParameterizedError(e2, complete.getArgumentStrings(TheoryAnchor.this.nullsOk()));160 }161 }162 };163 }164 /* access modifiers changed from: protected */165 @Override // org.junit.runners.BlockJUnit4ClassRunner166 public Statement methodInvoker(FrameworkMethod method, Object test) {167 return TheoryAnchor.this.methodCompletesWithParameters(method, complete, test);168 }169 @Override // org.junit.runners.BlockJUnit4ClassRunner170 public Object createTest() throws Exception {171 Object[] params = complete.getConstructorArguments();172 if (!TheoryAnchor.this.nullsOk()) {173 Assume.assumeNotNull(params);174 }175 return getTestClass().getOnlyConstructor().newInstance(params);176 }177 }.methodBlock(this.testMethod).evaluate();178 }179 /* access modifiers changed from: private */180 public Statement methodCompletesWithParameters(final FrameworkMethod method, final Assignments complete, final Object freshInstance) {181 return new Statement() {182 /* class org.junit.experimental.theories.Theories.TheoryAnchor.AnonymousClass2 */183 @Override // org.junit.runners.model.Statement184 public void evaluate() throws Throwable {185 Object[] values = complete.getMethodArguments();186 if (!TheoryAnchor.this.nullsOk()) {187 Assume.assumeNotNull(values);188 }189 method.invokeExplosively(freshInstance, values);190 }191 };192 }193 /* access modifiers changed from: protected */194 public void handleAssumptionViolation(AssumptionViolatedException e) {195 this.fInvalidParameters.add(e);196 }197 /* access modifiers changed from: protected */198 public void reportParameterizedError(Throwable e, Object... params) throws Throwable {199 if (params.length == 0) {200 throw e;201 }202 throw new ParameterizedAssertionError(e, this.testMethod.getName(), params);203 }204 /* access modifiers changed from: private */205 public boolean nullsOk() {206 Theory annotation = (Theory) this.testMethod.getMethod().getAnnotation(Theory.class);207 if (annotation == null) {208 return false;209 }210 return annotation.nullsAccepted();211 }212 /* access modifiers changed from: protected */213 public void handleDataPointSuccess() {214 this.successes++;215 }216 }217}...
Source:AndroidTestingRunner.java
...59 return afters.isEmpty() ? statement : new RunAfters(method, statement, afters,60 target);61 }62 protected Statement withPotentialTimeout(FrameworkMethod method, Object test, Statement next) {63 long timeout = this.getTimeout(method.getAnnotation(Test.class));64 if (timeout <= 0L && mTimeout > 0L) {65 timeout = mTimeout;66 }67 return timeout <= 0L ? next : new FailOnTimeout(next, timeout);68 }69 private long getTimeout(Test annotation) {70 return annotation == null ? 0L : annotation.timeout();71 }72 protected List<FrameworkMethod> looperWrap(FrameworkMethod method, Object test,73 List<FrameworkMethod> methods) {74 RunWithLooper annotation = method.getAnnotation(RunWithLooper.class);75 if (annotation == null) annotation = mKlass.getAnnotation(RunWithLooper.class);76 if (annotation != null) {77 methods = new ArrayList<>(methods);78 for (int i = 0; i < methods.size(); i++) {79 methods.set(i, LooperFrameworkMethod.get(methods.get(i),80 annotation.setAsMainLooper(), test));81 }82 }83 return methods;84 }85 protected FrameworkMethod looperWrap(FrameworkMethod method, Object test,86 FrameworkMethod base) {87 RunWithLooper annotation = method.getAnnotation(RunWithLooper.class);88 if (annotation == null) annotation = mKlass.getAnnotation(RunWithLooper.class);89 if (annotation != null) {90 return LooperFrameworkMethod.get(base, annotation.setAsMainLooper(), test);91 }92 return base;93 }94 public boolean shouldRunOnUiThread(FrameworkMethod method) {95 if (mKlass.getAnnotation(UiThreadTest.class) != null) {96 return true;97 } else {98 return UiThreadStatement.shouldRunOnUiThread(method);99 }100 }101}...
Source:TravisRunner.java
...44 }45 @Override46 protected void runChild(final FrameworkMethod method, RunNotifier notifier) {47 Description description = describeChild(method);48 if (method.getAnnotation(Ignore.class) != null) {49 notifier.fireTestIgnored(description);50 } else if ((method.getAnnotation(IgnoreOnTravis.class) != null ||51 getTestClass().getJavaClass().getAnnotation(IgnoreOnTravis.class) != null) &&52 isRunningOnTravis()) {53 System.out.println("Ignoring " + description.getDisplayName() + " on Travis CI");54 notifier.fireTestIgnored(description);55 } else if (method.getAnnotation(RetryOnTravis.class) != null &&56 isRunningOnTravis()) {57 runTestUnit(methodBlock(method), description, notifier,58 method.getAnnotation(RetryOnTravis.class).value());59 } else if (getTestClass().getJavaClass().getAnnotation(RetryOnTravis.class) != null &&60 isRunningOnTravis()) {61 runTestUnit(methodBlock(method), description, notifier,62 getTestClass().getJavaClass().getAnnotation(RetryOnTravis.class).value());63 } else {64 super.runChild(method, notifier);65 }66 }67 protected final void runTestUnit(Statement statement,68 Description description, RunNotifier notifier, int retries) {69 EachTestNotifier eachTestNotifier = new EachTestNotifier(notifier,70 description);71 eachTestNotifier.fireTestStarted();72 try {73 statement.evaluate();74 } catch (AssumptionViolatedException e) {75 eachTestNotifier.addFailedAssumption(e);76 } catch (Throwable e) {...
Source:CompilationRunner.java
...35 this.mappingFiles = new ArrayList<String>();36 this.processorOptions = new HashMap<String, String>();37 Package pkg = clazz.getPackage();38 this.packageName = pkg != null ? pkg.getName() : null;39 processWithClasses( clazz.getAnnotation( WithClasses.class ) );40 processWithMappingFiles( clazz.getAnnotation( WithMappingFiles.class ) );41 processOptions(42 clazz.getAnnotation( WithProcessorOption.class ),43 clazz.getAnnotation( WithProcessorOption.List.class )44 );45 ignoreCompilationErrors = clazz.getAnnotation( IgnoreCompilationErrors.class ) != null;46 }47 @Override48 protected Statement methodBlock(FrameworkMethod method) {49 Statement statement = super.methodBlock( method );50 processAnnotations( method );51 if ( !annotationProcessorNeedsToRun() ) {52 return statement;53 }54 return new CompilationStatement(55 statement,56 testEntities,57 preCompileEntities,58 mappingFiles,59 processorOptions,60 ignoreCompilationErrors61 );62 }63 private void processWithClasses(WithClasses withClasses) {64 if ( withClasses != null ) {65 Collections.addAll( testEntities, withClasses.value() );66 Collections.addAll( preCompileEntities, withClasses.preCompile() );67 }68 }69 private void processWithMappingFiles(WithMappingFiles withMappingFiles) {70 if ( withMappingFiles != null ) {71 String packageNameAsPath = TestUtil.fcnToPath( packageName );72 for ( String mappingFile : withMappingFiles.value() ) {73 mappingFiles.add( packageNameAsPath + TestUtil.RESOURCE_SEPARATOR + mappingFile );74 }75 }76 }77 private void processOptions(WithProcessorOption withProcessorOption,78 WithProcessorOption.List withProcessorOptionsListAnnotation) {79 addOptions( withProcessorOption );80 if ( withProcessorOptionsListAnnotation != null ) {81 for ( WithProcessorOption option : withProcessorOptionsListAnnotation.value() ) {82 addOptions( option );83 }84 }85 }86 private void processAnnotations(FrameworkMethod method) {87 // configuration will be added to potential class level configuration88 processWithClasses( method.getAnnotation( WithClasses.class ) );89 processWithMappingFiles( method.getAnnotation( WithMappingFiles.class ) );90 processOptions(91 method.getAnnotation( WithProcessorOption.class ),92 method.getAnnotation( WithProcessorOption.List.class )93 );94 // overrides potential class level configuration95 ignoreCompilationErrors = method.getAnnotation( IgnoreCompilationErrors.class ) != null;96 }97 private void addOptions(WithProcessorOption withProcessorOptionsAnnotation) {98 if ( withProcessorOptionsAnnotation != null ) {99 processorOptions.put( withProcessorOptionsAnnotation.key(), withProcessorOptionsAnnotation.value() );100 }101 }102 private boolean annotationProcessorNeedsToRun() {103 return !testEntities.isEmpty() || !mappingFiles.isEmpty();104 }105}...
Source:DynamoDBLocalRunner.java
...22 final Field javaField = field.getField();23 javaField.setAccessible(true);24 javaField.set(test, runner.getClient());25 }26 Optional.ofNullable(getTestClass().getAnnotation(DynamoDBSeed.class))27 .ifPresent(this::runSeeds);28 return test;29 }30 private String[] findDynamoDBArgs() {31 final DynamoDBArgs args = getTestClass().getAnnotation(DynamoDBArgs.class);32 return Optional.ofNullable(args)33 .map(a -> a.value())34 .filter(as -> as.length > 0)35 .orElseGet(() -> new String[] { "-clientOnly" });36 }37 private boolean ignoreRunner() {38 return Optional.ofNullable(getTestClass().getAnnotation(DynamoDBArgs.class))39 .filter(args -> args.skipIfUnavailable())40 .isPresent();41 }42 @Override43 protected Statement methodInvoker(FrameworkMethod method, Object test) {44 Optional.ofNullable(method.getAnnotation(DynamoDBSeed.class))45 .ifPresent(this::runSeeds);46 return super.methodInvoker(method, test);47 }48 @Override49 public void run(final RunNotifier notifier) {50 runner.enclosure(notifier, getDescription(), super::run);51 }52 @Override53 protected void runChild(final FrameworkMethod method, final RunNotifier notifier) {54 final Optional<Throwable> validation = validateExternalEnvironment();55 if (validation.isPresent()) {56 if (ignoreRunner()) {57 notifier.fireTestIgnored(getDescription());58 } else {59 notifier.fireTestFailure(new Failure(getDescription(), validation.get()));60 }61 } else {62 super.runChild(method, notifier);63 }64 }65 private void runSeeds(final DynamoDBSeed seeds) {66 for (final Class<? extends IDynamoDBSeed> seedClass : seeds.value()) {67 try {68 final IDynamoDBSeed seed = seedClass.newInstance();69 seed.accept(runner.getClient());70 } catch (Exception e) {71 throw new RuntimeException(e);72 }73 }74 }75 private Optional<Throwable> validateExternalEnvironment() {76 Throwable ex = null;77 try {78 runner.getClient().listTables(new ListTablesRequest()79 .withSdkClientExecutionTimeout(validationTimeout())80 .withSdkRequestTimeout(validationTimeout()));81 } catch (Throwable t) {82 ex = t;83 }84 return Optional.ofNullable(ex);85 }86 private int validationTimeout() {87 return Optional.ofNullable(getTestClass().getAnnotation(DynamoDBArgs.class))88 .map(args -> args.validationTimeout())89 .orElse(1000);90 }91}...
Source:RepeatRunner.java
...2021 @Override22 protected Description describeChild(FrameworkMethod method)23 {24 if (method.getAnnotation(Repeat.class) != null25 && method.getAnnotation(Ignore.class) == null)26 {2728 return describeRepeatTest(method);29 }30 return super.describeChild(method);31 }3233 private Description describeRepeatTest(FrameworkMethod method)34 {35 int times = method.getAnnotation(Repeat.class).value();3637 Description desc = Description.createSuiteDescription(testName(method)38 + "[" + times + "] times", method.getAnnotations());3940 for (int i = 0; i < times; ++i)41 {42 desc.addChild(Description.createTestDescription(getTestClass()43 .getJavaClass(), "[" + i + "] " + testName(method)));44 }4546 return desc;47 }4849 @Override50 protected void runChild(FrameworkMethod method, RunNotifier notifier)51 {5253 Description desc = describeChild(method);54 ResetSingleton resetSingle = desc.getAnnotation(ResetSingleton.class);5556 // wenn repeat an und ignore aus57 if (method.getAnnotation(Repeat.class) != null58 && method.getAnnotation(Ignore.class) == null)59 {60 if (resetSingle != null)61 {62 try63 {64 runRepeated(methodBlock(method), desc, notifier,65 resetSingle.type(), resetSingle.field());66 } catch (NoSuchFieldException | SecurityException67 | IllegalArgumentException | IllegalAccessException e)68 {69 e.printStackTrace();70 }71 }72 else
...
Source:ExtendedRunner.java
...20 } 21 22 @Override 23 protected Description describeChild(FrameworkMethod method) { 24 if (method.getAnnotation(Repeat.class) != null && 25 method.getAnnotation(Ignore.class) == null) { 26 return describeRepeatTest(method); 27 } 28 return super.describeChild(method); 29 } 30 31 private Description describeRepeatTest(FrameworkMethod method) { 32 int times = method.getAnnotation(Repeat.class).value(); 33 34 Description description = Description.createSuiteDescription( 35 testName(method) + " [" + times + " times]", 36 method.getAnnotations()); 37 38 for (int i = 1; i <= times; i++) { 39 description.addChild(Description.createTestDescription( 40 getTestClass().getJavaClass(), 41 "[" + i + "] " + testName(method))); 42 } 43 return description; 44 } 45 46 @Override 47 protected void runChild(final FrameworkMethod method, RunNotifier notifier) { 48 Description description = describeChild(method); 49 50 if (method.getAnnotation(Repeat.class) != null && 51 method.getAnnotation(Ignore.class) == null) { 52 runRepeatedly(methodBlock(method), description, notifier); 53 } 54 super.runChild(method, notifier); 55 } 56 57 private void runRepeatedly(Statement statement, Description description, 58 RunNotifier notifier) { 59 for (Description desc : description.getChildren()) { 60 runLeaf(statement, desc, notifier); 61 } 62 } 63} ...
Source:RepeatedRunner.java
...11 super(klass);12 }13 @Override14 protected Description describeChild(FrameworkMethod method) {15 if (method.getAnnotation(Repeat.class) != null && method.getAnnotation(Ignore.class) == null) {16 return describeRepeatTest(method);17 }18 return super.describeChild(method);19 }20 private Description describeRepeatTest(FrameworkMethod method) {21 int times = method.getAnnotation(Repeat.class).value();22 Description description = Description23 .createSuiteDescription(testName(method) + "(" + times + " times)", method.getAnnotations());24 for (int i = 1; i <= times; i++) {25 description.addChild(Description26 .createTestDescription(getTestClass().getJavaClass(), "[" + i + "] " + testName(method)));27 }28 return description;29 }30 @Override31 protected void runChild(final FrameworkMethod method, RunNotifier notifier) {32 Description description = describeChild(method);33 if (method.getAnnotation(Repeat.class) != null && method.getAnnotation(Ignore.class) == null) {34 runRepeatedly(methodBlock(method), description, notifier);35 }36 super.runChild(method, notifier);37 }38 private void runRepeatedly(Statement statement, Description description, RunNotifier notifier) {39 for (Description desc : description.getChildren()) {40 runLeaf(statement, desc, notifier);41 }42 }43}...
getAnnotation
Using AI Code Generation
1 public void testGetAnnotation() {2 Test test = new Test() {3 public Class<? extends Annotation> annotationType() {4 return null;5 }6 };7 Annotation annotation = test.getAnnotation(Test.class);8 assertEquals(test, annotation);9 }10}11OK (1 test)
getAnnotation
Using AI Code Generation
1public class TestRunner {2 public static void main(String[] args) throws Exception {3 Result result = JUnitCore.runClasses(TestJunit.class);4 for (Failure failure : result.getFailures()) {5 System.out.println(failure.toString());6 }7 System.out.println(result.wasSuccessful());8 }9}10public class TestRunner {11 public static void main(String[] args) throws Exception {12 Result result = JUnitCore.runClasses(TestJunit.class);13 for (Failure failure : result.getFailures()) {14 System.out.println(failure.toString());15 }16 System.out.println(result.wasSuccessful());17 }18}
getAnnotation
Using AI Code Generation
1public void testGetAnnotation() throws Exception {2 Class<?> testClass = Class.forName("com.example.junit.TestClass");3 Method method = testClass.getMethod("testMethod");4 Test test = method.getAnnotation(Test.class);5 System.out.println("test value: " + test.value());6 System.out.println("test timeout: " + test.timeout());7 System.out.println("test expected: " + test.expected());8 System.out.println("test groups: " + Arrays.toString(test.groups()));9}
getAnnotation
Using AI Code Generation
1public void testDescription() throws Exception {2 Method method = TestDescription.class.getMethod("testDescription");3 Description description = method.getAnnotation(Description.class);4 if (description != null) {5 System.out.println(description.value());6 } else {7 System.out.println("No description");8 }9}10@Description("The test method")11public void testDescription() throws Exception {12 Method method = TestDescription.class.getMethod("testDescription");13 Description description = method.getAnnotation(Description.class);14 if (description != null) {15 System.out.println(description.value());16 } else {17 System.out.println("No description");18 }19}20@Description("The test class")21public class TestDescription {22 @Description("The test method")23 public void testDescription() throws Exception {24 Method method = TestDescription.class.getMethod("testDescription");25 Description description = method.getAnnotation(Description.class);26 if (description != null) {27 System.out.println(description.value());28 } else {29 System.out.println("No description");30 }31 }32}33@Description("The test class")34public class TestDescription {35 @Description("The test method")36 public void testDescription() throws Exception {37 Method method = TestDescription.class.getMethod("testDescription");38 Description description = method.getAnnotation(Description.class);39 if (description != null) {40 System.out.println(description.value());41 } else {42 System.out.println("No description");43 }44 }45}46@Description("The test class")47public class TestDescription {48 public void testDescription() throws Exception {49 Method method = TestDescription.class.getMethod("testDescription");50 Description description = method.getAnnotation(Description.class);51 if (description != null) {52 System.out.println(description.value());53 } else {54 System.out.println("No description");55 }56 }57}
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.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!