Proveedor de datos y TestNG XML: parametrización en selenio (ejemplo)

A medida que creamos software, siempre queremos que funcione de manera diferente con un conjunto de datos diferente. Cuando se aplica Prueba el mismo software, no podemos ser injustos al probarlo con un solo conjunto de datos. Aquí nuevamente, necesitamos verificar que nuestro sistema está aceptando todos los conjuntos de combinaciones que se espera que los respalden. Para hacer esto, necesitamos parametrizar nuestros scripts de prueba. Aquí viene la parametrización en la imagen.

Parametrización en selenio

Parametrización en selenio es un proceso para parametrizar los scripts de prueba para enviar múltiples datos a la aplicación en tiempo de ejecución. Es una estrategia de ejecución que ejecuta automáticamente casos de prueba repetidos utilizando diferentes valores. Se da el concepto logrado mediante la parametrización de los scripts de prueba Prueba basada en datos.

En este tutorial, aprenderá:

Tipo de parametrización en TestNG-

Para que la parametrización sea más clara, revisaremos las opciones de parametrización en uno de los marcos más populares para Selenium Webdriver: TestNG.

dos caminos mediante el cual podemos lograr la parametrización en TestNG

  1. Con la ayuda de Parámetros anotación y TestNG XML expediente.

  2. Con la ayuda de Proveedor de datos anotación.

Los parámetros de Testng.xml se pueden establecer o nivel de prueba

Un parámetro de DataProvider Mode y ITestContext se puede tomar como parámetro.

Estudiémoslos en detalle –

Nota de parámetro con Testng.xml

Seleccione la parametrización mediante anotaciones cuando desee abordar la complejidad y el número mínimo de combinaciones de entrada.

Veamos cómo funciona esto

Caso de prueba

Paso 1) Inicie el navegador y vaya a Google.com

Paso 2) Ingrese una palabra clave de búsqueda

Paso 3) Confirme que el valor de entrada es el mismo que el valor proporcionado por nuestros datos de prueba

Paso 4) Repita 2 y 3 hasta que se ingresen todos los valores

Autor de la prueba Clave de búsqueda
Guru99 India
Krishna SAM
Bhupesh porcelana

A continuación se muestra un ejemplo de cómo hacerlo SIN parámetros

package parameters;

import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class NoParameterWithTestNGXML {
	String driverPath = "C:\geckodriver.exe";
	WebDriver driver;
    
    @Test
    public void testNoParameter() throws InterruptedException{
        String author = "guru99";
        String searchKey = "india";
        
        System.setProperty("webdriver.gecko.driver", driverPath);        
        driver= new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        
        driver.get("https://google.com");
        WebElement searchText = driver.findElement(By.name("q"));
        //Searching text in google text box
        searchText.sendKeys(searchKey);
        
        System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
                System.out.println("Thread will sleep now");
        
        Thread.sleep(3000);
        System.out.println("Value in Google Search Box = "+searchText.getAttribute("value") +" ::: Value given by input = "+searchKey);
        //verifying the value in google search box
        AssertJUnit.assertTrue(searchText.getAttribute("value").equalsIgnoreCase(searchKey));
}
}

Estudie, el ejemplo de arriba. Imagínese lo complejo que será el código cuando hagamos esto para 3 combinaciones de entrada

Ahora, parametricemos esto usando TestNG

Para hacer eso, necesitarás

Aquí está el código completo

Nivel de prueba TestNG.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" thread-count="3" >
<parameter name="author" value="Guru99" />
<parameter name="searchKey" value="India" />
<test name="testGuru">
<parameter name="searchKey" value="UK" />
<classes>
<class name="parameters.ParameterWithTestNGXML">
</class>
</classes>
</test>
</suite>

Archivo ParameterWithTestNGXML.java

package parameters;

