How to use #DataProvider in TestNG - selenium-webdriver

package com.xchanging.selenium.testcases.testng;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.xchanging.selenium.utility.CaptureScreenShot;
import com.xchanging.selenium.utility.ClearText;
import com.xchanging.selenium.utility.ClickEvent;
import com.xchanging.selenium.utility.GlobalVariables;
import com.xchanging.selenium.utility.ReadRows;
import com.xchanging.selenium.utility.SelectCheckBox;
import com.xchanging.selenium.utility.SelectDropDown;
import com.xchanging.selenium.utility.Text;
import com.xchanging.selenium.utility.VerifyText;
public class RegisterAccount extends GlobalVariables {
#Test(dataProvider = "getData")
public static void register() throws IOException {
ClickEvent.clickAt("createAccount_xpath");
Text.enterText("username_name", "username");
Text.enterText("password_name", "machans");
Text.enterText("confirmPassword_name", "machans");
ClickEvent.clickAt("securityquestion_name");
SelectDropDown.select("securityquestion_name", "petname");
Text.enterText("securityanswer_xpath", "vsbhss");
Text.enterText("fullName_name", "Chandrasekaran");
Text.enterText("email_name", "xx#gmail.com");
ClearText.clear("dob_name");
Text.enterText("dob_name", "11/11/1982");
SelectDropDown.select("gender_name", 1);
SelectDropDown.select("marital_name", 1);
SelectDropDown.select("country_name", "India");
SelectCheckBox.selectchkbox("checkbox_xpath");
ClickEvent.clickAt("register_xpath");
VerifyText.verify("Congratulations.. You have registered successfully");
VerifyText.verify("Login now");
CaptureScreenShot.screenshot("Registration_Successful");
ClickEvent.clickAt("closebutton_xpath");
}
#DataProvider
public ArrayList<HashMap> getData() throws IOException {
ArrayList<HashMap> table = ReadRows.readExcel("Sheet1");
return table;
}
}
Now I wanted to use this DataProvider and get values from xls and have to use it in my #Test Part.
Can any one help out???
If I use, this way it is working fine..
ArrayList<HashMap> table = ReadRows.readExcel("Sheet1");
table.get(0).get("email")
But I wanted to use #DataProvider..

Some How managed..
#Test(dataProvider="getData")
public static void register(ArrayList<HashMap> table) throws IOException {
}
This solves my problem.

If you want to use dataProvider annotation. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method.
You can try something like this:
#DataProvider
public Object[][] getData() throws IOException {
Object[][] data = new Object[3][2] // based on the size of your excel rows & cols.
// Write the code to read data from excel and store.
data[][] = //your Code.
return data;
}
And your test method can use the data.
//Lets say your Object[][] data returns 2 arguments.
#Test(dataProvider="getData")
public void testMethod(firstArgument, secondArgument){
// your code to use the arguments supplied by data.
}

Related

apache camel JUnit5 test case for database operation

I am trying to write Junit5 test case for apache camel router which has the DB operations.
Use case : There is an API call which will give me the data and my router is inserting those data to local database.
I have to write the test case to check the count from the database and compare it with the api data count which should match.
And the Database connection as well
My test class needs to get the count from the database and api to compare if both matches the assert satisfied .
Please help me to write test case for the same , Please refer the below for junit test case code.
Thanks in advance.
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.http.base.HttpOperationFailedException;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.BootstrapWith;
#CamelSpringBootTest
#ActiveProfiles("mock")
#BootstrapWith(SpringBootTestContextBootstrapper.class)
public class TestingPersonStoringDatabase {
#Autowired
protected CamelContext camelContext;
#Autowired
private ProducerTemplate template;
#EndpointInject("mock:purePersonsEndpoint")
private MockEndpoint personsMock;
#EndpointInject("mock:storePersons")
private MockEndpoint mock;
#BeforeEach
public void setup() throws Exception {
AdviceWith.adviceWith(camelContext, "storePersonsRoute",
a -> a.weaveAddLast().to("sql:select count(*) as results from persons").setBody()
.simple("${body[0][RESULTS]}").log("RESULTS: ${body}").to("mock:storePersons"));
camelContext.start();
}
#Test
public void testPersons() throws Exception {
personsMock.whenAnyExchangeReceived(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
throw new HttpOperationFailedException("", 400, "Simulated API error", null, null, null);
}
});
//MockEndpoint.assertIsSatisfied(camelContext);
mock.expectsMessageCount(142);
personsMock.expectsMessageCount(142);
mock.assertIsSatisfied();
}
}
storePersonsRoute this router has a inserting data in the database

