Sunday 15 March 2020

TestNG: Provide test input based on method name

Using ‘java.lang.reflect.Method’ class and @DataProvider annotation we can pass the input data based on method name.

Example
@DataProvider(name = "inputCombinations")
private Object[][] input(Method method) {
 if (method.getName().equals("negativeValues")) {
  return new Object[][] { { -1, -2 }, { 1, -2 }, { -2, 1 } };
 } else if (method.getName().equals("positiveValues")) {
  return new Object[][] { { 11, 12 }, { 14, 15 } };
 }
 return null;

}

Find the below working application.

CustomDataProvider1.java
package com.sample.app.tests;

import java.lang.reflect.Method;

import org.testng.annotations.DataProvider;

public class CustomDataProvider1 {

 @DataProvider(name = "inputCombinations")
 private Object[][] input(Method method) {
  if (method.getName().equals("negativeValues")) {
   return new Object[][] { { -1, -2 }, { 1, -2 }, { -2, 1 } };
  } else if (method.getName().equals("positiveValues")) {
   return new Object[][] { { 11, 12 }, { 14, 15 } };
  }
  return null;

 }

}

DataProviderDemo2.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 DataProviderDemo2 {

 private Calculator calculator = new Calculator();

 @Test(dataProvider = "inputCombinations", dataProviderClass = CustomDataProvider1.class)
 public void negativeValues(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));
 }

 @Test(dataProvider = "inputCombinations", dataProviderClass = CustomDataProvider1.class)
 public void positiveValues(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 DataProviderDemo2.java, you will see below messages in console.

[RemoteTestNG] detected TestNG version 7.0.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 : 23
Sum of a and b is : 29
PASSED: negativeValues(-1, -2)
PASSED: negativeValues(1, -2)
PASSED: negativeValues(-2, 1)
PASSED: positiveValues(11, 12)
PASSED: positiveValues(14, 15)

===============================================
    Default test
    Tests run: 5, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 5, Passes: 5, Failures: 0, Skips: 0
===============================================



Previous                                                    Next                                                    Home

No comments:

Post a Comment