import org.testng.AssertJUnit;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterWithTestNGXML {
	String driverPath = "C:\geckodriver.exe";
	WebDriver driver;
    @Test
    @Parameters({"author","searchKey"})
    public void testParameterWithXML( @Optional("Abc") String author,String searchKey) throws InterruptedException{

        System.setProperty("webdriver.gecko.driver", driverPath);
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");

        WebElement searchText = driver.findElement(By.name("q"));
        //Searching text in google text box
        searchText.sendKeys(searchKey);

        System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
        System.out.println("Thread will sleep now");
        Thread.sleep(3000);
        System.out.println("Value in Google Search Box = "+searchText.getAttribute("value") +" ::: Value given by input = "+searchKey);
        //verifying the value in google search box
        AssertJUnit.assertTrue(searchText.getAttribute("value").equalsIgnoreCase(searchKey));

}
}

Instrucciones para ejecutar el script, seleccione el archivo XML y Ejecutar como NG Test Suite

Haga clic derecho en un archivo .xml -> Ejecutar como -> Testng Suite (Nota: Suite)

Ahora los parámetros se pueden definir en 2 niveles

  1. Nivel de posicionamiento: los parámetros dentro de la etiqueta serán un parámetro de nivel de posicionamiento de un archivo XML TestNG.
  2. Nivel de prueba: los parámetros estarán dentro de la etiqueta del archivo XML de prueba en su parámetro de nivel de prueba.

Esta es la misma prueba que los parámetros de nivel de posicionamiento

NOTA: Cuando el nombre del parámetro es el mismo en el nivel de serie y en el nivel de prueba, es mejor dar el parámetro de nivel de prueba sobre el nivel de serie. Entonces, en ese caso, todas las clases que están dentro de ese nivel de prueba compartirán el parámetro de violación, mientras que otras clases que están fuera del nivel de prueba compartirán el parámetro de nivel establecido.

Solución de problemas

Problema n. ° 1 El valor del parámetro en testng.xml no se puede escribir con el parámetro del método de prueba correspondiente, debe ser un error.

Considere el siguiente ejemplo

Aquí, un atributo ‘autor’ es igual a ‘Guru99’ que es una cadena y en el modo de prueba correspondiente espera un valor entero, por lo que encontramos una excepción aquí.

Número 2 Sus @Parameters no tienen un valor correspondiente en test.xml.

Puede resolver esta situación agregando @Opcional anotación en el parámetro correspondiente en el método de prueba.

Número 3: Quieres probar varios valores del mismo parámetro usando Testng.xml

¡La respuesta simple es que esto no se puede hacer! Puede tener diferentes parámetros, pero cada parámetro solo puede tener un valor. Esto ayuda a evitar valores codificados en el script. Esto hace que el código sea reutilizable. Piense en ello como archivos de configuración para un script. Si desea utilizar varios valores para los parámetros, utilice DataProviders

Parámetros usando Dataprovider

Probar la anotación de @Parameters es fácil, pero con muchos conjuntos de datos necesitamos usar un proveedor de datos.

Para completar miles de formularios web utilizando nuestro marco de prueba, necesitamos una metodología diferente que pueda brindarnos un conjunto de datos muy grande en un solo flujo de ejecución.

Este concepto basado en datos se logra mediante @Proveedor de datos anotación en TestNG.

El solo tiene uno atributo ‘nombre’. Si no especifica un atributo de nombre, el nombre del proveedor de datos será el mismo que el nombre del método correspondiente.

Devoluciones de proveedores de datos objeto JAVA bidimensional con el modo de prueba y el modo de prueba, a veces invocará M en una matriz de matriz M * N. Por ejemplo, si el proveedor de datos devuelve un conjunto de 2 * 3 objetos, el caso de prueba correspondiente se invocará 2 veces con 3 parámetros cada vez .

Ejemplo completo