Passing values from database to the UI using Automation Selenium WebDriver with Java?

I am trying to pass values from my MySQL database to the UI using Automation Selenium WebDriver with Java? The code is returning only the first row.
Here are the database values:
I have changed the code many times using for int loop and have received different kind of errors such as:
before start of result set
after end of result set
I am unable to figure it out. I am not sure what I am doing wrong.
Basically, In this case I have firstName and lastName which are passed via the database to the UI. I want to pass those values to my test case. I do not want to hard code. Currently, I have a table with 2 columns and one column is firstName and second column is lastName.
I want to Iterate through the database and pick these values wherever I want. SendKeys.
Here is my test case code file.
FacebookTest file code below.
import static org.testng.Assert.assertThrows;
import java.sql.Array;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import selenium.ReadExcel;
public class FacebookTest
{
#SuppressWarnings({ "static-access", "unchecked" })
public static void main(String[] args) throws Exception
//public static void facebookTest()
{
// pointing to the file, now FF must have pointer as well in Selenium 3.0
// WebDriver
System.setProperty("webdriver.gecko.driver","geckodriver.exe");
// OPEN FF
FirefoxDriver driver = new FirefoxDriver();
DBTestData db = new DBTestData();
// ENTER URL
driver.get("http://www.facebook.com/");
try
{
ResultSet testData = db.data("","");
for(int i = 0; i < 10; i++)
{
String firstName = testData.getString("firstName");
String lastName = testData.getString("lastName");
System.out.println(firstName);
System.out.println(lastName);
driver.findElement(By.id("u_0_e")).clear();
driver.findElement(By.id("u_0_e")).sendKeys(firstName);
driver.findElement(By.id("u_0_g")).clear();
driver.findElement(By.id("u_0_g")).sendKeys(lastName);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
driver.quit();
}
}
}
Here is my DB file where I am getting the values from database and returning it to the test case 101 - see code below.
DBTestData code file below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
public class DBTestData {
// public static void main(String[] args) throws Exception
#SuppressWarnings({ "unused" })
// public static String data() throws Exception
public static ResultSet data(String firstName, String lastName) throws ClassNotFoundException, SQLException
{
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
// after localhost:3306 is where you will put the name of the database
// jdbc:mysql://localhost:3606/testdb ---> this is a database
// root is a database user and password too
// our query below
PreparedStatement statement = con.prepareStatement("SELECT firstName, lastName FROM test_data");
// creating variable to execute query
ResultSet result = statement.executeQuery();
// List sqlData = new ArrayList();
ArrayList<String> sqlData = new ArrayList<String>();
while (result.next())
{
sqlData.add(firstName = result.getString(firstName));
sqlData.add(lastName = result.getString(lastName));
}
return result;
}
}
Let me know how I can achieve this concept. Once I get the basics I will utilize the same file other test cases. Why can't we use the same concept 2D array to pass the values from database to UI?
Here is how I resolved my issue. I used a do while loop in my test case and It was able to fetch all the data from all rows and Iterate it in my webpage.
Here is the code below.
FacebookTest code file:
import static org.testng.Assert.assertThrows;
import java.sql.Array;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import selenium.ReadExcel;
public class FacebookTest
{
#SuppressWarnings({ "static-access", "unchecked" })
public static void main(String[] args) throws Exception
{
// pointing to the file, now FF must have pointer as well in Selenium 3.0 WebDriver
System.setProperty("webdriver.gecko.driver","geckodriver.exe");
// OPEN FF
FirefoxDriver driver = new FirefoxDriver();
DBTestData db = new DBTestData();
// ENTER URL
driver.get("http://www.facebook.com/");
try
{
ResultSet testData = db.data("","");
do
{
String firstName = testData.getString(1);
String lastName = testData.getString(2);
driver.findElement(By.id("u_0_e")).clear();
driver.findElement(By.id("u_0_e")).sendKeys(firstName);
driver.findElement(By.id("u_0_g")).clear();
driver.findElement(By.id("u_0_g")).sendKeys(lastName);
}
while(testData.next());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
driver.quit();
}
}
}
Here is my DBTestData file:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
public class DBTestData
{
public static ResultSet data(String firstName, String lastName) throws ClassNotFoundException, SQLException
{
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
// after localhost:3306 is where you will put the name of the database
// jdbc:mysql://localhost:3606/testdb ---> this is a database
// root is a database user and password too
// our query below
PreparedStatement statement = con.prepareStatement("SELECT firstName, lastName FROM test_data");
// creating variable to execute query
ResultSet result = statement.executeQuery();
// store all the rows data into one variable
ArrayList<String> sqlData = new ArrayList<String>();
while(result.next())
{
sqlData.add(firstName= result.getString("firstName"));
sqlData.add(lastName = result.getString("lastName"));
break;
}
return result;
}
}
So, how do I properly close the database connection?
And how do I Iterate until n number of rows?
Thanks
con.close(); is command for closing db

Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin

I am trying to create a Minecraft plugin with a command that will set the world name into config.yml. Except I keep getting "Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin" when I attempt to set the config. I have already searched around for several way to fix this but I have not understood have to implement other situations into mine.
Here is my code:
Main.java:
package me.Liam22840.MurderRun;
import org.bukkit.plugin.java.JavaPlugin;
import me.Liam22840.MurderRun.commands.HelpCommand;
import me.Liam22840.MurderRun.commands.SetmapCommand;
public class Main extends JavaPlugin {
#Override
public void onEnable(){
loadConfig();
new HelpCommand(this);
new SetmapCommand(this);
}
public void loadConfig(){
getConfig().options().copyDefaults(true);
saveConfig();
}
}
SetmapCommand.java:
package me.Liam22840.MurderRun.commands;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import Utils.Utils;
import me.Liam22840.MurderRun.Main;
import me.Liam22840.MurderRun.getConfig;
public class SetmapCommand implements CommandExecutor{
private int count;
public SetmapCommand(Main plugin){
plugin.getCommand("Setmap").setExecutor(this);
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)){
sender.sendMessage("Only players can execute this command!");
return true;
}
Player p = (Player) sender;
Location b_loc = p.getLocation();
if(p.hasPermission("MurderRun.Setworld")){
Main.getConfig().set("Maps." + p.getName() + count + ".World", b_loc.getWorld().getName());
Main.saveConfig();
p.sendMessage(Utils.chat("&4Map Set"));
return true;
} else{
p.sendMessage("You do not have the required permissions to execute this command!");
}
return false;
}
}
You can't directly call the Main class, because it is not static. To call it, you should do this in your Setmap class and the constructor:
private Main plugin;
public SetmapCommand(Main plugin){
this.plugin = plugin;
plugin.getCommand("Setmap").setExecutor(this);
}
After you did this, you can use in your Setmap class:
plugin.saveConfig();

