How to write TestNG to pass values from an excel sheet - maven

What am I doing wrong??? I have no idea why the parameters aren't passed!!!
Am trying to pass the values from an external excel sheet... Please help!!
And guys please don't mark this as duplicate!!
Thanks in advance
P.S I am trying not to use maven..
import Data.Bean;
import org.easetech.easytest.annotation.DataLoader;
import org.easetech.easytest.annotation.Param;
import org.easetech.easytest.loader.LoaderType;
import org.easetech.easytest.runner.DataDrivenTestRunner;
import org.junit.runner.RunWith;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* #author Effitrac
*/
public class TestNGTestCases {
public TestNGTestCases() {
}
// TODO add test methods here.
// The methods must be annotated with annotation #Test. For example:
//
// #Test
// public void hello() {}
#BeforeClass
public static void setUpClass() throws Exception {
}
#AfterClass
public static void tearDownClass() throws Exception {
}
#BeforeMethod
public void setUpMethod() throws Exception {
}
#AfterMethod
public void tearDownMethod() throws Exception {
}
/**
*
*/
#RunWith(DataDrivenTestRunner.class)
#DataLoader(filePaths = {"d:/data/kishore/testdata.csv"}, loaderType = LoaderType.CSV)
public class TestExcelDataLoader {
Bean b = new Bean();
#Test
public void testwelcome(#Param(name = "name") String name, #Param(name = "custID") Integer custID) {
System.out.print("Executing getExcelTestData :");
// System.out.println("Name : " + name + " ID : " + custID);
b.setName(name);
b.setCustID(custID);
b.doit();
System.out.println("Name : " + b.getName() + " ID : " + b.getCustID() + " Result : " + b.getResult());
// System.out.println("Name : " + name + " ID : " + custID + " Result : " + b.getResult());
}
}
}
This is the Output I receive....
[TestNG] Running:
Command line suite
[VerboseTestNG] RUNNING: Suite: "Command line test" containing "1" Tests (config: null)
[VerboseTestNG] SKIPPED: "Command line test" - TestNGTestCases$TestExcelDataLoader.testwelcome(java.lang.String, java.lang.Integer) finished in 16 ms
[VerboseTestNG] org.testng.TestNGException:
[VerboseTestNG] Method testwelcome requires 2 parameters but 0 were supplied in the #Test annotation.
[VerboseTestNG]
[VerboseTestNG] ===============================================
[VerboseTestNG] Command line test
[VerboseTestNG] Tests run: 1, Failures: 0, Skips: 1
[VerboseTestNG] ===============================================
===============================================
Command line suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Java Result: 2
Deleting directory C:\Users\Effitrac\AppData\Local\Temp\TestNGTestCases
test:
BUILD SUCCESSFUL (total time: 6 seconds)

Not sure why do you need to use third party library to run TestNG with DataDrivenTestRunner.class. Below works well for all the cases without any issues. Also why did you create TestNGTestCases class as neither you are extending it nor adding any tests to it.
package practise;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
public class SO34677983 {
#Test(dataProvider = "dp")
public void f(Integer CustId, String Name) {
System.out.println("Verifying something here");
}
#DataProvider
public Object[][] dp() throws IOException {
File csvRead = new File("someFilePath.csv");
BufferedReader br = new BufferedReader(new FileReader(csvRead));
String line = "";
Object[][] data = new Object[2][2];
int dataNum = 0;
while ((line = br.readLine()) != null) {
data[dataNum][0] = line.split(",")[0];
data[dataNum][1] = line.split(",")[1];
dataNum++;
}
br.close();
return data;
}
}

Related

extent report only shows the last run result for testng maven selenium java framework

