JUnit 4 parameter tests allow testing methods by parameter values in the change range. To test the parameters, follow these steps:
- Add annotation @ runwith (parameterized. Class) to the test class)
- Define the parameter to be tested using the variable range parameter value as a private variable.
- Use the private variable declared in the previous step as the input parameter to create the constructor.
- . Create a public static method using the @ parameters annotation, which returns the variable values to be tested in the form of a set.
- Use defined private variables to define the test method
JUnit 4 parametric test example
Evennumberchecker. JavaCheck whether the entered number is an even number:
package in.co.javatutorials; /*** @author javatutorials.co.in*/public class EvenNumberChecker { /** * Is input number even. * * @param i input number * @return <code>true</code> if input is even number; otherwise return false */ public boolean isEven(int i) { if (i % 2 == 0) { return true; } else { return false; } }}
Evennumbercheckertest. JavaPerform Parameter Tests on evennumberchecker. Java:
package in.co.javatutorials; import static org.junit.Assert.*; import java.util.Arrays;import java.util.Collection; import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters; /*** @author javatutorials.co.in*/// Step 1@RunWith(Parameterized.class)public class EvenNumberCheckerTest { // Step 2: variables to be used in test method of Step 5 private int inputNumber; private boolean isEven; // Step 3: parameterized constructor public EvenNumberCheckerTest(int inputNumber, boolean isEven) { super(); this.inputNumber = inputNumber; this.isEven = isEven; } // Step 4: data set of variable values @Parameters public static Collection<Object[]> data() { Object[][] data = new Object[][] { { 2, true }, { 5, false }, { 10, false } }; return Arrays.asList(data); } @Test public void test() { System.out.println("inputNumber: " + inputNumber + "; isEven: " + isEven); EvenNumberChecker evenNumberChecker = new EvenNumberChecker(); // Step 5: use variables in test code boolean actualResult = evenNumberChecker.isEven(inputNumber); assertEquals(isEven, actualResult); }}
Sample output
The output in the eclipse JUnit window is:
Sample log output
inputNumber: 2; isEven: trueinputNumber: 5; isEven: falseinputNumber: 10; isEven: false
Source code download
Click Download source code
Tutorial directory navigation
- JUnit 4 ignore test (ignore Test)
- JUnit 4 timeout test (timeout Test)
Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The source of this article is http://blog.csdn.net/luanlouis. For more information, see. Thank you!