By specifying 'dataProviderClass', you can access the data providers defined in other class.
Example
@Test(dataProvider = "inputCombinations", dataProviderClass = CustomDataProvider.class)
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;
}
}
CustomDataProvider.java
package com.sample.app.tests;
import org.testng.annotations.DataProvider;
public class CustomDataProvider {
@DataProvider(name = "inputCombinations")
private Object[][] input() {
return new Object[][] { { 0, 0 }, { -1, -2 }, { 1, -2 }, { -2, 1 }, { 1, 2 } };
}
}
DataProviderDemo1.java
package com.sample.app.tests;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.sample.app.arithmetic.Calculator;
public class DataProviderDemo1 {
private Calculator calculator = new Calculator();
@Test(dataProvider = "inputCombinations", dataProviderClass = CustomDataProvider.class)
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 DataProviderDemo1.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