I am using testng 6.9.10, extentreports 3.1.5. Using maven surefire plugin and using forkcount and reuse forks , the tests running in parallel. (i.e two instances of chrome browser opening with two tests classes running in parallel as I set forkcount -> 2 and reuseforks-> true)
mvn test -Dgroups=group1
( there are two test classes belong to group1). The problem is extent report only shows the result of the last run.
I've included only the listener class in pom.xml ( not anywhere else, Not in the #beforeclass or #afterclass as part of BaseTest class)
<property>
<name>listener</name>
<value>util.listener.TestExtentListener</value>
</property>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<forkCount>2</forkCount>
<reuseForks>true</reuseForks>
Any solution please?
public class ExtentManager {
private static ExtentReports extent;
private static String reportFileName = "Test-Automaton-Report"+".html";
private static String fileSeperator = System.getProperty("file.separator");
private static String reportFilepath = System.getProperty("user.dir") +fileSeperator+ "TestReport";
private static String reportFileLocation = reportFilepath +fileSeperator+ reportFileName;
public static ExtentReports getInstance() {
if (extent == null)
createInstance();
return extent;
}
//Create an extent report instance
public static ExtentReports createInstance() {
String fileName = getReportPath(reportFilepath);
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(reportFileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(reportFileName);
htmlReporter.config().setTimeStampFormat("EEEE, MMMM dd, yyyy, hh:mm a '('zzz')'");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
//Set environment details
extent.setSystemInfo("OS", "Mac");
extent.setSystemInfo("AUT", "QA");
return extent;
}
//Create the report path
private static String getReportPath (String path) {
File testDirectory = new File(path);
if (!testDirectory.exists()) {
if (testDirectory.mkdir()) {
System.out.println("Directory: " + path + " is created!" );
return reportFileLocation;
} else {
System.out.println("Failed to create directory: " + path);
return System.getProperty("user.dir");
}
} else {
System.out.println("Directory already exists: " + path);
}
return reportFileLocation;
}
}
public class ExtentTestManager {
static Map<Integer, ExtentTest> extentTestMap = new HashMap<Integer, ExtentTest>();
static ExtentReports extent = ExtentManager.getInstance();
public static synchronized ExtentTest getTest() {
return (ExtentTest) extentTestMap.get((int) (long) (Thread.currentThread().getId()));
}
public static synchronized void endTest() {
extent.flush();
}
public static synchronized ExtentTest startTest(String testName) {
ExtentTest test = extent.createTest(testName);
extentTestMap.put((int) (long) (Thread.currentThread().getId()), test);
return test;
}
}
public class TestExtentListener implements ITestListener {
ExtentTest test;
private static ThreadLocal<ExtentTest> extentTestThreadLocal = new ThreadLocal<ExtentTest>();
public void onStart(ITestContext context) {
System.out.println("*** Test Suite " + context.getName() + " started ***");
}
public void onFinish(ITestContext context) {
System.out.println(("*** Test Suite " + context.getName() + " ending ***"));
ExtentTestManager.endTest();
ExtentManager.getInstance().flush();
}
public void onTestStart(ITestResult result) {
System.out.println(("*** Running test method " + result.getMethod().getMethodName() + "..."));
test = ExtentTestManager.startTest(result.getMethod().getMethodName());
extentTestThreadLocal.set(test);
}
public void onTestSuccess(ITestResult result) {
System.out.println("*** Executed " + result.getMethod().getMethodName() + " test successfully...");
extentTestThreadLocal.get().log(Status.PASS, "Test passed");
}
public void onTestFailure(ITestResult result) {
System.out.println("*** Test execution " + result.getMethod().getMethodName() + " failed...");
extentTestThreadLocal.get().log(Status.FAIL, "Test Failed");
}
public void onTestSkipped(ITestResult result) {
System.out.println("*** Test " + result.getMethod().getMethodName() + " skipped...");
extentTestThreadLocal.get().log(Status.SKIP, "Test Skipped");
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
System.out.println("*** Test failed but within percentage % " + result.getMethod().getMethodName());
}
}
you might not be using thread local class in java to make extent report thread safe. Otherwise objects will get overridden and extent report only shows the active tests results.
You can do something like this:
ExtentReports extent = ExtentReportGenerator.ExtentReport();
ExtentTest test;;
private static ThreadLocal<ExtentTest> extent_test = new ThreadLocal<ExtentTest>();
For more details, you can refer to this blog.
https://www.automationinja.com/post/thread-safe-extent-report-in-selenium
If you use xml file to your testclasses all report will appear in extent report
This is my XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TC_WorldAirFares Automation Test Suite">
<listeners>
<listener class-name="ExtentReports.ExtentReporterNG" />
</listeners>
<suite name="Suite" parallel="instances" thread-count="2">
<test name="TC Automation Test Suite">
<classes>
<class name="Footerlinks" />
<class name="HeaderLinks" />
<class name="BookYourFlightsNow" />
</classes>
</test>
</suite>
keep class for extentreports
here extent report class (XML file listen your extentreport class and generate reports for you test classes
package ExtentReports;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class ExtentReporterNG implements IReporter {
private ExtentReports extent;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
String outputDirectory) {
extent = new ExtentReports(outputDirectory + File.separator
+ "Extent.html", true);
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}
private void buildTestNodes(IResultMap tests, LogStatus status) {
ExtentTest test;
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.startTest(result.getMethod().getMethodName());
test.setStartedTime(getTime(result.getStartMillis()));
test.setEndedTime(getTime(result.getEndMillis()));
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
} else {
test.log(status, "Test " + status.toString().toLowerCase()
+ "ed");
}
extent.endTest(test);
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}

jmeter echo server test in tcp and beanshall solve

2017-08-08 15:41:59,915 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: import java.io.*; import org.apache.jmeter.protocol.tcp.sampler.*; import java.u . . . '' : Typed variable declaration : Object constructor
2017-08-08 15:41:59,915 WARN o.a.j.m.BeanShellPreProcessor: Problem in BeanShell script. org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of:import java.io.; import org.apache.jmeter.protocol.tcp.sampler.; import java.u . . . '' : Typed variable declaration : Object constructor
1
I would like to test the server with jmeter from echo server. Once it was sent to the server, it was successful. But the class I use is only a number. How to get a sentence in the jmeter?? this is first question.
The second problem can be seen from the photograph. response message is ok but i have beanshall error in the code. How to fix that?
`
package org.apache.jmeter.protocol.tcp.sampler;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.util.JOrphanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LengthPrefixedBinaryTCPClientImpl extends
TCPClientDecorator {
private static final Logger log =
LoggerFactory.getLogger(LengthPrefixedBinaryTCPClientImpl.class);
private final int lengthPrefixLen = JMeterUtils.getPropDefault("tcp.binarylength.prefix.length", 2);
public LengthPrefixedBinaryTCPClientImpl() {
super(new BinaryTCPClientImpl());
tcpClient.setEolByte(Byte.MAX_VALUE+1);
}
#Override
public void write(OutputStream os, String s) throws IOException{
os.write(intToByteArray(s.length()/2,lengthPrefixLen));
if(log.isDebugEnabled()) {
log.debug("Wrote: " + s.length()/2 + " bytes");
}
this.tcpClient.write(os, s);
}
#Override
public void write(OutputStream os, InputStream is) throws IOException {
this.tcpClient.write(os, is);
}
#Override
public String read(InputStream is) throws ReadException{
byte[] msg = new byte[0];
int msgLen = 0;
byte[] lengthBuffer = new byte[lengthPrefixLen];
try {
if (is.read(lengthBuffer, 0, lengthPrefixLen) == lengthPrefixLen) {
msgLen = byteArrayToInt(lengthBuffer);
msg = new byte[msgLen];
int bytes = JOrphanUtils.read(is, msg, 0, msgLen);
if (bytes < msgLen) {
log.warn("Incomplete message read, expected: "+msgLen+" got:
"+bytes);
}
}
String buffer = JOrphanUtils.baToHexString(msg);
if(log.isDebugEnabled()) {
log.debug("Read: " + msgLen + "\n" + buffer);
}
return buffer;
}
catch(IOException e) {
throw new ReadException("", e, JOrphanUtils.baToHexString(msg));
}
}
/**
* Not useful, as the byte is never used.
* <p>
* {#inheritDoc}
*/
#Override
public byte getEolByte() {
return tcpClient.getEolByte();
}
/**
* {#inheritDoc}
*/
#Override
public void setEolByte(int eolInt) {
throw new UnsupportedOperationException("Cannot set eomByte for prefixed
messages");
}
}`

Error Handling Spring JdbcTemplate batchUpdate

I am trying to update thousands of rows in a table using batchUpdate. My requirements are:
1) Assume there are 1000 records in a batch. Record No 235 caused an error. How do I find out which record caused the error.
2) Assume that record 600 did not result in an update (reason could be no record matching the where clause). How can I find out records that did not result in an update.
3) In both scenarios above how can I continue processing the remaining records.
The only solution after long search and debug is to go to BatchUpdateException class and find the negative element and deduce the value of the insertion that is in error from the MAP.
import java.sql.BatchUpdateException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
#Repository("dao_")
public class YouDao extends CommunDao implements IyouDao {
public void bulkInsert(final List<Map<String, String>> map)
throws BusinessException {
try {
String sql = " insert into your_table " + "( aa,bb )"
+ "values " + "( ?,? )";
BatchPreparedStatementSetter batchPreparedStatementSetter = new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i)
throws SQLException {
Map<String, String> bean = map.get(i);
ps.setString(1, bean.get("aa"));
ps.setString(2, bean.get("bb"));
//..
//..
}
#Override
public int getBatchSize() {
return map.size();
}
};
getJdbcTemplate().batchUpdate(sql, batchPreparedStatementSetter);
}
catch (Exception e) {
if (e.getCause() instanceof BatchUpdateException) {
BatchUpdateException be = (BatchUpdateException) e.getCause();
int[] batchRes = be.getUpdateCounts();
if (batchRes != null && batchRes.length > 0) {
for (int index = 0; index < batchRes.length; index++) {
if (batchRes[index] == Statement.EXECUTE_FAILED) {
logger.error("Error execution >>>>>>>>>>>"
+ index + " --- , codeFail : " + batchRes[index]
+ "---, line " + map.get(index));
}
}
}
}
throw new BusinessException(e);
}
}
}
int[] rows =jdbcTemplate.batchUpdate(TbCareQueryConstant.SQL_UPDATE_BANKDETAILS_OF_USER, new BatchPreparedStatementSetter(){
.....
your code
}
for(int i=0 ; i < rows.length ; i++){
if(rows[i] == 0){
}
}

Not getting result when ran the Nashorn program

I am new to Nashorn, I am trying to write one program and try to ran that program but i am getting the result after ran the program.Please find my code is below.
package com.nashron;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvokScriptObjectMethod {
public static void main(String[] args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
try {
engine.eval(new FileReader("src/script/Script.js"));
} catch (ScriptException | FileNotFoundException ex) {
}
}
}
JS:
var Script = Java.type("com.nashron.Script");
var var1 = new Script("who am i");
return var1.get("I am Amar");
Java :
package com.nashron;
public class Script {
public Script() {
}
public Script(String arg1) {
this.var1 = arg1;
System.out.println("this is contructor");
}
private String var1;
public String get(String arg1) {
System.out.println("this is return statement");
return this.var1 + arg1;
}
}
here I want to get the return value.
Thanks in Advance
A top level script cannot have "return" statements. This is as per ECMAScript specification. Your program will result in ScriptException being thrown - as there is a return statement in your JS code (at top level). If you just remove return, the last evaluated expression is returned from engine.eval call.
Example:
File: Main.java
import javax.script.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
Object val = e.eval(new FileReader("x.js"));
System.out.println(val);
}
}
File: x.js
java.lang.System.getProperty("os.name");

