TestNG can't set progammatic default test name - java

I'm trying with the following code to change the default test name, but still the value has remains as: default test name and not the test i set it to be:
TestNG testng = new TestNG();
XmlSuite suite = new XmlSuite();
suite.setName("Programmatic suite");
XmlTest xmlTest = new XmlTest(suite);
xmlTest.setName(testcase);
List<XmlClass> classes = new ArrayList<XmlClass>();
classes.add(new XmlClass(testsuite));
xmlTest.setXmlClasses(classes) ;
xmlTest.setName(testcase);
List<XmlTest> xmlTestsList = new ArrayList<XmlTest>();
xmlTestsList.add(xmlTest);
suite.setTests(xmlTestsList);
List<XmlSuite> suites = new ArrayList<XmlSuite>();
suites.add(suite);
testng.setXmlSuites(suites);
testng.setTestNames(Arrays.asList(testcase));
testng.setTestClasses(new Class[] { autotestClass });
testng.addListener(tla);
testng.run();

Ok, basically added the call to the method:
testng.setDefaultTestName("your default testname");
Also i needed to implement the interface:
IMethodInterceptor

Related

JMeter test from Java Code - Generate Console/File Reports matching GUI Reports

I run the jmx file from Java code and would like to get console/file reports.
public static void main(String[] args) throws Exception {
StandardJMeterEngine jmeter = new StandardJMeterEngine();
JMeterUtils.loadJMeterProperties("path/jmeter.properties");
JMeterUtils.setJMeterHome("path/jmeter");
JMeterUtils.initLocale();
SaveService.loadProperties();
File in = new File("test.jmx");
HashTree testPlanTree = SaveService.loadTree(in);
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
String logFile = "result.html";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
jmeter.configure(testPlanTree);
jmeter.run();
ReportGenerator generator = new ReportGenerator(logFile, null);
generator.generate();
}
Running this code I have a html file generated:
timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect
1632316570010,1745,Created,500,,Requests 1-1,text,false,,417,1228,1,1,https://my.url,1740,0,1371
But for example I need the report like on GUI - Aggregate Graph:
How can I achieve this?
EDIT: Running into Null Pointer exception with this code:
public static void main(String[] args) throws Exception {
StandardJMeterEngine jmeter = new StandardJMeterEngine();
JMeterUtils.loadJMeterProperties("bla/jmeter.properties");
JMeterUtils.setJMeterHome("bla/apache-jmeter-5.4.1");
JMeterUtils.initLocale();
File reportOutputDir = new File("report-output");
if (reportOutputDir.exists()) {
FileUtils.forceDelete(reportOutputDir);
}
File results = new File("result.html");
if (results.exists()) {
FileUtils.forceDelete(results);
}
JMeterUtils.setProperty("jmeter.reportgenerator.exporter.html.classname", "org.apache.jmeter.report.dashboard.HtmlTemplateExporter");
JMeterUtils.setProperty("jmeter.reportgenerator.exporter.html.property.output_dir","report-output\\dashboard");
SaveService.loadProperties();
HashTree testPlanTree = new ListedHashTree();
HTTPSampler httpSampler = new HTTPSampler();
httpSampler.setDomain("host");
httpSampler.setPort(443);
httpSampler.setPath("/api/v1/stock-count/created");
httpSampler.setMethod("POST");
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.addTestElement(httpSampler);
loopController.setFirst(true);
loopController.initialize();
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setNumThreads(10);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.initialize();
TestPlan testPlan = new TestPlan();
testPlan.addThreadGroup(threadGroup);
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
Summariser summer = new Summariser(summariserName);
ResultCollector logger = new ResultCollector(summer);
logger.setFilename("result.html");
testPlanTree.add(testPlan, logger);
jmeter.configure(testPlanTree);
jmeter.run();
ReportGenerator generator = new ReportGenerator("result.html", null);
generator.generate();
}
15:39:26.906 [main] INFO org.apache.jmeter.report.dashboard.JsonExporter - Creating statistics for overall
15:39:26.906 [main] DEBUG org.apache.jmeter.report.dashboard.JsonExporter - Creating statistics for result data:null
Exception in thread "main" java.lang.NullPointerException
at org.apache.jmeter.report.dashboard.JsonExporter.createStatistic(JsonExporter.java:121)
at org.apache.jmeter.report.dashboard.JsonExporter.export(JsonExporter.java:72)
at org.apache.jmeter.report.dashboard.ReportGenerator.exportData(ReportGenerator.java:379)
at org.apache.jmeter.report.dashboard.ReportGenerator.generate(ReportGenerator.java:257)
at com.nordstrom.inventory.test.api.passport.JMeterTest.main(JMeterTest.java:87)
It's not "html", it's JMeter's .jtl results file in CSV format.
If you want to see the "Aggregate Graph" - Open your result.html file using "Browse" button of the Aggregate Graph listener and it will load it and render the chart
You might also want to consider using i.e. JMeter Plugins Command Line Tool which allows generation of various tables/charts from command line (can be also done programatically if you have the .jars in your project CLASSPATH)
You might want to generate JMeter's HTML Reporting Dashboard, you're almost there, you just need to add a couple of lines to your script somewhere before test execution:
JMeterUtils.setProperty("jmeter.reportgenerator.exporter.html.classname", "org.apache.jmeter.report.dashboard.HtmlTemplateExporter");
JMeterUtils.setProperty("jmeter.reportgenerator.exporter.html.property.output_dir","report-output/dashboard");
and then go to report-output\dashboard folder and open index.html with your favourite browser.

