Best junit code snippet using org.junit.runners.ParentRunner.getChildren
Source:ParentRunner.java  
...71    //72    /**73     * Returns a list of objects that define the children of this Runner.74     */75    protected abstract List<T> getChildren();76    /**77     * Returns a {@link Description} for {@code child}, which can be assumed to78     * be an element of the list returned by {@link ParentRunner#getChildren()}79     */80    protected abstract Description describeChild(T child);81    /**82     * Runs the test corresponding to {@code child}, which can be assumed to be83     * an element of the list returned by {@link ParentRunner#getChildren()}.84     * Subclasses are responsible for making sure that relevant test events are85     * reported through {@code notifier}86     */87    protected abstract void runChild(T child, RunNotifier notifier);88    //89    // May be overridden90    //91    /**92     * Adds to {@code errors} a throwable for each problem noted with the test class (available from {@link #getTestClass()}).93     * Default implementation adds an error for each method annotated with94     * {@code @BeforeClass} or {@code @AfterClass} that is not95     * {@code public static void} with no arguments.96     */97    protected void collectInitializationErrors(List<Throwable> errors) {98        validatePublicVoidNoArgMethods(BeforeClass.class, true, errors);99        validatePublicVoidNoArgMethods(AfterClass.class, true, errors);100        validateClassRules(errors);101    }102    /**103     * Adds to {@code errors} if any method in this class is annotated with104     * {@code annotation}, but:105     * <ul>106     * <li>is not public, or107     * <li>takes parameters, or108     * <li>returns something other than void, or109     * <li>is static (given {@code isStatic is false}), or110     * <li>is not static (given {@code isStatic is true}).111     */112    protected void validatePublicVoidNoArgMethods(Class<? extends Annotation> annotation,113            boolean isStatic, List<Throwable> errors) {114        List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(annotation);115        for (FrameworkMethod eachTestMethod : methods) {116            eachTestMethod.validatePublicVoidNoArg(isStatic, errors);117        }118    }119    private void validateClassRules(List<Throwable> errors) {120        CLASS_RULE_VALIDATOR.validate(getTestClass(), errors);121        CLASS_RULE_METHOD_VALIDATOR.validate(getTestClass(), errors);122    }123    /**124     * Constructs a {@code Statement} to run all of the tests in the test class. Override to add pre-/post-processing.125     * Here is an outline of the implementation:126     * <ul>127     * <li>Call {@link #runChild(Object, RunNotifier)} on each object returned by {@link #getChildren()} (subject to any imposed filter and sort).</li>128     * <li>ALWAYS run all non-overridden {@code @BeforeClass} methods on this class129     * and superclasses before the previous step; if any throws an130     * Exception, stop execution and pass the exception on.131     * <li>ALWAYS run all non-overridden {@code @AfterClass} methods on this class132     * and superclasses before any of the previous steps; all AfterClass methods are133     * always executed: exceptions thrown by previous steps are combined, if134     * necessary, with exceptions from AfterClass methods into a135     * {@link MultipleFailureException}.136     * </ul>137     *138     * @return {@code Statement}139     */140    protected Statement classBlock(final RunNotifier notifier) {141        Statement statement = childrenInvoker(notifier);142        statement = withBeforeClasses(statement);143        statement = withAfterClasses(statement);144        statement = withClassRules(statement);145        return statement;146    }147    /**148     * Returns a {@link Statement}: run all non-overridden {@code @BeforeClass} methods on this class149     * and superclasses before executing {@code statement}; if any throws an150     * Exception, stop execution and pass the exception on.151     */152    protected Statement withBeforeClasses(Statement statement) {153        List<FrameworkMethod> befores = fTestClass154                .getAnnotatedMethods(BeforeClass.class);155        return befores.isEmpty() ? statement :156                new RunBefores(statement, befores, null);157    }158    /**159     * Returns a {@link Statement}: run all non-overridden {@code @AfterClass} methods on this class160     * and superclasses before executing {@code statement}; all AfterClass methods are161     * always executed: exceptions thrown by previous steps are combined, if162     * necessary, with exceptions from AfterClass methods into a163     * {@link MultipleFailureException}.164     */165    protected Statement withAfterClasses(Statement statement) {166        List<FrameworkMethod> afters = fTestClass167                .getAnnotatedMethods(AfterClass.class);168        return afters.isEmpty() ? statement :169                new RunAfters(statement, afters, null);170    }171    /**172     * Returns a {@link Statement}: apply all173     * static fields assignable to {@link TestRule}174     * annotated with {@link ClassRule}.175     *176     * @param statement the base statement177     * @return a RunRules statement if any class-level {@link Rule}s are178     *         found, or the base statement179     */180    private Statement withClassRules(Statement statement) {181        List<TestRule> classRules = classRules();182        return classRules.isEmpty() ? statement :183                new RunRules(statement, classRules, getDescription());184    }185    /**186     * @return the {@code ClassRule}s that can transform the block that runs187     *         each method in the tested class.188     */189    protected List<TestRule> classRules() {190        List<TestRule> result = fTestClass.getAnnotatedMethodValues(null, ClassRule.class, TestRule.class);191        result.addAll(fTestClass.getAnnotatedFieldValues(null, ClassRule.class, TestRule.class));192        return result;193    }194    /**195     * Returns a {@link Statement}: Call {@link #runChild(Object, RunNotifier)}196     * on each object returned by {@link #getChildren()} (subject to any imposed197     * filter and sort)198     */199    protected Statement childrenInvoker(final RunNotifier notifier) {200        return new Statement() {201            @Override202            public void evaluate() {203                runChildren(notifier);204            }205        };206    }207    private void runChildren(final RunNotifier notifier) {208        for (final T each : getFilteredChildren()) {209            fScheduler.schedule(new Runnable() {210                public void run() {211                    ParentRunner.this.runChild(each, notifier);212                }213            });214        }215        fScheduler.finished();216    }217    /**218     * Returns a name used to describe this Runner219     */220    protected String getName() {221        return fTestClass.getName();222    }223    //224    // Available for subclasses225    //226    /**227     * Returns a {@link TestClass} object wrapping the class to be executed.228     */229    public final TestClass getTestClass() {230        return fTestClass;231    }232    /**233     * Runs a {@link Statement} that represents a leaf (aka atomic) test.234     */235    protected final void runLeaf(Statement statement, Description description,236            RunNotifier notifier) {237        EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);238        eachNotifier.fireTestStarted();239        try {240            statement.evaluate();241        } catch (AssumptionViolatedException e) {242            eachNotifier.addFailedAssumption(e);243        } catch (Throwable e) {244            eachNotifier.addFailure(e);245        } finally {246            eachNotifier.fireTestFinished();247        }248    }249    /**250     * @return the annotations that should be attached to this runner's251     *         description.252     */253    protected Annotation[] getRunnerAnnotations() {254        return fTestClass.getAnnotations();255    }256    //257    // Implementation of Runner258    //259    @Override260    public Description getDescription() {261        Description description = Description.createSuiteDescription(getName(),262                getRunnerAnnotations());263        for (T child : getFilteredChildren()) {264            description.addChild(describeChild(child));265        }266        return description;267    }268    @Override269    public void run(final RunNotifier notifier) {270        EachTestNotifier testNotifier = new EachTestNotifier(notifier,271                getDescription());272        try {273            Statement statement = classBlock(notifier);274            statement.evaluate();275        } catch (AssumptionViolatedException e) {276            testNotifier.fireTestIgnored();277        } catch (StoppedByUserException e) {278            throw e;279        } catch (Throwable e) {280            testNotifier.addFailure(e);281        }282    }283    //284    // Implementation of Filterable and Sortable285    //286    public void filter(Filter filter) throws NoTestsRemainException {287        for (Iterator<T> iter = getFilteredChildren().iterator(); iter.hasNext(); ) {288            T each = iter.next();289            if (shouldRun(filter, each)) {290                try {291                    filter.apply(each);292                } catch (NoTestsRemainException e) {293                    iter.remove();294                }295            } else {296                iter.remove();297            }298        }299        if (getFilteredChildren().isEmpty()) {300            throw new NoTestsRemainException();301        }302    }303    public void sort(Sorter sorter) {304        fSorter = sorter;305        for (T each : getFilteredChildren()) {306            sortChild(each);307        }308        Collections.sort(getFilteredChildren(), comparator());309    }310    //311    // Private implementation312    //313    private void validate() throws InitializationError {314        List<Throwable> errors = new ArrayList<Throwable>();315        collectInitializationErrors(errors);316        if (!errors.isEmpty()) {317            throw new InitializationError(errors);318        }319    }320    private List<T> getFilteredChildren() {321        if (fFilteredChildren == null) {322            fFilteredChildren = new ArrayList<T>(getChildren());323        }324        return fFilteredChildren;325    }326    private void sortChild(T child) {327        fSorter.apply(child);328    }329    private boolean shouldRun(Filter filter, T each) {330        return filter.shouldRun(describeChild(each));331    }332    private Comparator<? super T> comparator() {333        return new Comparator<T>() {334            public int compare(T o1, T o2) {335                return fSorter.compare(describeChild(o1), describeChild(o2));336            }...Source:PopupExample.java  
...71			public void handle(ActionEvent event) {72				popup.hide();73			}74		});75		root.getChildren().addAll(show, hide);76		primaryStage.setScene(new Scene(root));77		primaryStage.show();78	}79	protected Stage createPopup(Window owner) {80		final Stage popup = new Stage();81		popup.initOwner(owner);82		popup.initStyle(StageStyle.TRANSPARENT);83		popup.initModality(Modality.WINDOW_MODAL);84		VBox vBox = new VBox();85		vBox.setAlignment(Pos.CENTER);86		vBox.setSpacing(10);87		vBox.setPrefWidth(300);88		vBox.setPrefHeight(200);89		vBox.setMaxWidth(Double.MAX_VALUE);90		vBox.setMaxHeight(Double.MAX_VALUE);91		Label messageLabel = new Label("åºéå¦", new ImageView("org/vivus/javafx2/popup/fail.png"));92		vBox.getChildren().add(messageLabel);93//		Label showHideLabel = new Label("show/hide");94//		final TextArea stackTrace = new TextArea(STACK_TRACE);95//		stackTrace.setEditable(false);96//		stackTrace.setVisible(false);97//		showHideLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {98//			@Override99//			public void handle(MouseEvent arg0) {100//				stackTrace.setVisible(!stackTrace.isVisible());101//			}102//		});103//		vBox.getChildren().add(showHideLabel);104//		vBox.getChildren().add(stackTrace);105		TitledPane titledPane = new TitledPane();106		titledPane.setText("å¼å¸¸æ ");107		TextArea stackTrace = new TextArea(STACK_TRACE);108		stackTrace.setEditable(false);109		titledPane.setContent(stackTrace);110		titledPane.setExpanded(false);111		vBox.getChildren().add(titledPane);112		Button confirm = new Button("ç¡®ãå®");113		confirm.setOnAction(new EventHandler<ActionEvent>() {114			@Override115			public void handle(ActionEvent event) {116				popup.hide();117			}118		});119		vBox.getChildren().add(confirm);120		popup.setScene(new Scene(vBox));121		return popup;122	}123}Source:ParameterizedRunner.java  
...72	protected String getName() {73		return super.getName() + " " + configId;74	}75	/* (non-Javadoc)76	 * @see org.junit.runners.Parameterized#getChildren()77	 */78	@Override79	protected List<Runner> getChildren() {80		List<Runner> children = super.getChildren();81		for (Runner runner : children) {82			if (runner instanceof ParameterizedRequirementsRunner) {83				ParameterizedRequirementsRunner testRunner = (ParameterizedRequirementsRunner) runner;84				testRunner.setConfigId(configId);85				testRunner.setRequirements(requirements);86				testRunner.setRunListeners(runListeners);87				testRunner.setAfterTestExtensions(afterTestExtensions);88				testRunner.setBeforeTestExtensions(beforeTestExtensions);89				if (firstChildRunner == null){90					firstChildRunner = testRunner;91				}92			} else {93				return null;94			}...Source:FeatureRunner.java  
...33    @Override34    public Description getDescription() {35        if (description == null) {36            description = Description.createSuiteDescription(getName(), cucumberFeature.getGherkinFeature());37            for (ParentRunner child : getChildren()) {38                description.addChild(describeChild(child));39            }40        }41        return description;42    }43    @Override44    protected List<ParentRunner> getChildren() {45        return children;46    }47    @Override48    protected Description describeChild(ParentRunner child) {49        return child.getDescription();50    }51    @Override52    protected void runChild(ParentRunner child, RunNotifier notifier) {53        child.run(notifier);54    }55    @Override56    public void run(RunNotifier notifier) {57        jUnitReporter.uri(cucumberFeature.getPath());58        jUnitReporter.feature(cucumberFeature.getGherkinFeature());...Source:ForkJoinSuite.java  
...12public class ForkJoinSuite extends Suite {13  private static final Method METHOD_GET_CHILDREN;14  private final Runner runner;15  static {16    String methodName = "getChildren";17    Class<?> clazz = ParentRunner.class;18    try {19      METHOD_GET_CHILDREN = clazz.getDeclaredMethod(methodName);20    } catch (NoSuchMethodException e) {21      throw new IllegalStateException("no " + methodName + "() method on " + clazz, e);22    }23    METHOD_GET_CHILDREN.setAccessible(true);24  }25  public ForkJoinSuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {26    super(klass, Collections.<Runner>emptyList());27    ForkJoinParameters forkJoinParameters = getForkJoinParameters(klass);28    ForkJoinPool forkJoinPool = this.buildForkJoinPool(forkJoinParameters);29    RunnerBuilder runnerBuilder = this.getRunnerBuilder(forkJoinParameters);30    try {31      runner = runnerBuilder.runnerForClass(klass);32      recursivelySetScheduler(runner, forkJoinPool);33    } catch (Throwable e) {34      throw new InitializationError(e);35    }36  }37  @Override38  protected List<Runner> getChildren() {39    return Collections.singletonList(this.runner);40  }41  private static void recursivelySetScheduler(Runner runner, ForkJoinPool forkJoinPool) {42    if (runner instanceof ParentRunner) {43      ParentRunner<?> parentRunner = (ParentRunner<?>) runner;44      parentRunner.setScheduler(new ForkJoinRunnerScheduler(forkJoinPool));45      for (Object each : getChildren(parentRunner)) {46        if (each instanceof Runner) {47          Runner child = (Runner) each;48          recursivelySetScheduler(child, forkJoinPool);49        }50      }51    }52  }53  private static List<?> getChildren(Runner runner) {54    try {55      return (List<?>) METHOD_GET_CHILDREN.invoke(runner);56    } catch (ReflectiveOperationException e) {57      throw new RuntimeException("could not get children", e);58    }59  }60  private ForkJoinParameters getForkJoinParameters(Class<?> klass) throws InitializationError {61    return klass.getAnnotation(ForkJoinParameters.class);62  }63  private RunnerBuilder getRunnerBuilder(ForkJoinParameters parameter) throws InitializationError {64    if (parameter == null) {65      return new JUnit4Builder();66    }67    ...Source:ParentStatementRunner.java  
...47    protected String getName() {48        return name;49    }50    @Override51    protected List<DescribableStatement> getChildren() {52        return statements;53    }54    @Override55    protected Description describeChild(DescribableStatement child) {56        return child.getDescription();57    }58    @Override59    protected void runChild(final DescribableStatement child, RunNotifier notifier) {60        Description description = describeChild(child);61        Statement statement = child;62        statement = testRule.apply(statement, description);63        ParentRunnerHelper.abortingRunLeaf(statement, description, notifier);64    }65    /**...Source:NeodymiumCucumberWrapper.java  
...18        cucumber = new Cucumber(clazz);19    }20    // from Cucumber21    @Override22    protected List<ParentRunner<?>> getChildren()23    {24        return cucumber.getChildren();25    }26    @Override27    protected Description describeChild(ParentRunner<?> child)28    {29        return cucumber.describeChild(child);30    }31    @Override32    protected void runChild(ParentRunner<?> child, RunNotifier notifier)33    {34        cucumber.runChild(child, notifier);35    }36    @Override37    protected Statement childrenInvoker(RunNotifier notifier)38    {...Source:Pump.java  
...15    protected Cucumber newCucumberDelegate(Class<?> testClass) throws InitializationError {16        return new Cucumber(testClass);17    }18    @Override19    protected List<ParentRunner<?>> getChildren() {20        return cucumberDelegate.getChildren();21    }22    @Override23    protected Description describeChild(ParentRunner<?> child) {24        return cucumberDelegate.describeChild(child);25    }26    @Override27    protected void runChild(ParentRunner<?> child, RunNotifier notifier) {28        cucumberDelegate.runChild(child, notifier);29    }30    @Override31    protected Statement childrenInvoker(RunNotifier notifier) {32        return cucumberDelegate.childrenInvoker(notifier);33    }34}...getChildren
Using AI Code Generation
1import org.junit.runner.RunWith;2import org.junit.runners.Parameterized;3import org.junit.runners.Parameterized.Parameters;4import org.junit.runners.ParentRunner;5import org.junit.runners.model.FrameworkMethod;6import org.junit.runners.model.InitializationError;7import org.junit.runners.model.TestClass;8import java.util.ArrayList;9import java.util.Collection;10import java.util.List;11@RunWith(Parameterized.class)12public class ParameterizedTest extends ParentRunner<FrameworkMethod> {13    private int value;14    public ParameterizedTest(int value) {15        super(ParameterizedTest.class);16        this.value = value;17    }18    public static Collection<Object[]> getParameters() {19        List<Object[]> parameters = new ArrayList<>();20        parameters.add(new Object[] { 1 });21        parameters.add(new Object[] { 2 });22        parameters.add(new Object[] { 3 });23        parameters.add(new Object[] { 4 });24        parameters.add(new Object[] { 5 });25        return parameters;26    }27    protected List<FrameworkMethod> getChildren() {28        List<FrameworkMethod> children = new ArrayList<>();29        children.add(new FrameworkMethod("test1"));30        children.add(new FrameworkMethod("test2"));31        children.add(new FrameworkMethod("test3"));32        return children;33    }34    protected Description describeChild(FrameworkMethod child) {35        return Description.createTestDescription(getTestClass().getJavaClass(),36                String.format("[%s] %s", value, child.getName()));37    }38    protected void runChild(FrameworkMethod child, RunNotifier notifier) {39        Description description = describeChild(child);40        if (isIgnored(child)) {41            notifier.fireTestIgnored(description);42        } else {43            runLeaf(methodBlock(child), description, notifier);44        }45    }46    private Statement methodBlock(FrameworkMethod method) {47        Object test;48        try {49            test = new TestClass(getTestClass().getJavaClass()).getOnlyConstructor().newInstance();50        } catch (Exception e) {51            throw new RuntimeException("Failed to create test", e);52        }53        Statement statement = methodInvoker(method, test);54        statement = possiblyExpectingExceptions(method, test, statement);55        statement = withPotentialTimeout(method, test, statement);56        statement = withBefores(method, test, statement);57        statement = withAfters(method, test, statement);58        statement = withRules(method, test, statement);59        return statement;getChildren
Using AI Code Generation
1import org.junit.runner.JUnitCore2import org.junit.runner.Description3import org.junit.runner.notification.RunNotifier4import org.junit.runners.ParentRunner5import org.junit.runners.model.FrameworkMethod6import org.junit.runners.model.Statement7class TestRunner extends ParentRunner {8    TestRunner(Class testClass) {9        super(testClass)10    }11    protected List getChildren() {12            new FrameworkMethod(getTestClass().getJavaClass().getDeclaredMethod('test1')),13            new FrameworkMethod(getTestClass().getJavaClass().getDeclaredMethod('test2')),14            new FrameworkMethod(getTestClass().getJavaClass().getDeclaredMethod('test3')),15    }16    protected Description describeChild(FrameworkMethod child) {17        return Description.createTestDescription(getTestClass().getJavaClass(), child.getName())18    }19    protected void runChild(FrameworkMethod child, RunNotifier notifier) {20        Description description = describeChild(child)21        if (isIgnored(child)) {22            notifier.fireTestIgnored(description)23        } else {24            runLeaf(statement(child), description, notifier)25        }26    }27    private Statement statement(FrameworkMethod child) {28        try {29            test = newTest()30        } catch (Exception e) {31            return new Fail(e)32        }33        return new InvokeMethod(child, test)34    }35    private static class Fail extends Statement {36        Fail(Throwable targetException) {37        }38        void evaluate() throws Throwable {39        }40    }41    private static class InvokeMethod extends Statement {42        InvokeMethod(FrameworkMethod testMethod, Object target) {43        }44        void evaluate() throws Throwable {45            testMethod.invokeExplosively(target)46        }47    }48}49class TestClass {50    def test1() {51    }52    def test2() {53    }54    def test3() {55    }56}57JUnitCore.runClasses(TestRunner.class)getChildren
Using AI Code Generation
1public class JunitRunnerTest {2    public static void main(String[] args) throws Exception {3        JUnitCore jUnitCore = new JUnitCore();4        jUnitCore.run(AllTests.class);5    }6}7public class AllTests {8    public static Test suite() {9        TestSuite suite = new TestSuite();10        suite.addTestSuite(FirstTest.class);11        suite.addTestSuite(SecondTest.class);12        return suite;13    }14}15public class FirstTest {16    public void test1() {17        System.out.println("FirstTest.test1");18    }19}20public class SecondTest {21    public void test2() {22        System.out.println("SecondTest.test2");23    }24}getChildren
Using AI Code Generation
1import java.util.List;2import org.junit.runner.Description;3import org.junit.runner.JUnitCore;4import org.junit.runner.Request;5import org.junit.runner.Result;6import org.junit.runner.notification.Failure;7import org.junit.runner.notification.RunListener;8import org.junit.runners.BlockJUnit4ClassRunner;9import org.junit.runners.ParentRunner;10import org.junit.runners.model.InitializationError;11import org.junit.runners.model.RunnerBuilder;12public class AllTestsRunner extends ParentRunner<Runner> {13    private static final String TEST_SUITE_NAME = "com.example.tests.AllTests";14    private final BlockJUnit4ClassRunner blockRunner;15    public AllTestsRunner(Class<?> klass, RunnerBuilder builder) throws InitializationError {16        super(klass);17        blockRunner = new BlockJUnit4ClassRunner(klass);18        setScheduler(blockRunner.getScheduler());19    }20    protected List<Runner> getChildren() {21        return blockRunner.getChildren();22    }23    protected Description describeChild(Runner child) {24        return child.getDescription();25    }26    protected void runChild(Runner child, RunNotifier notifier) {27        child.run(notifier);28    }29    public static void main(String[] args) throws InitializationError {30        Request request = Request.aClass(AllTestsRunner.class);31        Result result = new JUnitCore().run(request);32        for (Failure failure : result.getFailures()) {33            System.out.println(failure.toString());34        }35    }36}37import org.junit.Test;38import org.junit.runner.RunWith;39import org.junit.runners.Suite;40@RunWith(AllTestsRunner.class)41@Suite.SuiteClasses({Test1.class, Test2.class})42public class AllTests {43}44public class Test1 {45    public void test1() {46        System.out.println("Test1");47    }48}49public class Test2 {50    public void test2() {51        System.out.println("Test2");52    }53}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!!
