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

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();
}
}

Related

NiFI "unable to find flowfile content"

I am using nifi 1.6 and get the following errors when trying to modify a clone of an incoming flowFile:
[1]"unable to find content for FlowFile: ... MissingFlowFileException
...
Caused by ContentNotFoundException: Could not find contetn for StandardClaim
...
Caused by java.io.EOFException: null"
[2]"FlowFileHandlingException: StandardFlowFileRecord... is not known in this session"
The first error occurs when trying to access the contents of the flow file, the second when removing the flow file from the session (within a catch of the first). This process is known to have worked under nifi 0.7.
The basic process is:
Clone the incoming flow file
Write to the clone
Write to the clone again (some additional formatting)
Repeat 1-3
The error occurs on the second iteration step 3.
An interesting point is that if immediately after the clone is performed, a session.read of the clone is done everything works fine. The read seems to reset some pointer.
I have created unit tests for this processor, but they do not fail in either case.
Below is code simplified from the actual version in use that demonstrates the issue. (The development system is not connected so I had to copy the code. Please forgive any typos - it should be close. This is also why a full stack trace is not provided.) The processor doing the work has a property to determine if an immediate read should be done, or not. So both scenarios can be performed easily. To set it up, all that is needed is a GetFile processor to supply the input and terminators for the output from the SampleCloningProcessor. A sample input file is included as well. The meat of the code is in the onTrigger and manipulate methods. The manipulation in this simplified version really don't do anything but copy the input to the output.
Any insights into why this is happening and suggestions for corrections will be appreciated - thanks.
SampleCloningProcessor.java
processor sample.package.cloning
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Arrays;
import java.util.Hashset;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.nifi.annotation.documentaion.CapabilityDescription;
import org.apache.nifi.annotation.documentaion.Tags;
import org.apache.nifi.componets.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessorContext;
import org.apache.nifi.processor.ProcessorSession;
import org.apache.nifi.processor.ProcessorInitioalizationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.io.InputStreamCalback;
import org.apache.nifi.processor.io.OutputStreamCalback;
import org.apache.nifi.processor.io.StreamCalback;
import org.apache.nifi.processor.util.StandardValidators;
import com.google.gson.Gson;
#Tags({"example", "clone"})
#CapabilityDescription("Demonsrates cloning of flowfile failure.")
public class SampleCloningProcessor extend AbstractProcessor {
/* Determines if an immediate read is performed after cloning of inoming flowfile. */
public static final PropertyDescriptor IMMEDIATE_READ = new PropertyDescriptor.Builder()
.name("immediateRead")
.description("Determines if processor runs successfully. If a read is done immediatly "
+ "after the clone of the incoming flowFile, then the processor should run successfully.")
.required(true)
.allowableValues("true", "false")
.defaultValue("true")
.addValidator(StandardValidators.BOLLEAN_VALIDATOR)
.build();
public static final Relationship SUCCESS = new Relationship.Builder().name("success").
description("No unexpected errors.").build();
public static final Relationship FAILURE = new Relationship.Builder().name("failure").
description("Errors were thrown.").build();
private Set<Relationship> relationships;
private List<PropertyDescriptors> properties;
#Override
public void init(final ProcessorInitializationContext contex) {
relationships = new HashSet<>(Arrays.asList(SUCCESS, FAILURE));
properties = new Arrays.asList(IMMEDIATE_READ);
}
#Override
public Set<Relationship> getRelationships() {
return this.relationships;
}
#Override
public List<PropertyDescriptor> getSuppprtedPropertyDescriptors() {
return this.properties;
}
#Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile incomingFlowFile = session.get();
if (incomingFlowFile == null) {
return;
}
try {
final InfileReader inFileReader = new InfileReader();
session.read(incomingFlowFile, inFileReader);
Product product = infileReader.getProduct();
boolean transfer = false;
getLogger().info("\tSession :\n" + session);
getLogger().info("\toriginal :\n" + incomingFlowFile);
for(int i = 0; i < 2; i++) {
transfer = manipulate(context, session, inclmingFlowFile, product);
}
} catch (Exception e) {
getLogger().error(e.getMessage(), e);
session.rollback(true);
}
}
private boolean manipuate(final ProcessContext context, final ProcessSession session
final FlowFile incomingFlowFile, final Product product) {
boolean transfer = false;
FlowFile outgoingFlowFile = null;
boolean immediateRead = context.getProperty(IMMEDIATE_READ).asBoolean();
try {
//Clone incoming flowFile
outgoinFlowFile = session.clone(incomingFlowFile);
getLogger().info("\tclone outgoing :\n" + outgoingFlowFile);
if(immediateRead) {
readFlowFile(session, outgoingFlowFile);
}
//First write into clone
StageOneWrite stage1Write = new StaeOneWrite(product);
outgoingFlowFile = session.write(outgoingFlowFile, stage1Write);
getLogger().info("\twrite outgoing :\n" + outgoingFlowFile);
// Format the cloned file with another write
outgoingFlowFile = formatFlowFile(outgoingFlowFile, session)
getLogger().info("\format outgoing :\n" + outgoingFlowFile);
session.transfer(outgoingFlowFile, SUCCESS);
transfer != true;
} catch(Exception e)
getLogger().error(e.getMessage(), e);
if(outgoingFlowFile ! = null) {
session.remove(outgoingFlowFile);
}
}
return transfer;
}
private void readFlowFile(fainl ProcessSession session, fianl Flowfile flowFile) {
session.read(flowFile, new InputStreamCallback() {
#Override
public void process(Final InputStream in) throws IOException {
try (Scanner scanner = new Scanner(in)) {
scanner.useDelimiter("\\A").next();
}
}
});
}
private FlowFile formatFlowFile(fainl ProcessSession session, FlowFile flowfile) {
OutputFormatWrite formatWrite = new OutputFormatWriter();
flowfile = session.write(flowFile, formatWriter);
return flowFile;
}
private static class OutputFormatWriter implement StreamCallback {
#Override
public void process(final InputStream in, final OutputStream out) throws IOException {
try {
IOUtils.copy(in. out);
out.flush();
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
private static class StageOneWriter implements OutputStreamCallback {
private Product product = null;
public StageOneWriter(Produt product) {
this.product = product;
}
#Override
public void process(final OutputStream out) throws IOException {
final Gson gson = new Gson();
final String json = gson.toJson(product);
out.write(json.getBytes());
}
}
private static class InfileReader implements InputStreamCallback {
private Product product = null;
public StageOneWriter(Produt product) {
this.product = product;
}
#Override
public void process(final InputStream out) throws IOException {
product = null;
final Gson gson = new Gson();
Reader inReader = new InputStreamReader(in, "UTF-8");
product = gson.fromJson(inreader, Product.calss);
}
public Product getProduct() {
return product;
}
}
SampleCloningProcessorTest.java
package sample.processors.cloning;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;
public class SampleCloningProcessorTest {
final satatic String flowFileContent = "{"
+ "\"cost\": \"cost 1\","
+ "\"description\": \"description","
+ "\"markup\": 1.2"
+ "\"name\":\"name 1\","
+ "\"supplier\":\"supplier 1\","
+ "}";
private TestRunner testRunner;
#Before
public void init() {
testRunner = TestRunner.newTestRunner(SampleCloningProcessor.class);
testRunner.enqueue(flowFileContent);
}
#Test
public void testProcessorImmediateRead() {
testRunner.setProperty(SampleCloningProcessor.IMMEDIATE_READ, "true");
testRunner.run();
testRinner.assertTransferCount("success", 2);
}
#Test
public void testProcessorImmediateRead_false() {
testRunner.setProperty(SampleCloningProcessor.IMMEDIATE_READ, "false");
testRunner.run();
testRinner.assertTransferCount("success", 2);
}
}
Product.java
package sample.processors.cloning;
public class Product {
private String name;
private String description;
private String supplier;
private String cost;
private float markup;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescriptione(final String description) {
this.description = description;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(final String supplier) {
this.supplier = supplier;
}
public String getCost() {
return cost;
}
public void setCost(final String cost) {
this.cost = cost;
}
public float getMarkup() {
return markup;
}
public void setMarkup(final float name) {
this.markup = markup;
}
}
product.json A sample input file.
{
"const" : "cost 1",
"description" : "description 1",
"markup" : 1.2,
"name" : "name 1",
"supplier" : "supplier 1"
}
Reported as a bug in Nifi. Being addressed by https://issues.apache.org/jira/browse/NIFI-5879

Cucumber Guice / Injector seems not to be thread-safe (Parallel execution / ExecutorService)

[long description warning]
I'm running some cucumber tests which have to be executed intercalated a defined server - for instance:
a.feature -> JBoss Server 1 | b.feature -> JBoss Serv. 2 | c.feature -> JB1 | etc.
For that, I created a hypothetical ExecutorService like this:
final ExecutorService executorService = Executors.newFixedThreadPool(2); //numberOfServers
for (Runnable task : tasks) {
executorService.execute(task);
}
executorService.shutdown();
try {
executorService.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
//doX();
}
The way that I manage about how will be the server chosen as liable to execute is:
inside of my Runnable class created for the executorService, I pass as a parameter a instanceId to a TestNG (XmlTest class) as below:
#Override
public void run() {
setupTest().run();
}
private TestNG setupTest() {
TestNG testNG = new TestNG();
XmlSuite xmlSuite = new XmlSuite();
XmlTest xmlTest = new XmlTest(xmlSuite);
xmlTest.setName(//irrelevant);
xmlTest.addParameter("instanceId", String.valueOf(instanceId));
xmlTest.setXmlClasses(..........);
testNG.setXmlSuites(..........);
return testNG;
}
Then, I get this just fine in a class that extends TestNgCucumberAdaptor:
#BeforeTest
#Parameters({"instanceId"})
public void setInstanceId(#Optional("") String instanceId) {
if (!StringUtils.isEmpty(instanceId)) {
this.instanceId = Integer.valueOf(instanceId);
}
}
And inside a #BeforeClass I'm populating a Pojo with this instanceId and setting the Pojo in a threadLocal attribute of another class. So far, so good.
public class CurrentPojoContext {
private static final ThreadLocal<PojoContext> TEST_CONTEXT = new ThreadLocal<PojoContext>();
...
public static PojoContext getContext(){
TEST_CONTEXT.get();
}
Now the problem really starts - I'm using Guice (Cucumber guice as well) in a 3rd class, injecting this pojo object that contains the instanceId. The example follows:
public class Environment {
protected final PojoContext pojoContext;
#Inject
public Environment() {
this.pojoContext = CurrentPojoContext.getContext();
}
public void foo() {
print(pojoContext.instanceId); // output: 1
Another.doSomething(pojoContext);
}
class Another{
public String doSomething(PojoContext p){
print(p.instanceId); // output: 2
}
}
}
Here it is not every time like this the outputs (1 and 2) but from time to time, I realized that the execution of different threads is messing with the attribute pojoContext. I know that is a little confusing, but my guess is that the Guice Injector is not thread-safe for this scenario - it might be a long shot, but I'd appreciate if someone else takes a guess.
Regards
Well, just in order to provide a solution for someone else, my solution was the following:
Create a class that maintains a Map with an identifier (unique and thread-safe one) as the key and a Guice Injector as value;
Inside my instantiation of Guice injector, I created my own module
Guice.createInjector(Stage.PRODUCTION, MyOwnModules.SCENARIO, new RandomModule());
and for this module:
public class MyOwnModules {
public static final Module SCENARIO = new ScenarioModule(MyOwnCucumberScopes.SCENARIO);
}
the scope defined here provides the following:
public class MyOwnCucumberScopes {
public static final ScenarioScope SCENARIO = new ParallelScenarioScope();
}
To sum up, the thread-safe will be in the ParallelScenarioScope:
public class ParallelScenarioScope implements ScenarioScope {
private static final Logger LOGGER = Logger.getLogger(ParallelScenarioScope.class);
private final ThreadLocal<Map<Key<?>, Object>> threadLocalMap = new ThreadLocal<Map<Key<?>, Object>>();
#Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
return new Provider<T>() {
public T get() {
Map<Key<?>, Object> scopedObjects = getScopedObjectMap(key);
#SuppressWarnings("unchecked")
T current = (T) scopedObjects.get(key);
if (current == null && !scopedObjects.containsKey(key)) {
current = unscoped.get();
scopedObjects.put(key, current);
}
return current;
}
};
}
protected <T> Map<Key<?>, Object> getScopedObjectMap(Key<T> key) {
Map<Key<?>, Object> map = threadLocalMap.get();
if (map == null) {
throw new OutOfScopeException("Cannot access " + key + " outside of a scoping block");
}
return map;
}
#Override
public void enterScope() {
checkState(threadLocalMap.get() == null, "A scoping block is already in progress");
threadLocalMap.set(new ConcurrentHashMap<Key<?>, Object>());
}
#Override
public void exitScope() {
checkState(threadLocalMap.get() != null, "No scoping block in progress");
threadLocalMap.remove();
}
private void checkState(boolean expression, String errorMessage) {
if (!expression) {
LOGGER.info("M=checkState, Will throw exception: " + errorMessage);
throw new IllegalStateException(errorMessage);
}
}
}
Now the gotcha is just to be careful regarding the #ScenarioScoped and the code will work as expected.

How to write TestNG to pass values from an excel sheet

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;
}
}

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");

NUnit is not showing Debug messages in its window

I'm using NUnit 262 and VS 2010.
This code should show messages writen with Debug.Writeline in the NUnit window, but it doen't.
The code:
public interface ILongRunningLibrary {
string RunForALongTime(int interval);
}
public class LongRunningLibrary : ILongRunningLibrary {
public string RunForALongTime(int interval) {
var timeToWait = interval * 1000; Thread.Sleep(timeToWait);
return string.Format("Waited {0} seconds", interval);
}
}
[TestFixture]
public class MoqExamples {
private Mock<ILongRunningLibrary> _longRunningLibrary;
[SetUp]
public void SetupForTest() {
_longRunningLibrary = new Mock<ILongRunningLibrary>();
}
[Test]
public void TestLongRunningLibrary() {
const int interval = 10;
var result = _longRunningLibrary.Object.RunForALongTime(interval);
Debug.WriteLine("Return from method was '" + result + "'");
}
[TearDown]
public void TearDownAfterTest() {
}
}
I should see this in the NUnit window:
But I see this instead:
When using Console.WriteLine, you'll see the output in the Text Output tab at the bottom of the test runner. I'm not sure if Debug.WriteLine puts it there as well. Have you checked?

Resources