How to get #tag from an excel file to CucumberOptions in Selenium java

Normally I would write a cucumber option as below:
#CucumberOptions(
features = "src\\main\\java\\feature"
, glue= "stepdefination",
plugin= {"com.cucumber.listener.ExtentCucumberFormatter:Report/Report.html"}
tags="#tag, #tag1, #sort"
)
public class TestRunner extends TestFunction {
#Test
public void runcukes( ) {
new TestNGCucumberRunner(getClass()).runCukes();
}
#BeforeClass
public void tags() {
}
#AfterClass
public void writeExtentReport() {
Reporter.loadXMLConfig("extent-config.xml");
}
}
My question is: How can I fetch #tag, #tag1, #sort from an excel file to #cucmberoptions and run the program in Selenium Java?
I am not sure about using cucumber options but by using cucumber RuntimeOptions class you can achieve it. The below method needs to be called in a loop that means you have 10 tags to execute then call this method in for loop.
public static boolean cucumberRun(String tag) {
try {
ClassLoader classLoader = CustomClass.class.getClassLoader();
ResourceLoader resourceLoader = new MultiLoader(classLoader);
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
/* Adding cucumber plugins */
List<String> pluginList = new ArrayList<String>();
pluginList.add("--plugin");
pluginList.add("html:target/cucumber-html-report");
pluginList.add("--plugin");
pluginList.add("json:target/cucumber.json");
pluginList.add("--plugin");
pluginList.add("com.cucumber.listener.ExtentCucumberFormatter:");
pluginList.add("--plugin");
pluginList.add("rerun:target/failedScenarios.txt");
/* Location for BDD extent report. */
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath("location/Extent_report.html");
/*
* Adding cucumberOptions.
*
* You can get the tag value from excel and pass it here. We need to add # before tag value.
*/
RuntimeOptions ro = new RuntimeOptions(pluginList);
ro.getFilters().add("#"+tag);
ro.getFeaturePaths().add("location of feature files");
ro.getGlue().add("location of glue code");
/* Loads all the resources into Cucumber RunTime class and execute. */
cucumber.runtime.Runtime runtime = new cucumber.runtime.Runtime(resourceLoader, classFinder, classLoader,
ro);
runtime.run();
}catch(Exception e){
// Handle exception
}

Selenium Webdriver create project jar

I need to run my project in other system(computer2) also through cmd what requirement need in (Computer2).
System.setProperty("webdriver.chrome.driver","Project1\\Driver\\chromedriver.exe);
driver=new ChromeDriver();
driver.get("http://www.gmail.net/");
driver.close();
These are the code and contain main method also
public class Mainpage
{
#SuppressWarnings("deprecation")
public static void main(String[] args) {
TestListenerAdapter t2=new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[]{login.class});
testng.addListener(t2);
testng.run();
}
}
It's unclear what error you're getting (or if you're even getting an error), but changing "http://www.gmail.net/" to "http://www.gmail.com/" might solve your issue.

Create TestNG.xml file dynamically and pass parameter

I have to execute test scripts using dynamic testng.xml file which means I have to create testng.xml file thru code and pass the parameters to the #Test methods pro grammatically.
For that I have created two Java files DynamicTestNG.java which should generate testng.xml file and run SampleClass.java where the #Test method has been written along with the parameters.
DynamicTestNG.java
public class DynamicTestNG {
public void runTestNGTest(Map<String,String> testngParams) {
//Create an instance on TestNG
TestNG myTestNG = new TestNG();
//Create an instance of XML Suite and assign a name for it.
XmlSuite mySuite = new XmlSuite();
mySuite.setName("MySuite");
//Create an instance of XmlTest and assign a name for it.
XmlTest myTest = new XmlTest(mySuite);
myTest.setName("MyTest");
//Add any parameters that you want to set to the Test.
myTest.setParameters(testngParams);
//Create a list which can contain the classes that you want to run.
List<XmlClass> myClasses = new ArrayList<XmlClass> ();
myClasses.add(new XmlClass("SampleClass"));
//Assign that to the XmlTest Object created earlier.
myTest.setXmlClasses(myClasses);
//Create a list of XmlTests and add the Xmltest you created earlier to it.
List<XmlTest> myTests = new ArrayList<XmlTest>();
myTests.add(myTest);
//add the list of tests to your Suite.
mySuite.setTests(myTests);
//Add the suite to the list of suites.
List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
mySuites.add(mySuite);
//Set the list of Suites to the testNG object you created earlier.
myTestNG.setXmlSuites(mySuites);
TestListenerAdapter tla = new TestListenerAdapter();
myTestNG.addListener(tla);
//invoke run() - this will run your class.
myTestNG.run();
}
public static void main (String args[])
{
DynamicTestNG dt = new DynamicTestNG();
//This Map can hold your testng Parameters.
Map<String,String> testngParams = new HashMap<String,String> ();
testngParams.put("searchtext1", "testdata1");
testngParams.put("searchtext2", "testdata2");
dt.runTestNGTest(testngParams);
}
}
And SampleClass.java
public class SampleClass {
private WebDriver driver;
#BeforeTest
public void setUp()
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\AK5040691\\Desktop\\IE driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://executeautomation.com/blog/custom-testng-library-for-appium/#more-1562");
}
//#Parameters({"searchText1","searchText2"})
//#Test
public void searchText(String text1, String text2)
{
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.className("search-field")).sendKeys(text1);
driver.findElement(By.className("search-field")).clear();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.className("search-field")).sendKeys(text2);
}
}
Its not running. Please let me know the mistake here.
You have to uncomment the #Test annotation in your SampleClass file. And if your SampleClass is in a package , then absolute package name + class name is to be specified in this statement.
myClasses.add(new XmlClass("com.some.package.SampleClass"));
Generally TestNG classes have a suffix or prefix labelled "Test" so that surefire plugin can include them in the execution flow, in case if you are using maven.
You can instead use the constructor with parameter of class object .
myClasses.add(new XmlClass(SampleClass.class));

