How to use TestWithParameters class of org.junit.runners.parameterized package

Best junit code snippet using org.junit.runners.parameterized.TestWithParameters

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package junit4.v4_12;
2
3import org.junit.Test;
4import org.junit.runner.RunWith;
5import org.junit.runner.Runner;
6import org.junit.runners.Parameterized;
7import org.junit.runners.Parameterized.Parameter;
8import org.junit.runners.Parameterized.Parameters;
9import org.junit.runners.Parameterized.UseParametersRunnerFactory;
10import org.junit.runners.model.InitializationError;
11import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
12import org.junit.runners.parameterized.ParametersRunnerFactory;
13import org.junit.runners.parameterized.TestWithParameters;
14
15import java.util.Arrays;
16import java.util.List;
17
18/**
19 * {@link UseParametersRunnerFactory} を無理矢理使ってみる。
20 *
21 * @author irof
22 */
23@RunWith(Parameterized.class)
24@UseParametersRunnerFactory(PracUseParametersRunnerFactory.FriendlyRunner.Factory.class)
25public class PracUseParametersRunnerFactory {
26
27    /**
28     * パラメータが一つの時は単純なリストの <code>@parameters</code> と
29     * 単一の <code>@Parameter</code> フィールドで良くなった。
30     */
31    @Parameters
32    public static List<String> data() {
33        return Arrays.asList("A", "B", "C");
34    }
35
36    @Parameter
37    public String arg;
38
39    @Test
40    public void test() throws Exception {
41    }
42
43    /**
44     * テストメソッド名がにこやかになる謎のRunner
45     */
46    public static class FriendlyRunner extends BlockJUnit4ClassRunnerWithParameters {
47
48        public FriendlyRunner(TestWithParameters test) throws InitializationError {
49            super(test);
50        }
51
52        @Override
53        protected String getName() {
54            return " (^-^) " + super.getName();
55        }
56
57        public static class Factory implements ParametersRunnerFactory {
58
59            @Override
60            public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
61                return new FriendlyRunner(test);
62            }
63        }
64    }
65}
66
Full Screen
copy
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package org.apache.zookeeper;
20
21import java.util.List;
22import org.junit.runners.model.FrameworkMethod;
23import org.junit.runners.model.InitializationError;
24import org.junit.runners.model.Statement;
25import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
26import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory;
27import org.junit.runners.parameterized.TestWithParameters;
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31public class ZKParameterized {
32
33    private static final Logger LOG = LoggerFactory.getLogger(ZKParameterized.class);
34
35    public static class RunnerFactory extends BlockJUnit4ClassRunnerWithParametersFactory {
36
37        @Override
38        public org.junit.runner.Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
39            return new ZKParameterized.Runner(test);
40        }
41
42    }
43
44    public static class Runner extends BlockJUnit4ClassRunnerWithParameters {
45
46        public Runner(TestWithParameters test) throws InitializationError {
47            super(test);
48        }
49
50        @Override
51        protected List<FrameworkMethod> computeTestMethods() {
52            return JUnit4ZKTestRunner.computeTestMethodsForClass(getTestClass().getJavaClass(), super.computeTestMethods());
53        }
54
55        @Override
56        protected Statement methodInvoker(FrameworkMethod method, Object test) {
57            return new JUnit4ZKTestRunner.LoggedInvokeMethod(method, test);
58        }
59
60    }
61
62}
63
Full Screen
copy
1package com.example.controlsumsnilschecker.utils;
2
3import org.junit.runner.Runner;
4import org.junit.runners.model.InitializationError;
5import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
6import org.junit.runners.parameterized.ParametersRunnerFactory;
7import org.junit.runners.parameterized.TestWithParameters;
8import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
9
10/*
11 * @created 09.11.2021 - 3:08
12 * @project controlSumSnilsChecker
13 * @author Polyakov Anton
14 */
15public class SpringParametersRunnerFactory implements ParametersRunnerFactory {
16 @Override
17 public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
18  final BlockJUnit4ClassRunnerWithParameters runnerWithParameters = new BlockJUnit4ClassRunnerWithParameters(test);
19  return new SpringJUnit4ClassRunner(test.getTestClass().getJavaClass()) {
20   @Override
21   protected Object createTest() throws Exception {
22    final Object testInstance = runnerWithParameters.createTest();
23    getTestContextManager().prepareTestInstance(testInstance);
24    return testInstance;
25   }
26  };
27 }
28}
29
30
Full Screen
copy
1import junitparams.JUnitParamsRunner;
2import junitparams.Parameters;
3import org.junit.Before;
4import org.junit.Test;
5import org.junit.runner.RunWith;
6import org.mockito.InjectMocks;
7import org.mockito.Mock;
8
9import java.util.Arrays;
10
11import static org.hamcrest.CoreMatchers.is;
12import static org.hamcrest.MatcherAssert.assertThat;
13import static org.mockito.Mockito.when;
14import static org.mockito.MockitoAnnotations.initMocks;
15
16@RunWith(value = JUnitParamsRunner.class)
17public class ParameterizedMockitoTest {
18
19    @InjectMocks
20    private SomeService someService;
21    @Mock
22    private SomeOtherService someOtherService;
23
24    @Before
25    public void setup() {
26        initMocks(this);
27    }
28
29    @Test
30    @Parameters(method = "getParameters")
31    public void testWithParameters(Boolean parameter, Boolean expected) throws Exception {
32        when(someOtherService.getSomething()).thenReturn(new Something());
33        Boolean testObject = someService.getTestObject(parameter);
34        assertThat(testObject, is(expected));
35    }
36
37    @Test
38    public void testSomeBasicStuffWithoutParameters() {
39        int i = 0;
40        assertThat(i, is(0));
41    }
42
43    public Iterable getParameters() {
44        return Arrays.asList(new Object[][]{
45                {Boolean.TRUE, Boolean.TRUE},
46                {Boolean.FALSE, Boolean.FALSE},
47        });
48    }
49}
50
Full Screen
copy
1@RunWith(Parameterized.class)
2public class YourComponentTest {        
3    @Mock YourDep mockYourDep;
4
5    @Parameter
6    public Parameter parameter;
7
8    @Parameters public static Collection<Object[]> data() { /* Return the values */ }
9
10    @Before
11    public void init() {
12        MockitoAnnotations.initMocks(this);
13    }
14
15    @Test public void test() { /* Use the field value in assertions */ }
16}
17
Full Screen
copy
1@RunWith(Parameterized.class)
2public class YourComponentTest {
3    @Rule public MockitoRule rule = MockitoJUnit.rule();
4    @Mock YourDep mockYourDep;
5
6    @Parameters public static Collection<Object[]> data() { /* Return the values */ }
7
8    public YourComponentTest(Parameter parameter) { /* Save the parameter to a field */ }
9
10    @Test public void test() { /* Use the field value in assertions */ }
11}
12
Full Screen
copy
1package example.junit;
2
3import java.util.ArrayList;
4import java.util.Arrays;
5import java.util.Collection;
6import java.util.Collections;
7import java.util.Iterator;
8import java.util.List;
9
10import org.apache.commons.lang3.StringUtils;
11import org.junit.AfterClass;
12import org.junit.Before;
13import org.junit.BeforeClass;
14import org.junit.Test;
15import org.junit.runner.RunWith;
16import org.junit.runners.Parameterized;
17import org.openqa.selenium.By;
18import org.openqa.selenium.WebDriver;
19import org.openqa.selenium.WebElement;
20import org.openqa.selenium.chrome.ChromeDriver;
21import org.openqa.selenium.firefox.FirefoxDriver;
22
23/**
24 * Parallel Selenium WebDriver example for http://stackoverflow.com/questions/30353996/selenium-and-parallelized-junit-webdriver-instances
25 * Parallelized class is like http://hwellmann.blogspot.de/2009/12/running-parameterized-junit-tests-in.html
26 */
27@RunWith(Parallelized.class)
28public class ParallelSeleniumTest {
29
30    /** Available driver types */
31    enum WebDriverType {
32        CHROME,
33        FIREFOX
34    }
35
36    /** Create WebDriver instances for specified type */
37    static class WebDriverFactory {
38        static WebDriver create(WebDriverType type) {
39            WebDriver driver;
40            switch (type) {
41            case FIREFOX:
42                driver = new FirefoxDriver();
43                break;
44            case CHROME:
45                driver = new ChromeDriver();
46                break;
47            default:
48                throw new IllegalStateException();
49            }
50            log(driver, "created");
51            return driver;
52        }
53    }
54
55    // for description how to user Parametrized
56    // see: https://github.com/junit-team/junit/wiki/Parameterized-tests
57    @Parameterized.Parameter
58    public WebDriverType currentDriverType;
59
60    // test case naming requires junit 4.11
61    @Parameterized.Parameters(name= "{0}")
62    public static Collection<Object[]> driverTypes() {
63        return Arrays.asList(new Object[][] {
64                { WebDriverType.CHROME },
65                { WebDriverType.FIREFOX }
66            });
67    }
68
69    private static ThreadLocal<WebDriver> currentDriver = new ThreadLocal<WebDriver>();
70    private static List<WebDriver> driversToCleanup = Collections.synchronizedList(new ArrayList<WebDriver>());
71
72    @BeforeClass
73    public static void initChromeVariables() {
74        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
75    }
76
77    @Before
78    public void driverInit() {
79        if (currentDriver.get()==null) {
80            WebDriver driver = WebDriverFactory.create(currentDriverType);
81            driversToCleanup.add(driver);
82            currentDriver.set(driver);
83        }
84    }
85
86    private WebDriver getDriver() {
87        return currentDriver.get();
88    }
89
90    @Test
91    public void searchForChromeDriver() throws InterruptedException {
92        openAndSearch(getDriver(), "chromedriver");
93    }
94
95    @Test
96    public void searchForJunit() throws InterruptedException {
97        openAndSearch(getDriver(), "junit");
98    }
99
100    @Test
101    public void searchForStackoverflow() throws InterruptedException {
102        openAndSearch(getDriver(), "stackoverflow");
103    }
104
105    private void openAndSearch(WebDriver driver, String phraseToSearch) throws InterruptedException {
106        log(driver, "search for: "+phraseToSearch);
107        driver.get("http://www.google.com");
108        WebElement searchBox = driver.findElement(By.name("q"));
109        searchBox.sendKeys(phraseToSearch);
110        searchBox.submit();
111        Thread.sleep(3000);
112    }
113
114    @AfterClass
115    public static void driverCleanup() {
116        Iterator<WebDriver> iterator = driversToCleanup.iterator();
117        while (iterator.hasNext()) {
118            WebDriver driver = iterator.next();
119            log(driver, "about to quit");
120            driver.quit();
121            iterator.remove();
122        }
123    }
124
125    private static void log(WebDriver driver, String message) {
126        String driverShortName = StringUtils.substringAfterLast(driver.getClass().getName(), ".");
127        System.out.println(String.format("%15s, %15s: %s", Thread.currentThread().getName(), driverShortName, message));
128    }
129
130}
131
Full Screen
copy
1pool-1-thread-1,    ChromeDriver: created
2pool-1-thread-1,    ChromeDriver: search for: stackoverflow
3pool-1-thread-2,   FirefoxDriver: created
4pool-1-thread-2,   FirefoxDriver: search for: stackoverflow
5pool-1-thread-1,    ChromeDriver: search for: junit
6pool-1-thread-2,   FirefoxDriver: search for: junit
7pool-1-thread-1,    ChromeDriver: search for: chromedriver
8pool-1-thread-2,   FirefoxDriver: search for: chromedriver
9           main,    ChromeDriver: about to quit
10           main,   FirefoxDriver: about to quit
11
Full Screen
copy
1public class SpringJUnit4ClassRunnerFactory
2    implements ParameterizedRunnerFactory {
3  @Override
4  public Runner createRunnerForTestWithParameters(final TestWithParameters test)
5         throws InitializationError {
6     return new SpringJUnit4ClassRunner(testClass.getJavaClass()) {
7       @Override
8       protected Object createTest() throws Exception {
9         Object[] args = test.getParameters().toArray();
10         Object testInstance = test.getTestClass().getOnlyConstructor()
11             .newInstance(args);
12
13         // copied from SpringJUnit4ClassRunner.createTest():
14         getTestContextManager().prepareTestInstance(testInstance);
15         return testInstance;
16       }
17     };
18  }
19}
20
Full Screen
copy
1@UseParametersRunnerFactory
2@RunWith(Parameterized.class)
3public class FooTesdt {
4}
5
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in TestWithParameters

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)