Best junit code snippet using org.junit.runners.ParentRunner.getTestClass
Source:ParentRunner.java  
...70        validateClassRules(errors);71        applyValidators(errors);72    }73    private void applyValidators(List<Throwable> errors) {74        if (getTestClass().getJavaClass() != null) {75            for (TestClassValidator each : VALIDATORS) {76                errors.addAll(each.validateTestClass(getTestClass()));77            }78        }79    }80    /* access modifiers changed from: protected */81    public void validatePublicVoidNoArgMethods(Class<? extends Annotation> annotation, boolean isStatic, List<Throwable> errors) {82        for (FrameworkMethod eachTestMethod : getTestClass().getAnnotatedMethods(annotation)) {83            eachTestMethod.validatePublicVoidNoArg(isStatic, errors);84        }85    }86    private void validateClassRules(List<Throwable> errors) {87        RuleMemberValidator.CLASS_RULE_VALIDATOR.validate(getTestClass(), errors);88        RuleMemberValidator.CLASS_RULE_METHOD_VALIDATOR.validate(getTestClass(), errors);89    }90    /* access modifiers changed from: protected */91    public Statement classBlock(RunNotifier notifier) {92        Statement statement = childrenInvoker(notifier);93        if (!areAllChildrenIgnored()) {94            return withClassRules(withAfterClasses(withBeforeClasses(statement)));95        }96        return statement;97    }98    private boolean areAllChildrenIgnored() {99        for (T child : getFilteredChildren()) {100            if (!isIgnored(child)) {101                return false;102            }103        }104        return true;105    }106    /* access modifiers changed from: protected */107    public Statement withBeforeClasses(Statement statement) {108        List<FrameworkMethod> befores = this.testClass.getAnnotatedMethods(BeforeClass.class);109        if (befores.isEmpty()) {110            return statement;111        }112        return new RunBefores(statement, befores, null);113    }114    /* access modifiers changed from: protected */115    public Statement withAfterClasses(Statement statement) {116        List<FrameworkMethod> afters = this.testClass.getAnnotatedMethods(AfterClass.class);117        if (afters.isEmpty()) {118            return statement;119        }120        return new RunAfters(statement, afters, null);121    }122    private Statement withClassRules(Statement statement) {123        List<TestRule> classRules = classRules();124        if (classRules.isEmpty()) {125            return statement;126        }127        return new RunRules(statement, classRules, getDescription());128    }129    /* access modifiers changed from: protected */130    public List<TestRule> classRules() {131        List<TestRule> result = this.testClass.getAnnotatedMethodValues(null, ClassRule.class, TestRule.class);132        result.addAll(this.testClass.getAnnotatedFieldValues(null, ClassRule.class, TestRule.class));133        return result;134    }135    /* access modifiers changed from: protected */136    public Statement childrenInvoker(final RunNotifier notifier) {137        return new Statement() {138            /* class org.junit.runners.ParentRunner.AnonymousClass2 */139            @Override // org.junit.runners.model.Statement140            public void evaluate() {141                ParentRunner.this.runChildren(notifier);142            }143        };144    }145    /* access modifiers changed from: protected */146    public boolean isIgnored(T t) {147        return false;148    }149    /* access modifiers changed from: private */150    /* access modifiers changed from: public */151    private void runChildren(final RunNotifier notifier) {152        RunnerScheduler currentScheduler = this.scheduler;153        try {154            for (final T each : getFilteredChildren()) {155                currentScheduler.schedule(new Runnable() {156                    /* class org.junit.runners.ParentRunner.AnonymousClass3 */157                    /* JADX DEBUG: Multi-variable search result rejected for r0v0, resolved type: org.junit.runners.ParentRunner */158                    /* JADX WARN: Multi-variable type inference failed */159                    public void run() {160                        ParentRunner.this.runChild(each, notifier);161                    }162                });163            }164        } finally {165            currentScheduler.finished();166        }167    }168    /* access modifiers changed from: protected */169    public String getName() {170        return this.testClass.getName();171    }172    public final TestClass getTestClass() {173        return this.testClass;174    }175    /* access modifiers changed from: protected */176    public final void runLeaf(Statement statement, Description description, RunNotifier notifier) {177        EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);178        eachNotifier.fireTestStarted();179        try {180            statement.evaluate();181        } catch (AssumptionViolatedException e) {182            eachNotifier.addFailedAssumption(e);183        } catch (Throwable th) {184            eachNotifier.fireTestFinished();185            throw th;186        }...Source:NestedRunner.java  
...75        return children;76    }77    @Override78        public String getName() {79        return getTestClass().getJavaClass().getSimpleName();80    }81    protected Description describeChild(Object child) {82        if (child instanceof Runner) {83            return ((Runner)child).getDescription();84        } else {85            return delegatedRunner.callTheProtectedDescribeChild((FrameworkMethod)child);86        }87    }88    protected void runChild(Object child, RunNotifier notifier) {89        if (child instanceof Runner) {90            ((Runner)child).run(notifier);91        } else {92            delegatedRunner.callThePrivateRunChild((FrameworkMethod)child, notifier);93        }94    }95    private Object constructTestClass() throws Exception {96        if (getTestClass().getOnlyConstructor().getParameterTypes().length == 1 && parentRunner != null) {97            Object parent = parentRunner.constructTestClass();98            Object newInstance = getTestClass().getOnlyConstructor().newInstance(parent);99            delegatedRunner.currentTestObject = newInstance;100            return newInstance;101        }102        Object newInstance = getTestClass().getOnlyConstructor().newInstance();103        delegatedRunner.currentTestObject = newInstance;104        return newInstance;105    }106    public List<FrameworkMethod> getBefores() {107        List<FrameworkMethod> befores = new ArrayList<FrameworkMethod>();108        befores.addAll(getTestClass().getAnnotatedMethods(Before.class));109        return befores;110    }111    public List<FrameworkMethod> getAfters() {112        List<FrameworkMethod> afters = new ArrayList<FrameworkMethod>();113        afters.addAll(getTestClass().getAnnotatedMethods(After.class));114        return afters;115    }116    private Statement withParentBefores(Statement statement) {117        if (parentRunner != null) {118            return parentRunner.withParentBefores(new RunBefores(statement, getBefores(), delegatedRunner.currentTestObject));119        }120        return new RunBefores(statement, getBefores(), delegatedRunner.currentTestObject);121    }122    private Statement withParentAfters(Statement statement) {123        if (parentRunner != null) {124            return new RunAfters(parentRunner.withParentAfters(statement), getAfters(), delegatedRunner.currentTestObject);125        }126        return new RunAfters(statement, getAfters(), delegatedRunner.currentTestObject);127    }128    private class NestedClassRunner extends BlockJUnit4ClassRunner {129        private Object currentTestObject;130        public NestedClassRunner(Class<?> childClass) throws InitializationError {131            super(childClass);132        }133        public void callThePrivateRunChild(FrameworkMethod child, RunNotifier notifier) {134            runChild(child, notifier);135        }136        public Description callTheProtectedDescribeChild(FrameworkMethod child) {137            return describeChild(child);138        }139        public Collection<? extends Object> giveMeTheDamnChildren() {140            return super.getChildren();141        }142        protected void validateConstructor(List<Throwable> errors) {143            validateOnlyOneConstructor(errors);144            validateNonStaticInnerClassWithDefaultConstructor(errors);145        }146        private void validateNonStaticInnerClassWithDefaultConstructor(List<Throwable> errors) {147            try {148                getTestClass().getJavaClass().getConstructor(NestedRunner.this.getTestClass().getJavaClass());149            } catch (NoSuchMethodException e) {150                String gripe = "Nested test classes should be non-static and have a public zero-argument constructor";151                errors.add(new Exception(gripe));152            }153        }154        protected Object createTest() throws Exception {155            return constructTestClass();156        }157        protected Statement methodBlock(FrameworkMethod method) {158            Statement statement = super.methodBlock(method);159	    if (statement instanceof Fail) {160                return statement;161	    }162            statement = withParentBefores(statement);...Source:BlockJUnit4ClassRunnerWithParameters.java  
...12public class BlockJUnit4ClassRunnerWithParameters extends BlockJUnit4ClassRunner {13    private final String name;14    private final Object[] parameters;15    public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test) throws InitializationError {16        super(test.getTestClass().getJavaClass());17        this.parameters = test.getParameters().toArray(new Object[test.getParameters().size()]);18        this.name = test.getName();19    }20    @Override // org.junit.runners.BlockJUnit4ClassRunner21    public Object createTest() throws Exception {22        if (fieldsAreAnnotated()) {23            return createTestUsingFieldInjection();24        }25        return createTestUsingConstructorInjection();26    }27    private Object createTestUsingConstructorInjection() throws Exception {28        return getTestClass().getOnlyConstructor().newInstance(this.parameters);29    }30    private Object createTestUsingFieldInjection() throws Exception {31        List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();32        if (annotatedFieldsByParameter.size() == this.parameters.length) {33            Object testClassInstance = getTestClass().getJavaClass().newInstance();34            for (FrameworkField each : annotatedFieldsByParameter) {35                Field field = each.getField();36                int index = ((Parameterized.Parameter) field.getAnnotation(Parameterized.Parameter.class)).value();37                try {38                    field.set(testClassInstance, this.parameters[index]);39                } catch (IllegalArgumentException iare) {40                    throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + this.parameters[index] + " that is not the right type (" + this.parameters[index].getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare);41                }42            }43            return testClassInstance;44        }45        throw new Exception("Wrong number of parameters and @Parameter fields. @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + this.parameters.length + ".");46    }47    /* access modifiers changed from: protected */48    @Override // org.junit.runners.ParentRunner49    public String getName() {50        return this.name;51    }52    /* access modifiers changed from: protected */53    @Override // org.junit.runners.BlockJUnit4ClassRunner54    public String testName(FrameworkMethod method) {55        return method.getName() + getName();56    }57    /* access modifiers changed from: protected */58    @Override // org.junit.runners.BlockJUnit4ClassRunner59    public void validateConstructor(List<Throwable> errors) {60        validateOnlyOneConstructor(errors);61        if (fieldsAreAnnotated()) {62            validateZeroArgConstructor(errors);63        }64    }65    /* access modifiers changed from: protected */66    @Override // org.junit.runners.BlockJUnit4ClassRunner67    public void validateFields(List<Throwable> errors) {68        super.validateFields(errors);69        if (fieldsAreAnnotated()) {70            List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();71            int[] usedIndices = new int[annotatedFieldsByParameter.size()];72            for (FrameworkField each : annotatedFieldsByParameter) {73                int index = ((Parameterized.Parameter) each.getField().getAnnotation(Parameterized.Parameter.class)).value();74                if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {75                    errors.add(new Exception("Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + "."));76                } else {77                    usedIndices[index] = usedIndices[index] + 1;78                }79            }80            for (int index2 = 0; index2 < usedIndices.length; index2++) {81                int numberOfUse = usedIndices[index2];82                if (numberOfUse == 0) {83                    errors.add(new Exception("@Parameter(" + index2 + ") is never used."));84                } else if (numberOfUse > 1) {85                    errors.add(new Exception("@Parameter(" + index2 + ") is used more than once (" + numberOfUse + ")."));86                }87            }88        }89    }90    /* access modifiers changed from: protected */91    @Override // org.junit.runners.ParentRunner92    public Statement classBlock(RunNotifier notifier) {93        return childrenInvoker(notifier);94    }95    /* access modifiers changed from: protected */96    @Override // org.junit.runners.ParentRunner97    public Annotation[] getRunnerAnnotations() {98        return new Annotation[0];99    }100    private List<FrameworkField> getAnnotatedFieldsByParameter() {101        return getTestClass().getAnnotatedFields(Parameterized.Parameter.class);102    }103    private boolean fieldsAreAnnotated() {104        return !getAnnotatedFieldsByParameter().isEmpty();105    }106}...Source:TestWrapper.java  
...37    public TestWrapper(Class<?> klass, RunnerBuilder builder) throws InitializationError {38        super(klass);39        // the real test runner we're about to construct may be affected by our setup40        beforeAll();41        WrapperOptions options = getTestClass().getAnnotation(WrapperOptions.class);42        if (options == null) {43            actualRunner = new BlockJUnit4ClassRunner(klass);44        } else {45            try {46                AnnotatedBuilder annotatedBuilder = new AnnotatedBuilder(builder);47                // make the runner from the options48                actualRunner = (ParentRunner<?>)annotatedBuilder.buildRunner(options.runWith(), klass);49            } catch (Exception e) {50                throw new InitializationError(e);51            }52        }53    }54    @Override55    protected List<Runner> getChildren() {56        if (!shouldRun()) {57            System.out.println("Filtering out: " + getTestClass().getJavaClass().getCanonicalName());58            return emptyList();59        }60        return singletonList(actualRunner);61    }62    @Override63    protected Description describeChild(Runner testWrapper) {64        return testWrapper.getDescription();65    }66    @Override67    protected void runChild(Runner testWrapper, RunNotifier runNotifier) {68        testWrapper.run(runNotifier);69        afterAll();70    }71    @SuppressWarnings("unchecked")72    private boolean shouldRun() {73        return getTestClass().getAnnotatedFields(Plugin.class)74            .stream()75            .filter(FrameworkMember::isStatic)76            .filter(field -> TestFilter.class.isAssignableFrom(field.getType()))77            .map(this::filterAsPredicate)78            .allMatch(predicate -> predicate.test(getTestClass().getJavaClass()));79    }80    private TestFilter filterAsPredicate(FrameworkField field) {81        try {82            return (TestFilter)field.getField().get(getTestClass().getJavaClass());83        } catch (IllegalAccessException e) {84            throw new TestWrapperError("Cannot apply filter in: " + field.toString(), e);85        }86    }87    private void beforeAll() {88        getTestClass().getAnnotatedFields(Plugin.class)89            .stream()90            .filter(FrameworkMember::isStatic)91            .filter(field -> BeforeAction.class.isAssignableFrom(field.getType()))92            .forEach(this::executeBeforeAction);93    }94    private void afterAll() {95        getTestClass().getAnnotatedFields(Plugin.class)96            .stream()97            .filter(FrameworkMember::isStatic)98            .filter(field -> AfterAction.class.isAssignableFrom(field.getType()))99            .forEach(this::executeAfterAction);100    }101    @SuppressWarnings("unchecked")102    private void executeBeforeAction(FrameworkField field) {103        try {104            Class<?> clazz = getTestClass().getJavaClass();105            ((BeforeAction)field.getField().get(clazz)).before(clazz);106        } catch (Throwable t) {107            throw new TestWrapperError("Cannot perform before action in: " + field.toString(), t);108        }109    }110    @SuppressWarnings("unchecked")111    private void executeAfterAction(FrameworkField field) {112        try {113            Class<?> clazz = getTestClass().getJavaClass();114            ((AfterAction)field.getField().get(clazz)).after(clazz);115        } catch (Throwable t) {116            throw new TestWrapperError("Cannot perform after action in: " + field.toString(), t);117        }118    }119}...Source:ParentRunnerClassLoaderTest.java  
...18        runTestWithParentRunner(testClassWithOwnClassLoader);19        Field fieldWithReference = testClassWithOwnClassLoader.getDeclaredField("applyTestClass");20        Class<?> usedClass = (Class<?>) fieldWithReference.get(null);21        assertEquals("JUnitRunner can be located in own classLoader, so, " +22                        "Class.forName org.junit.runner.Description.getTestClass can not see " +23                        "in current classloader by execute Class.forName",24                testClassWithOwnClassLoader, usedClass25        );26    }27    @Test28    public void testDescriptionContainCorrectTestClass() throws Exception {29        Class<?> testClassWithOwnClassLoader = wrapToClassLoader(TestWithClassRule.class);30        ParentRunner<?> runner = new BlockJUnit4ClassRunner(testClassWithOwnClassLoader);31        Description description = runner.getDescription();32        assertEquals("ParentRunner accept already instantiate Class<?> with tests, if we lost it instance, and will " +33                "use Class.forName we can not find test class again, because tests can be " +34                "located in different ClassLoader",35                description.getTestClass(), testClassWithOwnClassLoader36        );37    }38    @Test39    public void testBackwardCompatibilityWithOverrideGetName() throws Exception {40        final Class<TestWithClassRule> originalTestClass = TestWithClassRule.class;41        final Class<?> waitClass = ParentRunnerClassLoaderTest.class;42        ParentRunner<FrameworkMethod> subParentRunner = new BlockJUnit4ClassRunner(originalTestClass) {43            @Override44            protected String getName() {45                return waitClass.getName();46            }47        };48        Description description = subParentRunner.getDescription();49        Class<?> result = description.getTestClass();50        assertEquals("Subclass of ParentRunner can override getName method and specify another test class for run, " +51                "we should  maintain backwards compatibility with JUnit 4.12",52                waitClass, result53        );54    }55    private void runTestWithParentRunner(Class<?> testClass) throws InitializationError {56        ParentRunner<?> runner = new BlockJUnit4ClassRunner(testClass);57        runner.run(new RunNotifier());58    }59    private Class<?> wrapToClassLoader(Class<?> sourceClass) throws ClassNotFoundException {60        URL classpath = sourceClass.getProtectionDomain().getCodeSource().getLocation();61        VisibleClassLoader loader = new VisibleClassLoader(new URL[]{classpath}, this.getClass().getClassLoader());62        Class<?> testClassWithOwnClassLoader = loader.findClass(sourceClass.getName());63        assert testClassWithOwnClassLoader != sourceClass;...getTestClass
Using AI Code Generation
1public class ParentRunnerTest {2    public void testGetTestClass() throws Exception {3        ParentRunner<?> runner = new ParentRunner<Object>(Object.class) {4            protected List<Object> getChildren() {5                return null;6            }7            protected Description describeChild(Object child) {8                return null;9            }10            protected void runChild(Object child, RunNotifier notifier) {11            }12        };13        assertEquals(Object.class, runner.getTestClass());14    }15}16package org.junit.tests.running.classes;17import static org.junit.Assert.assertEquals;18import java.util.List;19import org.junit.Test;20import org.junit.runner.Description;21import org.junit.runner.notification.RunNotifier;22import org.junit.runners.ParentRunner;23 * The class <code>ParentRunnerTest</code> contains tests for the class {@link <code>ParentRunner</code>}24public class ParentRunnerTest {25    public ParentRunnerTest(String name) {26    }27     * @see TestCase#setUp()28     * @see TestCase#setUp()29    protected void setUp() throws Exception {30    }31     * @see TestCase#tearDown()32     * @see TestCase#tearDown()33    protected void tearDown() throws Exception {34    }35    public static void main(String[] args) {36    }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!!