package parameters;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ParameterByDataprovider {
    WebDriver driver;
    String driverPath = "C:\geckodriver.exe";

    @BeforeTest
    public void setup(){
        //Create firefox driver object
         System.setProperty("webdriver.gecko.driver", driverPath);
         driver = new FirefoxDriver();
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
         driver.get("https://google.com");
    }
 
    /** Test case to verify google search box
     * @param author
     * @param searchKey
     * @throws InterruptedException
     */

    @Test(dataProvider="SearchProvider")
    public void testMethod(String author,String searchKey) throws InterruptedException{
    {
        WebElement searchText = driver.findElement(By.name("q"));
        //search value in google searchbox
        searchText.sendKeys(searchKey);
        System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
        Thread.sleep(3000);
        String testValue = searchText.getAttribute("value");
        System.out.println(testValue +"::::"+searchKey);
        searchText.clear();
        //Verify if the value in google search box is correct
        Assert.assertTrue(testValue.equalsIgnoreCase(searchKey));
    }
    }
    /**
     * @return Object[][] where first column contains 'author'
     * and second column contains 'searchKey'
     */

    @DataProvider(name="SearchProvider")
    public Object[][] getDataFromDataprovider(){
    return new Object[][] 
    	{
            { "Guru99", "India" },
            { "Krishna", "UK" },
            { "Bhupesh", "USA" }
        };

    }

}

Invitar a DataProvider de una clase diferente

De forma predeterminada, DataProvider reside en la misma clase que el método de prueba o su principal. Para ponerlo en otra clase, necesitamos hacer que el método del proveedor de datos sea tan estático como en el método de prueba, necesitamos agregar un atributo dataProviderClass en @ Examen anotación.

Ejemplo de código

TestClass ParameterDataproviderWithClassLevel.java

package parameters;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ParameterDataproviderWithClassLevel {
    WebDriver driver;
    String driverPath = "C:\geckodriver.exe";
    
 	@BeforeTest
    public void setup(){
 		System.setProperty("webdriver.gecko.driver", driverPath);
		driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
    }
   
    @Test(dataProvider="SearchProvider",dataProviderClass=DataproviderClass.class)
    public void testMethod(String author,String searchKey) throws InterruptedException{
        
        WebElement searchText = driver.findElement(By.name("q"));
        //Search text in google text box
        searchText.sendKeys(searchKey);
        System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
        Thread.sleep(3000);
        //get text from search box
        String testValue = searchText.getAttribute("value");
        System.out.println(testValue +"::::"+searchKey);
        searchText.clear();
        //verify if search box has correct value
        Assert.assertTrue(testValue.equalsIgnoreCase(searchKey));
   }
}

DataproviderClass.java

package parameters;

import org.testng.annotations.DataProvider;
public class DataproviderClass {
        @DataProvider(name="SearchProvider")
        public static Object[][] getDataFromDataprovider(){
            return new Object[][] {
                { "Guru99", "India" },
                { "Krishna", "UK" },
                { "Bhupesh", "USA" }
            };  
}}

Tipos de parámetros en el proveedor de datos

Hay dos tipos de parámetros que admite el método DataProvider.

Método– Si el MISMO DataProvider debería comportarse de manera diferente con un método de prueba diferente, utilizando un parámetro de método.

En el siguiente ejemplo,

package parameters;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ParameterByMethodInDataprovider{

    WebDriver driver;
    String driverPath = "C:\geckodriver.exe";
     
    @BeforeTest
    public void setup(){
    	System.setProperty("webdriver.gecko.driver", driverPath);
    	driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
    }

    @Test(dataProvider="SearchProvider")
    public void testMethodA(String author,String searchKey) throws InterruptedException{
        
    	WebElement searchText = driver.findElement(By.name("q"));
        //Search text in search box
        searchText.sendKeys(searchKey);
        //Print author and search string
        System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
        Thread.sleep(3000);
        String testValue = searchText.getAttribute("value");
        System.out.println(testValue +"::::"+searchKey);
        searchText.clear();
        //Verify if google text box is showing correct value
        Assert.assertTrue(testValue.equalsIgnoreCase(searchKey));
    }
      
    @Test(dataProvider="SearchProvider")
    public void testMethodB(String searchKey) throws InterruptedException{
        {
        	WebElement searchText = driver.findElement(By.name("q"));
            //Search text in search box
            searchText.sendKeys(searchKey);
            //Print only search string
            System.out.println("Welcome ->Unknown user Your search key is->"+searchKey);
            Thread.sleep(3000);
            String testValue = searchText.getAttribute("value");
            System.out.println(testValue +"::::"+searchKey);
            searchText.clear();
            //Verify if google text box is showing correct value
            Assert.assertTrue(testValue.equalsIgnoreCase(searchKey));
        }
    }    
    /**
     * Here DataProvider returning value on the basis of test method name
     * @param m
     * @return
     **/

    @DataProvider(name="SearchProvider")
    public Object[][] getDataFromDataprovider(Method m){
        if(m.getName().equalsIgnoreCase("testMethodA")){
        return new Object[][] {
                { "Guru99", "India" },
                { "Krishna", "UK" },
                { "Bhupesh", "USA" }
            };}
        else{
        return new Object[][] {
                { "Canada" },
                { "Russia" },
                { "Japan" }
            };}       
    }
}