How to remove custome properties from SOAPUI test case using java?

I have some custom properties for all the test cases in SoapUI.
I am able to delete using Groovy script step as described in below question:
How to remove Custom Properties from a SoapUI TestCase using Groovy?
testRunner.testCase.removeProperty( "Testcase_Property" );
But I wanted to delete these properties from JAVA. Below is the code I wrote:
String soapuiProjectPath = "ProjectLocation";
WsdlProject project = new WsdlProject(soapuiProjectPath);
StringToObjectMap context = new StringToObjectMap();
TestSuite testSuite = project.getTestSuiteByName("TestSuiteName");
WsdlTestSuite wsdlSuite = (WsdlTestSuite) testSuite;
List<TestCase> allTestCaseList = wsdlSuite.getTestCaseList();
for (TestCase testCase : allTestCaseList) {
WsdlTestCaseRunner testCaseRunner = new WsdlTestCaseRunner((WsdlTestCase) testCase, context);
List<TestProperty> testCasePropertyList = testCase.getPropertyList();
for (TestProperty testProperty : testCasePropertyList) {
WsdlTestRunContext runContext = testCaseRunner.getRunContext();
runContext.removeProperty(testProperty.getName());
}
}
System.out.println("Completed execution.");
project.save();
It is not throwing any exception. But not actually removing the custom properties as well.
Because you've to apply the removeProperty in WsdlTestCase not in WsdlTestRunContext. You can change your testCase loop code for something like:
for(TestCase testCase : allTestCaseList) {
List<TestProperty> testCasePropertyList = testCase.getPropertyList();
for (TestProperty testProperty : testCasePropertyList) {
((WsdlTestCase) testCase).removeProperty(testProperty.getName());
}
}
Hope it helps,

Categories

Resources