Best junit code snippet using org.junit.runners.model.FrameworkMethod.getName
Source:LoadTimeWeavableTestRunner.java  
...119        validate();120    }121    private TestClass getCustomTestClass(Class<?> originalTestClass, ClassLoader customLoader) {122        try {123            Class<?> newTestClass = customLoader.loadClass(originalTestClass.getName());124            if (newTestClass == originalTestClass) {125                throw new IllegalStateException(newTestClass.getName() + " loaded from custom class loader should have been a different instance but was the same!");126            }127            return new TestClass(newTestClass);128        } catch (ClassNotFoundException e) {129            throw new IllegalStateException("Failed to load test class from custom classloader: " + originalTestClass.getName());130        }131    }132    protected ClassLoader getCustomClassLoader() {133        return customLoader;134    }135    /**136     * Adds to {@code errors} if any method in this class is annotated with137     * {@code annotation}, but:138     * <ul>139     * <li>is not public, or140     * <li>takes parameters, or141     * <li>returns something other than void, or142     * <li>is static (given {@code isStatic is false}), or143     * <li>is not static (given {@code isStatic is true}).144     */145    protected void validatePublicVoidNoArgMethods(Class<? extends Annotation> annotation,146            boolean isStatic, List<Throwable> errors) {147        List<FrameworkMethod> methods = getOriginalTestClass().getAnnotatedMethods(annotation);148        for (FrameworkMethod eachTestMethod : methods) {149            eachTestMethod.validatePublicVoidNoArg(isStatic, errors);150        }151    }152    private void validateClassRules(List<Throwable> errors) {153        CLASS_RULE_VALIDATOR.validate(getOriginalTestClass(), errors);154        CLASS_RULE_METHOD_VALIDATOR.validate(getOriginalTestClass(), errors);155    }156    /**157     * Constructs a {@code Statement} to run all of the tests in the test class. Override to add pre-/post-processing.158     * Here is an outline of the implementation:159     * <ul>160     * <li>Call {@link #runChild(org.junit.runners.model.FrameworkMethod, org.junit.runner.notification.RunNotifier)} on each object returned by {@link #getChildren()} (subject to any imposed filter and sort).</li>161     * <li>ALWAYS run all non-overridden {@code @BeforeClass} methods on this class162     * and superclasses before the previous step; if any throws an163     * Exception, stop execution and pass the exception on.164     * <li>ALWAYS run all non-overridden {@code @AfterClass} methods on this class165     * and superclasses before any of the previous steps; all AfterClass methods are166     * always executed: exceptions thrown by previous steps are combined, if167     * necessary, with exceptions from AfterClass methods into a168     * {@link org.junit.runners.model.MultipleFailureException}.169     * </ul>170     *171     * @return {@code Statement}172     */173    protected Statement classBlock(final RunNotifier notifier) {174        Statement statement = childrenInvoker(notifier);175        statement = withBeforeClasses(statement);176        statement = withAfterClasses(statement);177        statement = withClassRules(statement);178        return statement;179    }180    /**181     * Returns a {@link org.junit.runners.model.Statement}: run all non-overridden {@code @BeforeClass} methods on this class182     * and superclasses before executing {@code statement}; if any throws an183     * Exception, stop execution and pass the exception on.184     */185    protected Statement withBeforeClasses(Statement statement) {186        List<FrameworkMethod> befores = getTestClass()187                .getAnnotatedMethods(BeforeClass.class);188        return befores.isEmpty() ? statement :189                new RunBefores(statement, befores, null);190    }191    /**192     * Returns a {@link org.junit.runners.model.Statement}: run all non-overridden {@code @AfterClass} methods on this class193     * and superclasses before executing {@code statement}; all AfterClass methods are194     * always executed: exceptions thrown by previous steps are combined, if195     * necessary, with exceptions from AfterClass methods into a196     * {@link org.junit.runners.model.MultipleFailureException}.197     */198    protected Statement withAfterClasses(Statement statement) {199        List<FrameworkMethod> afters = getTestClass()200                .getAnnotatedMethods(AfterClass.class);201        return afters.isEmpty() ? statement :202                new RunAfters(statement, afters, null);203    }204    /**205     * Returns a {@link org.junit.runners.model.Statement}: apply all206     * static fields assignable to {@link org.junit.rules.TestRule}207     * annotated with {@link org.junit.ClassRule}.208     *209     * @param statement the base statement210     * @return a RunRules statement if any class-level {@link org.junit.Rule}s are211     *         found, or the base statement212     */213    private Statement withClassRules(Statement statement) {214        List<TestRule> classRules = classRules();215        return classRules.isEmpty() ? statement :216                new RunRules(statement, classRules, getDescription());217    }218    /**219     * @return the {@code ClassRule}s that can transform the block that runs220     *         each method in the tested class.221     */222    protected List<TestRule> classRules() {223        List<TestRule> result = getTestClass().getAnnotatedMethodValues(null, ClassRule.class, TestRule.class);224        result.addAll(getTestClass().getAnnotatedFieldValues(null, ClassRule.class, TestRule.class));225        return result;226    }227    /**228     * Returns a {@link org.junit.runners.model.Statement}: Call {@link #runChild(org.junit.runners.model.FrameworkMethod, org.junit.runner.notification.RunNotifier)}229     * on each object returned by {@link #getChildren()} (subject to any imposed230     * filter and sort)231     */232    protected Statement childrenInvoker(final RunNotifier notifier) {233        return new Statement() {234            @Override235            public void evaluate() {236                runChildren(notifier);237            }238        };239    }240    private void runChildren(final RunNotifier notifier) {241        for (final FrameworkMethod each : getFilteredChildren()) {242            fScheduler.schedule(new Runnable() {243                public void run() {244                    LoadTimeWeavableTestRunner.this.runChild(each, notifier);245                }246            });247        }248        fScheduler.finished();249    }250    /**251     * Returns a name used to describe this Runner252     */253    protected String getName() {254        return getOriginalTestClass().getName();255    }256    /**257     * Returns a {@link org.junit.runners.model.TestClass} object wrapping the class to be executed.258     */259    public final TestClass getTestClass() {260        if (fTestClass == null) {261            throw new IllegalStateException("Attempted to access test class but it has not yet been initialized!");262        }263        return fTestClass;264    }265    /**266     * Returns the original test class that was passed to this test runner.267     */268    public final TestClass getOriginalTestClass() {269        return originalTestClass;270    }271    /**272     * Runs a {@link org.junit.runners.model.Statement} that represents a leaf (aka atomic) test.273     */274    protected final void runLeaf(Statement statement, Description description,275            RunNotifier notifier) {276        EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);277        eachNotifier.fireTestStarted();278        try {279            statement.evaluate();280        } catch (AssumptionViolatedException e) {281            eachNotifier.addFailedAssumption(e);282        } catch (Throwable e) {283            eachNotifier.addFailure(e);284        } finally {285            eachNotifier.fireTestFinished();286        }287    }288    /**289     * @return the annotations that should be attached to this runner's290     *         description.291     */292    protected Annotation[] getRunnerAnnotations() {293        return getOriginalTestClass().getAnnotations();294    }295    //296    // Implementation of Runner297    //298    @Override299    public Description getDescription() {300        Description description = Description.createSuiteDescription(getName(),301                getRunnerAnnotations());302        for (FrameworkMethod child : getOriginalFilteredChildren()) {303            description.addChild(describeOriginalChild(child));304        }305        return description;306    }307    @Override308    public void run(final RunNotifier notifier) {309        ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();310        Thread.currentThread().setContextClassLoader(customLoader);311        try {312            if (runBootstrapTest(notifier, getOriginalTestClass())) {313                this.fTestClass = getCustomTestClass(getOriginalTestClass().getJavaClass(), customLoader);314                EachTestNotifier testNotifier = new EachTestNotifier(notifier, getDescription());315                try {316                    Statement statement = classBlock(notifier);317                    statement.evaluate();318                } catch (AssumptionViolatedException e) {319                    testNotifier.fireTestIgnored();320                } catch (StoppedByUserException e) {321                    throw e;322                } catch (Throwable e) {323                    testNotifier.addFailure(e);324                }325            }326        } finally {327            Thread.currentThread().setContextClassLoader(currentContextClassLoader);328        }329    }330    protected boolean runBootstrapTest(RunNotifier notifier, TestClass testClass) {331        if (!runningBootstrapTest.get().booleanValue()) {332            runningBootstrapTest.set(Boolean.TRUE);333            try {334                BootstrapTest bootstrapTest = getBootstrapTestAnnotation(testClass.getJavaClass());335                if (bootstrapTest != null) {336                    Result result = JUnitCore.runClasses(bootstrapTest.value());337                    List<Failure> failures = result.getFailures();338                    for (Failure failure : failures) {339                        notifier.fireTestFailure(failure);340                    }341                    return result.getFailureCount() == 0;342                } else {343                    throw new IllegalStateException("LoadTimeWeavableTestRunner, must be coupled with an @BootstrapTest annotation to define the bootstrap test to execute.");344                }345            } finally {346                runningBootstrapTest.set(Boolean.FALSE);347            }348        }349        return true;350    }351    private BootstrapTest getBootstrapTestAnnotation(Class<?> testClass) {352        BootstrapTest bootstrapTest = testClass.getAnnotation(BootstrapTest.class);353        if (bootstrapTest != null) {354            return bootstrapTest;355        } else if (testClass.getSuperclass() != null) {356            return getBootstrapTestAnnotation(testClass.getSuperclass());357        } else {358            return null;359        }360    }361    //362    // Implementation of Filterable and Sortable363    //364    public void filter(Filter filter) throws NoTestsRemainException {365        for (Iterator<FrameworkMethod> iter = getOriginalFilteredChildren().iterator(); iter.hasNext(); ) {366            FrameworkMethod each = iter.next();367            if (shouldRun(filter, each)) {368                try {369                    filter.apply(each);370                } catch (NoTestsRemainException e) {371                    iter.remove();372                }373            } else {374                iter.remove();375            }376        }377        if (getOriginalFilteredChildren().isEmpty()) {378            throw new NoTestsRemainException();379        }380    }381    public void sort(Sorter sorter) {382        fSorter = sorter;383        for (FrameworkMethod each : getOriginalFilteredChildren()) {384            sortChild(each);385        }386        Collections.sort(getOriginalFilteredChildren(), comparator());387    }388    //389    // Private implementation390    //391    private void validate() throws InitializationError {392        List<Throwable> errors = new ArrayList<Throwable>();393        collectInitializationErrors(errors);394        if (!errors.isEmpty()) {395            throw new InitializationError(errors);396        }397    }398    private List<FrameworkMethod> getOriginalFilteredChildren() {399        if (originalFilteredChildren == null) {400            originalFilteredChildren = new ArrayList<FrameworkMethod>(getOriginalChildren());401        }402        return originalFilteredChildren;403    }404    private List<FrameworkMethod> getFilteredChildren() {405        if (getOriginalFilteredChildren() == null) {406            throw new IllegalStateException("Attempted to get filtered children before original filtered children were initialized.");407        }408        if (filteredChildren == null) {409            filteredChildren = new ArrayList<FrameworkMethod>();410            List<FrameworkMethod> testMethods = computeTestMethods();411            for (FrameworkMethod originalMethod : getOriginalFilteredChildren()) {412                for (FrameworkMethod testMethod : testMethods) {413                    if (originalMethod.isShadowedBy(testMethod)) {414                        filteredChildren.add(testMethod);415                    }416                }417            }418        }419        return filteredChildren;420    }421    private void sortChild(FrameworkMethod child) {422        fSorter.apply(child);423    }424    private boolean shouldRun(Filter filter, FrameworkMethod each) {425        return filter.shouldRun(describeOriginalChild(each));426    }427    private Comparator<? super FrameworkMethod> comparator() {428        return new Comparator<FrameworkMethod>() {429            public int compare(FrameworkMethod o1, FrameworkMethod o2) {430                return fSorter.compare(describeChild(o1), describeChild(o2));431            }432        };433    }434    //435    // Implementation of ParentRunner436    //437    /**438     * Runs the test corresponding to {@code child}, which can be assumed to be439     * an element of the list returned by {@link #getChildren()}.440     * Subclasses are responsible for making sure that relevant test events are441     * reported through {@code notifier}442     */443    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {444        this.currentMethod = method.getMethod();445        try {446            Description description = describeChild(method);447            if (method.getAnnotation(Ignore.class) != null) {448                notifier.fireTestIgnored(description);449            } else {450                runLeaf(methodBlock(method), description, notifier);451            }452        } finally {453            this.currentMethod = null;454        }455    }456    /**457     * Returns a {@link org.junit.runner.Description} for {@code child}, which can be assumed to458     * be an element of the list returned by {@link #getChildren()}459     */460    protected Description describeChild(FrameworkMethod method) {461        return Description.createTestDescription(getTestClass().getJavaClass(),462                testName(method), method.getAnnotations());463    }464    protected Description describeOriginalChild(FrameworkMethod method) {465        return Description.createTestDescription(getOriginalTestClass().getJavaClass(),466                testName(method), method.getAnnotations());467    }468    /**469     * Returns a list of objects that define the children of this Runner.470     */471    protected List<FrameworkMethod> getChildren() {472        return computeTestMethods();473    }474    protected List<FrameworkMethod> getOriginalChildren() {475        return computeOriginalTestMethods();476    }477    //478    // Override in subclasses479    //480    /**481     * Returns the methods that run tests. Default implementation returns all482     * methods annotated with {@code @Test} on this class and superclasses that483     * are not overridden.484     */485    protected List<FrameworkMethod> computeTestMethods() {486        return getTestClass().getAnnotatedMethods(Test.class);487    }488    protected List<FrameworkMethod> computeOriginalTestMethods() {489        return getOriginalTestClass().getAnnotatedMethods(Test.class);490    }491    /**492     * Adds to {@code errors} a throwable for each problem noted with the test class (available from {@link #getTestClass()}).493     * Default implementation adds an error for each method annotated with494     * {@code @BeforeClass} or {@code @AfterClass} that is not495     * {@code public static void} with no arguments.496     */497    protected void collectInitializationErrors(List<Throwable> errors) {498        validatePublicVoidNoArgMethods(BeforeClass.class, true, errors);499        validatePublicVoidNoArgMethods(AfterClass.class, true, errors);500        validateClassRules(errors);501        validateNoNonStaticInnerClass(errors);502        validateConstructor(errors);503        validateInstanceMethods(errors);504        validateFields(errors);505        validateMethods(errors);506    }507    protected void validateNoNonStaticInnerClass(List<Throwable> errors) {508        if (getOriginalTestClass().isANonStaticInnerClass()) {509            String gripe = "The inner class " + getOriginalTestClass().getName()510                    + " is not static.";511            errors.add(new Exception(gripe));512        }513    }514    /**515     * Adds to {@code errors} if the test class has more than one constructor,516     * or if the constructor takes parameters. Override if a subclass requires517     * different validation rules.518     */519    protected void validateConstructor(List<Throwable> errors) {520        validateOnlyOneConstructor(errors);521        validateZeroArgConstructor(errors);522    }523    /**524     * Adds to {@code errors} if the test class has more than one constructor525     * (do not override)526     */527    protected void validateOnlyOneConstructor(List<Throwable> errors) {528        if (!hasOneConstructor()) {529            String gripe = "Test class should have exactly one public constructor";530            errors.add(new Exception(gripe));531        }532    }533    /**534     * Adds to {@code errors} if the test class's single constructor takes535     * parameters (do not override)536     */537    protected void validateZeroArgConstructor(List<Throwable> errors) {538        if (!getOriginalTestClass().isANonStaticInnerClass()539                && hasOneConstructor()540                && (getOriginalTestClass().getOnlyConstructor().getParameterTypes().length != 0)) {541            String gripe = "Test class should have exactly one public zero-argument constructor";542            errors.add(new Exception(gripe));543        }544    }545    private boolean hasOneConstructor() {546        return getOriginalTestClass().getJavaClass().getConstructors().length == 1;547    }548    /**549     * Adds to {@code errors} for each method annotated with {@code @Test},550     * {@code @Before}, or {@code @After} that is not a public, void instance551     * method with no arguments.552     *553     * @deprecated unused API, will go away in future version554     */555    @Deprecated556    protected void validateInstanceMethods(List<Throwable> errors) {557        validatePublicVoidNoArgMethods(After.class, false, errors);558        validatePublicVoidNoArgMethods(Before.class, false, errors);559        validateTestMethods(errors);560        if (computeOriginalTestMethods().size() == 0) {561            errors.add(new Exception("No runnable methods"));562        }563    }564    protected void validateFields(List<Throwable> errors) {565        RULE_VALIDATOR.validate(getOriginalTestClass(), errors);566    }567    private void validateMethods(List<Throwable> errors) {568        RULE_METHOD_VALIDATOR.validate(getOriginalTestClass(), errors);569    }570    /**571     * Adds to {@code errors} for each method annotated with {@code @Test}that572     * is not a public, void instance method with no arguments.573     */574    protected void validateTestMethods(List<Throwable> errors) {575        validatePublicVoidNoArgMethods(Test.class, false, errors);576    }577    /**578     * Returns a new fixture for running a test. Default implementation executes579     * the test class's no-argument constructor (validation should have ensured580     * one exists).581     */582    protected Object createTest() throws Exception {583        Object test = getTestClass().getOnlyConstructor().newInstance();584        setTestName(test, currentMethod);585        setTestMethod(test, currentMethod);586        return test;587    }588    /**589     * Sets the {@link java.lang.reflect.Method} on the test case if it is {@link org.kuali.rice.test.MethodAware}590     * @param method the current method to be run591     * @param test the test instance592     */593    protected void setTestMethod(Object test, Method method) throws Exception {594        Class<?> methodAwareClass = Class.forName(MethodAware.class.getName(), true, getCustomClassLoader());595        if (methodAwareClass.isInstance(test)) {596            Method setTestMethod = methodAwareClass.getMethod("setTestMethod", Method.class);597            setTestMethod.invoke(test, method);598        }599    }600    protected void setTestName(final Object test, final Method testMethod) throws Exception {601        String name = testMethod == null ? "" : testMethod.getName();602        final Method setNameMethod = MethodUtils.getAccessibleMethod(test.getClass(), "setName",603                new Class[]{String.class});604        if (setNameMethod != null) {605            setNameMethod.invoke(test, name);606        }607    }608    /**609     * Returns the name that describes {@code method} for {@link org.junit.runner.Description}s.610     * Default implementation is the method's name611     */612    protected String testName(FrameworkMethod method) {613        return method.getName();614    }615    /**616     * Returns a Statement that, when executed, either returns normally if617     * {@code method} passes, or throws an exception if {@code method} fails.618     *619     * Here is an outline of the default implementation:620     *621     * <ul>622     * <li>Invoke {@code method} on the result of {@code createTest()}, and623     * throw any exceptions thrown by either operation.624     * <li>HOWEVER, if {@code method}'s {@code @Test} annotation has the {@code625     * expecting} attribute, return normally only if the previous step threw an626     * exception of the correct type, and throw an exception otherwise.627     * <li>HOWEVER, if {@code method}'s {@code @Test} annotation has the {@code...Source:PinpointPluginTestRunner.java  
...55        this.context = context;56        this.testCase = testCase;57    }58    @Override59    protected String getName() {60        return String.format("[%s]", testCase.getTestId());61    }62    @Override63    protected String testName(final FrameworkMethod method) {64        return String.format("%s[%s]", method.getName(), testCase.getTestId());65    }66    @Override67    protected Statement classBlock(RunNotifier notifier) {68        return new PinpointPluginTestStatement(this, notifier, context, testCase);69    }70    @Override71    public void filter(Filter filter) throws NoTestsRemainException {72        synchronized (childrenLock) {73            List<FrameworkMethod> children = new ArrayList<FrameworkMethod>(getFilteredChildren());74            for (Iterator<FrameworkMethod> iter = children.iterator(); iter.hasNext(); ) {75                FrameworkMethod each = iter.next();76                if (shouldRun(filter, each)) {77                    try {78                        filter.apply(each);79                    } catch (NoTestsRemainException e) {80                        iter.remove();81                    }82                } else {83                    iter.remove();84                }85            }86            filteredChildren = Collections.unmodifiableCollection(children);87            if (filteredChildren.isEmpty()) {88                throw new NoTestsRemainException();89            }90        }91    }92    private Collection<FrameworkMethod> getFilteredChildren() {93        if (filteredChildren == null) {94            synchronized (childrenLock) {95                if (filteredChildren == null) {96                    filteredChildren = Collections.unmodifiableCollection(getChildren());97                }98            }99        }100        return filteredChildren;101    }102    public void sort(Sorter sorter) {103        synchronized (childrenLock) {104            for (FrameworkMethod each : getFilteredChildren()) {105                sorter.apply(each);106            }107            List<FrameworkMethod> sortedChildren = new ArrayList<FrameworkMethod>(getFilteredChildren());108            Collections.sort(sortedChildren, comparator(sorter));109            filteredChildren = Collections.unmodifiableCollection(sortedChildren);110        }111    }112    private Comparator<? super FrameworkMethod> comparator(final Sorter sorter) {113        return new Comparator<FrameworkMethod>() {114            public int compare(FrameworkMethod o1, FrameworkMethod o2) {115                return sorter.compare(describeChild(o1), describeChild(o2));116            }117        };118    }119    private void runChildren(final RunNotifier notifier) {120        final RunnerScheduler currentScheduler = scheduler;121        try {122            for (final FrameworkMethod each : getFilteredChildren()) {123                currentScheduler.schedule(new Runnable() {124                    public void run() {125                        runChild(each, notifier);126                    }127                });128            }129        } finally {130            currentScheduler.finished();131        }132    }133    protected Statement childrenInvoker(final RunNotifier notifier) {134        return new Statement() {135            @Override136            public void evaluate() {137                runChildren(notifier);138            }139        };140    }141    boolean isAvaiable(Filter filter) {142        synchronized (childrenLock) {143            List<FrameworkMethod> children = new ArrayList<FrameworkMethod>(getFilteredChildren());144            for (FrameworkMethod method : children) {145                if (shouldRun(filter, method)) {146                    return true;147                }148            }149        }150        return false;151    }152    private boolean shouldRun(Filter filter, FrameworkMethod each) {153        if (filter.shouldRun(describeChild(each))) {154            return true;155        }156        String testDescribe = PinpointPluginTestUtils.getTestDescribe(each.getMethod());157        return testDescribe.equals(filter.describe());158    }159    @Override160    public Description getDescription() {161        Description description = Description.createSuiteDescription(getName(), getRunnerAnnotations());162        for (FrameworkMethod child : getFilteredChildren()) {163            description.addChild(describeChild(child));164        }165        return description;166    }167}...Source:FrameworkMethod.java  
...26            }27        }.run();28    }29    @Override // org.junit.runners.model.FrameworkMember30    public String getName() {31        return this.method.getName();32    }33    public void validatePublicVoidNoArg(boolean isStatic, List<Throwable> errors) {34        validatePublicVoid(isStatic, errors);35        if (this.method.getParameterTypes().length != 0) {36            errors.add(new Exception("Method " + this.method.getName() + " should have no parameters"));37        }38    }39    public void validatePublicVoid(boolean isStatic, List<Throwable> errors) {40        if (isStatic() != isStatic) {41            String state = isStatic ? "should" : "should not";42            errors.add(new Exception("Method " + this.method.getName() + "() " + state + " be static"));43        }44        if (!isPublic()) {45            errors.add(new Exception("Method " + this.method.getName() + "() should be public"));46        }47        if (this.method.getReturnType() != Void.TYPE) {48            errors.add(new Exception("Method " + this.method.getName() + "() should be void"));49        }50    }51    /* access modifiers changed from: protected */52    @Override // org.junit.runners.model.FrameworkMember53    public int getModifiers() {54        return this.method.getModifiers();55    }56    public Class<?> getReturnType() {57        return this.method.getReturnType();58    }59    @Override // org.junit.runners.model.FrameworkMember60    public Class<?> getType() {61        return getReturnType();62    }63    @Override // org.junit.runners.model.FrameworkMember64    public Class<?> getDeclaringClass() {65        return this.method.getDeclaringClass();66    }67    public void validateNoTypeParametersOnArgs(List<Throwable> errors) {68        new NoGenericTypeParametersValidator(this.method).validate(errors);69    }70    public boolean isShadowedBy(FrameworkMethod other) {71        if (!(other.getName().equals(getName()) && other.getParameterTypes().length == getParameterTypes().length)) {72            return false;73        }74        for (int i = 0; i < other.getParameterTypes().length; i++) {75            if (!other.getParameterTypes()[i].equals(getParameterTypes()[i])) {76                return false;77            }78        }79        return true;80    }81    public boolean equals(Object obj) {82        if (!FrameworkMethod.class.isInstance(obj)) {83            return false;84        }85        return ((FrameworkMethod) obj).method.equals(this.method);...Source:FunctionalJavaFXRunner.java  
...54        List<FrameworkMethod> methods = new ArrayList<>(super.computeTestMethods());55        Collections.sort(methods, new Comparator<FrameworkMethod>() {56            @Override57            public int compare(FrameworkMethod a, FrameworkMethod b) {58                return a.getName().compareTo(b.getName());59            }60        });61        return unmodifiableList(methods);62    }63    @Override64    protected void runChild(FrameworkMethod method, RunNotifier notifier) {65        try {66            resolveTestFXClassRule(method);67            notifier.addFirstListener(new FailureListener(testFXClassRule));68        } catch (Exception e) {69            notifier.fireTestFailure(new Failure(createTestDescription(method.getDeclaringClass(), method.getName()), e));70        }71        super.runChild(method, notifier);72    }73    @Override74    protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) {75        try {76            resolveTestFXClassRule(method);77            testFXClassRule.injectMembers(target);78        } catch (Exception e) {79            return new Fail(e);80        }81        return super.withBefores(method, target, statement);82    }83    @Override84    protected boolean isIgnored(FrameworkMethod child) {85        if (super.isIgnored(child)) {86            return true;87        }88        try {89            resolveTestFXClassRule(child);90            return testFXClassRule.hasFailures();91        } catch (Exception e) {92            return true;93        }94    }95    private void resolveTestFXClassRule(FrameworkMethod child) throws NoSuchFieldException, IllegalAccessException {96        if (testFXClassRule == null) {97            for (Field field : child.getDeclaringClass().getFields()) {98                if (BasiliskTestFXClassRule.class.isAssignableFrom(field.getType())) {99                    testFXClassRule = (BasiliskTestFXClassRule) field.get(null);100                    return;101                }102            }103            throw new IllegalStateException("Class " + child.getDeclaringClass().getName() + " does not define a field of type " + BasiliskTestFXClassRule.class.getName());104        }105    }106}...Source:TestCaseWithRules.java  
...56            public void evaluate() throws Throwable {57                superRunBare();58            }59        };60        final String name = getName();61        FrameworkMethod frameworkMethod;62        try {63            Method method = getClass().getMethod(name, (Class[]) null);64            frameworkMethod = new FrameworkMethod(method);65        } catch (NoSuchMethodException e) {66            frameworkMethod = new FrameworkMethod(null) {67                @Override68                public String getName() {69                    return name;70                }71                @Override72                public Annotation[] getAnnotations() {73                    return new Annotation[0];74                }75                @Override76                public <T extends Annotation> T getAnnotation(Class<T> annotationType) {77                    return null;78                }79            };80        }81        Description description =82                Description.createTestDescription(getClass(), frameworkMethod.getName(),83                        frameworkMethod.getAnnotations());84        List<Object> rules = testClass.getAnnotatedFieldValues(this, Rule.class, Object.class);85        for (Object rule : rules) {86            if (rule instanceof TestRule) {87                statement = ((TestRule) rule).apply(statement, description);88            } else {89                statement = ((MethodRule) rule).apply(statement, frameworkMethod, this);90            }91        }92        statement.evaluate();93    }94    private void superRunBare() throws Throwable {95        super.runBare();96    }...Source:Testfetcher.java  
...26	}27      URLClassLoader cl = URLClassLoader.newInstance(urls);28      while (e.hasMoreElements()) {29          JarEntry je = (JarEntry) e.nextElement();30          if(je.isDirectory() || !je.getName().endsWith(".class") || je.getName().contains("$")){31              continue;32          }33          // -6 because of .class34          String className = je.getName().substring(0,je.getName().length()-6);35          className = className.replace('/', '.');36          try {37			Class c = cl.loadClass(className);38			System.out.println(c.getName());39			 TestClass testClass = new TestClass(c);40	    	  List<FrameworkMethod> testList = testClass.getAnnotatedMethods(org.junit.Test.class);41	    	  List<FrameworkMethod> BeforeList = testClass.getAnnotatedMethods(org.junit.Before.class);42	    	  List<FrameworkMethod> AfterList = testClass.getAnnotatedMethods(org.junit.After.class);43	    	  44	    	  for (FrameworkMethod frameworkMethod : testList) {45	    		  String name = testClass.getName();46	    	      String method = frameworkMethod.getName();47	    	      System.out.println(name + "\t" + method + "\t");48	    	      RunNotifier notifier = new RunNotifier();49	    	      RunListener listener = new CustomListener();50	    	      notifier.addListener(listener);51	    	      new CustomRunner(c).runMethod(method, notifier);52	    	      System.out.println(notifier.toString());53			}54		} catch (ClassNotFoundException e1) {55			// TODO Auto-generated catch block56			e1.printStackTrace();57		} 58          catch (Exception e1) {59			// TODO Auto-generated catch block60			e1.printStackTrace();...Source:WebMvcTestPrintDefaultRunner.java  
...34	protected Statement methodBlock(FrameworkMethod frameworkMethod) {35		Statement statement = super.methodBlock(frameworkMethod);36		statement = new AlwaysPassStatement(statement);37		OutputCapture outputCapture = new OutputCapture();38		if (frameworkMethod.getName().equals("shouldPrint")) {39			outputCapture.expect(containsString("HTTP Method"));40		}41		else if (frameworkMethod.getName().equals("shouldNotPrint")) {42			outputCapture.expect(not(containsString("HTTP Method")));43		}44		else {45			throw new IllegalStateException("Unexpected test method");46		}47		System.err.println(frameworkMethod.getName());48		return outputCapture.apply(statement, null);49	}50	private static class AlwaysPassStatement extends Statement {51		private final Statement delegate;52		AlwaysPassStatement(Statement delegate) {53			this.delegate = delegate;54		}55		@Override56		public void evaluate() throws Throwable {57			try {58				this.delegate.evaluate();59			}60			catch (AssertionError ex) {61			}...Source:RandomizedRepeatRunner.java  
...41			for(int i = 0; i < numTimes; i++) {42				final int ii = i;43				methods.add(new FrameworkMethod(m.getMethod()) {44					@Override45					public String getName() {46						return super.getName() + " (" + ii + ")";47					}48					49				});50			}51		}52		Collections.shuffle(methods);53		return methods;54	}55  56}...getName
Using AI Code Generation
1import org.junit.runners.model.FrameworkMethod;2public class FrameworkMethodExample {3    public static void main(String[] args) throws Exception {4        FrameworkMethod method = new FrameworkMethod(FrameworkMethodExample.class.getMethod("test", null));5        System.out.println(method.getName());6    }7    public void test() {8    }9}getName
Using AI Code Generation
1System.out.println("Test method: " + getName() + " has been executed");2System.out.println("Test method: " + getName() + " annotation: " + getAnnotation(Test.class));3System.out.println("Test method: " + getName() + " annotations: " + Arrays.toString(getAnnotations()));4System.out.println("Test method: " + getName() + " parameter types: " + Arrays.toString(getParameterTypes()));5System.out.println("Test method: " + getName() + " return type: " + getReturnType());6System.out.println("Test method: " + getName() + " declaring class: " + getDeclaringClass());7System.out.println("Test method: " + getName() + " modifiers: " + getModifiers());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!!