Aquí está la salida

ITestContext– Se puede utilizar para crear varios parámetros para escenarios de prueba basados ​​en grupos.

En la vida real, puede utilizar ITestContext para cambiar los valores de los parámetros según los métodos de prueba, el host y las configuraciones de prueba.

En el siguiente ejemplo de código

package parameters;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ParameterByITestContextInDataprovider {
	WebDriver driver;
	String driverPath = "C:\geckodriver.exe";
	@BeforeTest(groups={"A","B"})
	public void setup(){
		System.setProperty("webdriver.gecko.driver", driverPath);
		  	driver = new FirefoxDriver();
			driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
			driver.get("https://google.com");
	}
	
	@Test(dataProvider="SearchProvider",groups="A")
	public void testMethodA(String author,String searchKey) throws InterruptedException{
		{
		  //search google textbox
			WebElement searchText = driver.findElement(By.name("q"));
			//search a value on it
			searchText.sendKeys(searchKey);
			System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
			Thread.sleep(3000);
			String testValue = searchText.getAttribute("value");
			System.out.println(testValue +"::::"+searchKey);
			searchText.clear();
			//verify correct value in searchbox
			Assert.assertTrue(testValue.equalsIgnoreCase(searchKey));
	}
	}
	
	@Test(dataProvider="SearchProvider",groups="B")
	public void testMethodB(String searchKey) throws InterruptedException{
		{
		  //find google search box
			WebElement searchText = driver.findElement(By.name("q"));
			//search a value on it
			searchText.sendKeys(searchKey);
			System.out.println("Welcome ->Unknown user Your search key is->"+searchKey);
			Thread.sleep(3000);
			String testValue = searchText.getAttribute("value");
			System.out.println(testValue +"::::"+searchKey);
			searchText.clear();
			//verify correct value in searchbox
			Assert.assertTrue(testValue.equalsIgnoreCase(searchKey));
	}
	}
	
	/**
	 * Here the DAtaProvider will provide Object array on the basis on ITestContext
	 * @param c
	 * @return
	 */
	@DataProvider(name="SearchProvider")
	public Object[][] getDataFromDataprovider(ITestContext c){
	Object[][] groupArray = null;
		for (String group : c.getIncludedGroups()) {
		if(group.equalsIgnoreCase("A")){
			groupArray = new Object[][] { 
					{ "Guru99", "India" }, 
					{ "Krishna", "UK" }, 
					{ "Bhupesh", "USA" } 
				};
		break;	
		}
			else if(group.equalsIgnoreCase("B"))
			{
			groupArray = new Object[][] { 
						{  "Canada" }, 
						{  "Russia" }, 
						{  "Japan" } 
					};
			}
		break;
	}
	return groupArray;		
	}
}

Nota: Si ejecuta su clase de prueba directamente, primero llamará al proveedor de datos que los grupos no pueden obtener información porque los grupos no están disponibles. Pero en cambio, si llama a esta clase a través de testng.xml, la información del grupo estará disponible con ITestContext. Utilice el siguiente XML para llamar a la prueba


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

  <test name="example1">

    <groups>
        <run>
            <include name="A" />
        </run>
    </groups>

    <classes>
       <class
        name="parameters.ParameterByITestContextInDataprovider" />
    </classes>

  </test>


  <test name="example2">

    <groups>
        <run>
            <include name="B" />
        </run>
    </groups>

    <classes>
       <class
        name="parameters.ParameterByITestContextInDataprovider" />
    </classes>

  </test>

</suite>

Resumen:

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *