Using @DataProvider annotation, we can pass parameters to test cases.
For example, let’s try to test 'add' function of calculator with different input combinations.
Step 1: Define a method that feeds input the test case.
@DataProvider(name = "inputCombinations")
private Object[][] input() {
return new Object[][] { { 0, 0 }, { -1, -2 }, { 1, -2 }, { -2, 1 }, { 1, 2 } };
}
Step 2: Specify data provider to the test case. Data provider pass the input to the test function.
@Test(dataProvider = "inputCombinations")
public void addTest(int a, int b) {
int result = calculator.add(a, b);
System.out.println("Sum of a and b is : " + result);
assertEquals(result, sum(a, b));
}
Find the below working application.
package com.sample.app.arithmetic;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int mul(int a, int b) {
return a * b;
}
public int div(int a, int b) {
return a / b;
}
public int remainder(int a, int b) {
return a % b;
}
public boolean isEven(int number) {
return number % 2 == 0;
}
public boolean isOdd(int number) {
return number % 2 != 0;
}
}
DataProviderDemo.java
package com.sample.app.tests;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.sample.app.arithmetic.Calculator;
public class DataProviderDemo {
private Calculator calculator = new Calculator();
@DataProvider(name = "inputCombinations")
private Object[][] input() {
return new Object[][] { { 0, 0 }, { -1, -2 }, { 1, -2 }, { -2, 1 }, { 1, 2 } };
}
@Test(dataProvider = "inputCombinations")
public void addTest(int a, int b) {
int result = calculator.add(a, b);
System.out.println("Sum of a and b is : " + result);
assertEquals(result, sum(a, b));
}
private static int sum(int a, int b) {
return a + b;
}
}
Run DataProviderDemo.java, you will see below messages in console.
[RemoteTestNG] detected TestNG version 7.0.0 Sum of a and b is : 0 Sum of a and b is : -3 Sum of a and b is : -1 Sum of a and b is : -1 Sum of a and b is : 3 PASSED: addTest(0, 0) PASSED: addTest(-1, -2) PASSED: addTest(1, -2) PASSED: addTest(-2, 1) PASSED: addTest(1, 2) =============================================== Default test Tests run: 5, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 5, Passes: 5, Failures: 0, Skips: 0 ===============================================
No comments:
Post a Comment