Converting MapWritable to a string in Hadoop

When I run my output with the toString() method I am getting:
#zombie org.apache.hadoop.io.MapWritable#b779f586
#zombies org.apache.hadoop.io.MapWritable#c8008ef9
#zona org.apache.hadoop.io.MapWritable#99e061a1
#zoology org.apache.hadoop.io.MapWritable#9d0060be
#zzp org.apache.hadoop.io.MapWritable#3e52c108
Here is my reducer code, how can I get the map values to print out instead?
package sample;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Reducer;
public class IntSumReducer
extends Reducer<Text,MapWritable,Text,MapWritable> {
private MapWritable result = new MapWritable();
String temp = "";
public void reduce(Text key, Iterable<MapWritable> values, Context context)throws IOException, InterruptedException {
result.clear();
for (MapWritable val : values) {
Iterable<Writable> keys = val.keySet();
for (Writable k : keys) {
IntWritable tally = (IntWritable) val.get(k);
if (result.containsKey(k)) {
IntWritable tallies = (IntWritable) result.get(k);
tallies.set(tallies.get() + tally.get());
temp = toString() + " : " + tallies.get();
result.put(new Text(temp), tallies);
} else {
temp = k.toString() + " : " + tally.get();
result.put(new Text(temp), tally);
}
}
}
context.write(key, result);
}
}
Thanks for the help
Adding a class like this should work:
class MyMapWritable extends MapWritable {
#Override
public String toString() {
StringBuilder result = new StringBuilder();
Set<Writable> keySet = this.keySet();
for (Object key : keySet) {
result.append("{" + key.toString() + " = " + this.get(key) + "}");
}
return result.toString();
}
}
Then call it like so:
MyMapWritable mw = new MyMapWritable();
mw.toString();
Your result is a MapWritable, and the toString() method is not overridden in MapWritable.
You can create new class that extends MapWritable and create your own toString() method in it.
Change your code after that to :
public class IntSumReducer extends Reducer<Text,MapWritable,Text,YourMapWritable> {
private YourMapWritable result = new YourMapWritable();
String temp = "";
...

Resources