how to create CXF API for jbilling integration?

Can anyone tell me how to create CXF API? For jbilling integration, I want to create CXF API. But I don't know how to create it.
you can create a class in jbilling which call other evn and send headers and body as Json or string.
like this.
package com.cycle30.plugin.payment;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.log4j.Logger;
public class HttpJMSClient {
private PostMethod postMethod;
private String webUrl;
private List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
private static final Logger logger = Logger.getLogger(HttpJMSClient.class);
public HttpJMSClient() {
// TODO Auto-generated constructor stub
}
public void getConnection()
{
webUrl="http://localhost:8081";
nameValuePairs.add(new NameValuePair("x-force-user-id","abc1233"));
nameValuePairs.add(new NameValuePair("x-trans-id","123"));
}
public String makeCall( String body)
{
Object output=null;
try{
WebClient client = WebClient.create(webUrl);
for (NameValuePair h : nameValuePairs) {
client.header(h.getName(), h.getValue());
}
Response response = client.type(MediaType.APPLICATION_JSON).post(body,
Response.class);
logger.debug("Output from Server .... \n");
output = response.getEntity();
logger.debug(output);
System.out.println("my res: "+output.toString());
int statusCode = response.getStatus();
System.out.println("status code: "+statusCode);
return output.toString();
}catch(Exception e){
logger.error(e.getMessage());
logger.error(e.getCause());
}
return output.toString();
}
}

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources