Best junit code snippet using org.junit.runner.Description.getAnnotation
Source:AbstractMultiTestRunner.java
...97 RunnerBuilder runnerBuilder = new RunnerBuilder() {98 @Override99 public Runner runnerForClass(Class<?> testClass) throws Throwable {100 for (Class<?> candidate = testClass; candidate != null; candidate = candidate.getSuperclass()) {101 RunWith runWith = candidate.getAnnotation(RunWith.class);102 if (runWith != null && !AbstractMultiTestRunner.class.isAssignableFrom(runWith.value())) {103 try {104 Runner r = (Runner) runWith.value().getConstructors()[0].newInstance(testClass);105 return filter(r);106 } catch (InvocationTargetException e) {107 throw e.getTargetException();108 }109 }110 }111 return filter(new BlockJUnit4ClassRunner(testClass));112 }113 //we need to filter at the level child runners because the suite is not doing the right thing here114 private Runner filter(Runner r) {115 for (Filter filter : filters) {116 try {117 ((Filterable)r).filter(filter);118 } catch (NoTestsRemainException e) {119 //ignore120 }121 }122 return r;123 }124 };125 return new Suite(runnerBuilder, targetClasses.toArray(new Class<?>[targetClasses.size()]));126 }127 protected static abstract class Execution implements Filterable {128 protected Class<?> target;129 private Description templateDescription;130 private final Map<Description, Description> descriptionTranslations = new HashMap<Description, Description>();131 private final Set<Description> enabledTests = new LinkedHashSet<Description>();132 private final Set<Description> disabledTests = new LinkedHashSet<Description>();133 private final List<Filter> filters = new LinkedList<Filter>();134 final void init(Class<?> target, Description templateDescription) {135 this.target = target;136 this.templateDescription = templateDescription;137 }138 private Runner createExecutionRunner() throws InitializationError {139 List<? extends Class<?>> targetClasses = loadTargetClasses();140 return createRunnerFor(targetClasses, filters);141 }142 final void addDescriptions(Description parent) {143 map(templateDescription, parent);144 }145 final void run(final RunNotifier notifier) {146 RunNotifier nested = new RunNotifier();147 NestedRunListener nestedListener = new NestedRunListener(notifier);148 nested.addListener(nestedListener);149 try {150 runEnabledTests(nested);151 } finally {152 nestedListener.cleanup();153 }154 for (Description disabledTest : disabledTests) {155 nested.fireTestStarted(disabledTest);156 nested.fireTestIgnored(disabledTest);157 }158 }159 private void runEnabledTests(RunNotifier nested) {160 if (enabledTests.isEmpty()) {161 return;162 }163 Runner runner;164 try {165 runner = createExecutionRunner();166 } catch (Throwable t) {167 runner = new CannotExecuteRunner(getDisplayName(), target, t);168 }169 try {170 if (!disabledTests.isEmpty()) {171 ((Filterable) runner).filter(new Filter() {172 @Override173 public boolean shouldRun(Description description) {174 return !disabledTests.contains(description);175 }176 @Override177 public String describe() {178 return "disabled tests";179 }180 });181 }182 } catch (NoTestsRemainException e) {183 return;184 }185 runner.run(nested);186 }187 private Description translateDescription(Description description) {188 return descriptionTranslations.containsKey(description) ? descriptionTranslations.get(description) : description;189 }190 public void filter(Filter filter) throws NoTestsRemainException {191 filters.add(filter);192 for (Map.Entry<Description, Description> entry : descriptionTranslations.entrySet()) {193 if (!filter.shouldRun(entry.getKey())) {194 enabledTests.remove(entry.getValue());195 disabledTests.remove(entry.getValue());196 }197 }198 }199 protected void before() {200 }201 protected void after() {202 }203 private void map(Description source, Description parent) {204 for (Description child : source.getChildren()) {205 Description mappedChild;206 if (child.getMethodName() != null) {207 mappedChild = Description.createSuiteDescription(String.format("%s [%s](%s)", child.getMethodName(), getDisplayName(), child.getClassName()));208 parent.addChild(mappedChild);209 if (!isTestEnabled(new TestDescriptionBackedTestDetails(source, child))) {210 disabledTests.add(child);211 } else {212 enabledTests.add(child);213 }214 } else {215 mappedChild = Description.createSuiteDescription(child.getClassName());216 }217 descriptionTranslations.put(child, mappedChild);218 map(child, parent);219 }220 }221 /**222 * Returns a display name for this execution. Used in the JUnit descriptions for test execution.223 */224 protected abstract String getDisplayName();225 /**226 * Returns true if the given test should be executed, false if it should be ignored. Default is true.227 */228 protected boolean isTestEnabled(TestDetails testDetails) {229 return true;230 }231 /**232 * Checks that this execution can be executed, throwing an exception if not.233 */234 protected void assertCanExecute() {235 }236 /**237 * Loads the target classes for this execution. Default is the target class that this runner was constructed with.238 */239 protected List<? extends Class<?>> loadTargetClasses() {240 return Collections.singletonList(target);241 }242 private static class CannotExecuteRunner extends Runner {243 private final Description description;244 private final Throwable failure;245 public CannotExecuteRunner(String displayName, Class<?> testClass, Throwable failure) {246 description = Description.createSuiteDescription(String.format("%s(%s)", displayName, testClass.getName()));247 this.failure = failure;248 }249 @Override250 public Description getDescription() {251 return description;252 }253 @Override254 public void run(RunNotifier notifier) {255 Description description = getDescription();256 notifier.fireTestStarted(description);257 notifier.fireTestFailure(new Failure(description, failure));258 notifier.fireTestFinished(description);259 }260 }261 private class NestedRunListener extends RunListener {262 private final RunNotifier notifier;263 boolean started;264 boolean complete;265 public NestedRunListener(RunNotifier notifier) {266 this.notifier = notifier;267 }268 @Override269 public void testStarted(Description description) {270 Description translated = translateDescription(description);271 notifier.fireTestStarted(translated);272 if (!started && !complete) {273 try {274 assertCanExecute();275 started = true;276 before();277 } catch (Throwable t) {278 notifier.fireTestFailure(new Failure(translated, t));279 }280 }281 }282 @Override283 public void testFailure(Failure failure) {284 Description translated = translateDescription(failure.getDescription());285 notifier.fireTestFailure(new Failure(translated, failure.getException()));286 }287 @Override288 public void testAssumptionFailure(Failure failure) {289 Description translated = translateDescription(failure.getDescription());290 notifier.fireTestAssumptionFailed(new Failure(translated, failure.getException()));291 }292 @Override293 public void testIgnored(Description description) {294 Description translated = translateDescription(description);295 notifier.fireTestIgnored(translated);296 }297 @Override298 public void testFinished(Description description) {299 Description translated = translateDescription(description);300 notifier.fireTestFinished(translated);301 }302 public void cleanup() {303 if (started) {304 after();305 }306 // Prevent further tests (ignored) from triggering start actions307 complete = true;308 }309 }310 }311 public interface TestDetails {312 /**313 * Locates the given annotation for the test. May be inherited from test class.314 */315 @Nullable316 <A extends Annotation> A getAnnotation(Class<A> type);317 }318 private static class TestDescriptionBackedTestDetails implements TestDetails {319 private final Description parent;320 private final Description test;321 private TestDescriptionBackedTestDetails(Description parent, Description test) {322 this.parent = parent;323 this.test = test;324 }325 @Override326 public String toString() {327 return test.toString();328 }329 public <A extends Annotation> A getAnnotation(Class<A> type) {330 A annotation = test.getAnnotation(type);331 if (annotation != null) {332 return annotation;333 }334 return parent.getAnnotation(type);335 }336 }337}...
Source:LessVerboseTextListener.java
...98 ex.printStackTrace();99 }100 }101 @SuppressWarnings("unchecked")102 public static <T extends Annotation> T getAnnotation(Class<?> q, String methodName, Class<T> a) {103 try {104 if (q != null) {105 T rem = q.getAnnotation(a);106 if (rem != null) {107 return rem;108 }109 String qs = methodName;110 if (qs.contains(" - ")) {111 qs = qs.replaceAll(" - .*", "");112 }113 Method qm = q.getMethod(qs);114 if (qm != null) {115 rem = qm.getAnnotation(a);116 return rem;117 }118 }119 } catch (Exception ex) {120 ex.printStackTrace();121 }122 return null;123 }124 public static KnownToFail getK2F(Description description) {125 return getAnnotation(description.getTestClass(), description.getMethodName(), KnownToFail.class);126 }127 public static Remote getRemote(Description description) {128 return getAnnotation(description.getTestClass(), description.getMethodName(), Remote.class);129 }130 private void printRemote(PrintStream writer, Description description) {131 try {132 Remote rem = getRemote(description);133 if (rem != null) {134 writer.println(" - This test is running remote content, note that failures may be caused by broken target application or connection");135 }136 } catch (Exception ex) {137 ex.printStackTrace();138 }139 }140}...
Source:RunUntilFailure.java
...31 super(klass); 32 } 33 @Override 34 protected Description describeChild(FrameworkMethod method) { 35 if (method.getAnnotation(Repeat.class) != null && 36 method.getAnnotation(Ignore.class) == null) { 37 return describeRepeatTest(method); 38 } 39 return super.describeChild(method); 40 } 41 private Description describeRepeatTest(FrameworkMethod method) { 42 int times = method.getAnnotation(Repeat.class).value(); 43 Description description = Description.createSuiteDescription( 44 testName(method) + " [" + times + " times]", 45 method.getAnnotations()); 46 for (int i = 1; i <= times; i++) { 47 description.addChild(Description.createTestDescription( 48 getTestClass().getJavaClass(), 49 testName(method) + "-" + i)); 50 } 51 return description; 52 } 53 @Override 54 protected void runChild(final FrameworkMethod method, RunNotifier notifier) { 55 Description description = describeChild(method); 56 if (method.getAnnotation(Repeat.class) != null && 57 method.getAnnotation(Ignore.class) == null) { 58 runRepeatedly(methodBlock(method), description, notifier); 59 } 60 super.runChild(method, notifier); 61 } 62 private void runRepeatedly(Statement statement, Description description, 63 RunNotifier notifier) {64 notifier.addListener(new RunListener() {65 @Override66 public void testFailure(Failure failure) {67 hasFailure = true;68 }69 });70 for (Description desc : description.getChildren()) { 71 if (hasFailure) {...
Source:DojoTestRunner.java
...23 private DojoTestClient dojoClient;2425 public DojoTestRunner(Class<?> klass) throws InitializationError {26 runner = new BlockJUnit4ClassRunner(klass);27 ReportTo annotation = klass.getAnnotation(ReportTo.class);28 if (annotation == null) {29 throw new InitializationError("Annotation @" + ReportTo.class.getSimpleName() +30 " should be defined at a class level");31 }32 dojoClient = new DojoTestClient(annotation.server(), annotation.userName());33 }3435 @Override36 public Description getDescription() {37 return runner.getDescription();38 }3940 @Override41 public void run(RunNotifier notifier) {42 TestListener listener = new TestListener();43 notifier.addListener(listener);4445 runner.run(notifier);46 try {47 String response = dojoClient.sendResultsToServer();48 System.out.println("-----------------------------------------------------------------");49 System.out.println("Send: '" + dojoClient.getResult() + "'");50 System.out.println("Server answer: \n" + response);51 System.out.println("-----------------------------------------------------------------");52 } catch (IOException e) {53 reportSendFailure(listener, e);54 }55 }5657 private void reportSendFailure(TestListener listener, Exception e) {58 try {59 listener.testFailure(new Failure(getDescription(), e));60 } catch (Exception e1) {61 e1.printStackTrace();62 }63 }6465 @Override66 public int testCount() {67 return runner.testCount();68 }6970 public void filter(Filter filter) throws NoTestsRemainException {71 runner.filter(filter);72 }7374 private class TestListener extends RunListener {75 private Map<Description, Failure> testFailures = new HashMap<Description, Failure>();767778 @Override79 public void testFailure(Failure failure) throws Exception {80 testFailures.put(failure.getDescription(), failure);81 }8283 @Override84 public void testFinished(Description description) throws Exception {85 Scenario scenario = description.getAnnotation(Scenario.class);86 if (scenario == null) {87 return;88 }8990 Failure failure = testFailures.get(description);91 dojoClient.addResult(failure, scenario.value());92 }93 }94}9596
...
Source:ExpoTestRunner.java
...22 testConfig = TestConfig.get();23 }24 @Override25 public boolean shouldRun(Description description) {26 if (description.getAnnotation(ExpoAlwaysPassThroughFilter.class) != null) {27 return true;28 }29 JSONArray testTypes = testConfig.optJSONArray(TEST_TYPES_KEY);30 if (testTypes != null) {31 boolean foundTestType = false;32 for (int i = 0; i < testTypes.length(); i++) {33 if (testTypes.optString(i).equals(TEST_SUITE_TEST_TYPE) && description.getAnnotation(ExpoTestSuiteTest.class) != null) {34 foundTestType = true;35 } else if (testTypes.optString(i).equals(DEV_MODE_TEST_TYPE) && description.getAnnotation(ExpoDevModeTest.class) != null) {36 foundTestType = true;37 }38 }39 if (!foundTestType) {40 return false;41 }42 }43 JSONArray sdkVersions = testConfig.optJSONArray(SDK_VERSIONS_KEY);44 ExpoSdkVersionTest sdkVersionAnnotation = description.getAnnotation(ExpoSdkVersionTest.class);45 if (sdkVersions != null && sdkVersionAnnotation != null) {46 boolean foundSdkVersion = false;47 for (int i = 0; i < sdkVersions.length(); i++) {48 if (sdkVersionAnnotation.value().equals(sdkVersions.optString(i))) {49 foundSdkVersion = true;50 }51 }52 if (!foundSdkVersion) {53 return false;54 }55 }56 return true;57 }58 @Override...
Source:CustomListener.java
...35 * Creates the TestInfo object and populates name and descirption (if available)36 */37 public void testStarted(Description description) {38 // if not a an annotated test return39 if(description.getAnnotation(Test.class) == null) {40 return;41 }42 // increment test count43 meta.incrementNumTests();44 45 // create entry for this test46 this.outputMap.put(description.getMethodName(), 47 new TestInfo(description.getMethodName()));48 49 50 // Check for description annotation51 if(description.getAnnotation(TestDescription.class) != null) {52 53 // get annotation54 TestDescription td = description.getAnnotation(TestDescription.class);55 56 // get value57 String descriptionText = td.value();58 59 // get map entry and set its description60 outputMap.get(description.getMethodName()).setDescription(descriptionText);61 62 } 63 // if no description, set empty string64 else {65 // get map entry and set its description66 outputMap.get(description.getMethodName()).setDescription("");67 }68 // Check for hint annotation69 if(description.getAnnotation(TestDescription.class) != null) {70 // get annotation71 TestHint th = description.getAnnotation(TestHint.class);72 // get value73 String hintText = th.value();74 // get map entry and set its hint75 outputMap.get(description.getMethodName()).setHint(hintText);76 }77 // if no hint, set empty string78 else{79 // get map entry and set its hint80 outputMap.get(description.getMethodName()).setHint("");81 }82 83 }84 85 /**...
Source:AbstractBumblebeeRunner.java
...22 super();23 fName = klass.getName();24 addParent(klass);25 for (Class<?> each : JUnit.getAnnotatedTestClasses(klass)) {26 if(each.getAnnotation(RunWith.class)==null&&each.getAnnotation(SuiteClasses.class)!=null) {27 add(new BumbleBeeSubSuiteRunner(each));28 } else {29 Runner childRunner= Request.aClass(each).getRunner();30 if (childRunner != null) {31 add(childRunner);32 }33 }34 }35 removeParent(klass);36 }37 38 @Override39 public void run(RunNotifier notifier) {40 runChildren(notifier);
...
Source:AnnotatedDescriptionTest.java
...26 }2728 @Test29 public void annotationsExistOnDescriptionsOfClasses() {30 assertTrue((describe(AnnotatedClass.class).getAnnotation(31 MyOwnAnnotation.class) != null));32 }3334 @Test35 public void getAnnotationsReturnsAllAnnotations() {36 assertEquals(1, describe(ValueAnnotatedClass.class).getAnnotations()37 .size());38 }3940 @Ignore41 public static class IgnoredClass {42 @Test43 public void a() {44 }45 }4647 @Test48 public void annotationsExistOnDescriptionsOfIgnoredClass() {49 assertTrue((describe(IgnoredClass.class).getAnnotation(Ignore.class) != null));50 }5152 @Retention(RetentionPolicy.RUNTIME)53 public @interface ValuedAnnotation {54 String value();55 }5657 @ValuedAnnotation("hello")58 public static class ValueAnnotatedClass {59 @Test60 public void a() {61 }62 }6364 @Test65 public void descriptionOfTestClassHasValuedAnnotation() {66 Description description= describe(ValueAnnotatedClass.class);67 assertEquals("hello", description.getAnnotation(ValuedAnnotation.class)68 .value());69 }7071 @Test72 public void childlessCopyOfDescriptionStillHasAnnotations() {73 Description description= describe(ValueAnnotatedClass.class);74 assertEquals("hello", description.childlessCopy().getAnnotation(ValuedAnnotation.class)75 .value());76 }7778 @Test79 public void characterizeCreatingMyOwnAnnotation() {80 Annotation annotation= new Ignore() {81 public String value() {82 return "message";83 }8485 public Class<? extends Annotation> annotationType() {86 return Ignore.class;87 }88 };
...
getAnnotation
Using AI Code Generation
1import org.junit.runner.Description;2import org.junit.runner.JUnitCore;3import org.junit.runner.Request;4import org.junit.runner.Result;5import org.junit.runner.notification.Failure;6public class TestRunner {7 public static void main(String[] args) {8 Result result = JUnitCore.runClasses(TestJunit.class);9 for (Failure failure : result.getFailures()) {10 System.out.println(failure.toString());11 }12 System.out.println("Result=="+result.wasSuccessful());13 }14}
getAnnotation
Using AI Code Generation
1import org.junit.runner.Description;2import org.junit.runner.notification.Failure;3public class MyFailure extends Failure {4 public MyFailure(Description description, Throwable thrownException) {5 super(description, thrownException);6 }7 public String toString() {8 return "MyFailure [description=" + getDescription() + ", thrownException=" + getException() + "]";9 }10}11import org.junit.runner.Description;12import org.junit.runner.notification.Failure;13public class MyFailure extends Failure {14 public MyFailure(Description description, Throwable thrownException) {15 super(description, thrownException);16 }17 public String toString() {18 return "MyFailure [description=" + getDescription() + ", thrownException=" + getException() + "]";19 }20}21import org.junit.runner.Description;22import org.junit.runner.notification.Failure;23public class MyFailure extends Failure {24 public MyFailure(Description description, Throwable thrownException) {25 super(description, thrownException);26 }27 public String toString() {28 return "MyFailure [description=" + getDescription() + ", thrownException=" + getException() + "]";29 }30}31import org.junit.runner.Description;32import org.junit.runner.notification.Failure;33public class MyFailure extends Failure {34 public MyFailure(Description description, Throwable thrownException) {35 super(description, thrownException);36 }37 public String toString() {38 return "MyFailure [description=" + getDescription() + ", thrownException=" + getException() + "]";39 }40}41import org.junit.runner.Description;42import org.junit.runner.notification.Failure;43public class MyFailure extends Failure {44 public MyFailure(Description description, Throwable thrownException) {45 super(description, thrownException);46 }47 public String toString() {48 return "MyFailure [description=" + getDescription() + ", thrownException=" + getException() + "]";49 }50}51import org.junit.runner.Description;52import org.junit.runner.notification.Failure;53public class MyFailure extends Failure {54 public MyFailure(Description description, Throwable thrownException) {55 super(description, thrownException);56 }
getAnnotation
Using AI Code Generation
1import org.junit.runner.Description;2import org.junit.runner.notification.RunNotifier;3import org.junit.runners.BlockJUnit4ClassRunner;4import org.junit.runners.model.InitializationError;5import org.junit.runners.model.Statement;6public class MyRunner extends BlockJUnit4ClassRunner {7 public MyRunner(Class<?> klass) throws InitializationError {8 super(klass);9 }10 protected void runChild(Description description, RunNotifier notifier) {11 MyAnnotation annotation = description.getAnnotation(MyAnnotation.class);12 if (annotation != null) {13 System.out.println("annotation.value() = " + annotation.value());14 }15 super.runChild(description, notifier);16 }17 protected Statement withBeforeClasses(Statement statement) {18 System.out.println("MyRunner.withBeforeClasses");19 return super.withBeforeClasses(statement);20 }21 protected Statement withAfterClasses(Statement statement) {22 System.out.println("MyRunner.withAfterClasses");23 return super.withAfterClasses(statement);24 }25 protected Statement withBeforeClasses(Statement statement) {26 System.out.println("MyRunner.withBeforeClasses");27 return super.withBeforeClasses(statement);28 }29 protected Statement withAfterClasses(Statement statement) {30 System.out.println("MyRunner.withAfterClasses");31 return super.withAfterClasses(statement);32 }33}34import org.junit.Test;35import org.junit.runner.RunWith;36@RunWith(MyRunner.class)37public class TestClass {38 @MyAnnotation("test1")39 public void test1() {40 System.out.println("TestClass.test1");41 }42 @MyAnnotation("test2")43 public void test2() {44 System.out.println("TestClass.test2");45 }46 public void test3() {47 System.out.println("TestClass.test3");48 }49}50import java.lang.annotation.ElementType;51import java.lang.annotation.Retention;52import java.lang.annotation.RetentionPolicy;53import java.lang.annotation.Target;54@Retention(RetentionPolicy.RUNTIME)55@Target({ElementType.METHOD})56public @interface MyAnnotation {57 String value() default "";58}59annotation.value() = test160annotation.value() = test2
getAnnotation
Using AI Code Generation
1import org.junit.runner.Description;2import java.lang.annotation.Annotation;3public class JunitDescription {4 public static void main(String[] args) {5 Description description = Description.createSuiteDescription("MySuite");6 description.addChild(Description.createTestDescription("MyTest1", "test1"));7 description.addChild(Description.createTestDescription("MyTest2", "test2"));8 Annotation annotation = description.getAnnotation(MyAnnotation.class);9 System.out.println(annotation);10 }11}12@com.journaldev.junit.MyAnnotation()
getAnnotation
Using AI Code Generation
1public void testGetAnnotation() throws Exception {2 Description description = Description.createTestDescription(3 this.getClass(), "testGetAnnotation");4 assertEquals("testGetAnnotation", description.getMethodName());5}6public void testGetAnnotations() throws Exception {7 Description description = Description.createTestDescription(8 this.getClass(), "testGetAnnotations");9 assertEquals("testGetAnnotations", description.getMethodName());10}11public void testGetTestClass() throws Exception {12 Description description = Description.createTestDescription(13 this.getClass(), "testGetTestClass");14 assertEquals(this.getClass(), description.getTestClass());15}16public void testGetMethodName() throws Exception {17 Description description = Description.createTestDescription(18 this.getClass(), "testGetMethodName");19 assertEquals("testGetMethodName", description.getMethodName());20}21public void testGetDisplayName() throws Exception {22 Description description = Description.createTestDescription(23 this.getClass(), "testGetDisplayName");24 assertEquals("testGetDisplayName", description.getDisplayName());25}26public void testGetChildren() throws Exception {27 Description description = Description.createTestDescription(28 this.getClass(), "testGetChildren");29 assertEquals("testGetChildren", description.getMethodName());30}31public void testGetClassName() throws Exception {32 Description description = Description.createTestDescription(33 this.getClass(), "testGetClassName");34 assertEquals("testGetClassName", description.getMethodName());35}36public void testCreateSuiteDescription() throws Exception {37 Description description = Description.createSuiteDescription(38 this.getClass(), new Annotation[]{});39 assertEquals("testCreateSuiteDescription", description.getMethodName());40}
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!!