I have an automation project (Java, Maven with TestNG, log4j).
I am trying to create log file foreach test class (LoginTest would create LoginTest.log, HomeTest would create HomeTest.log , etc), I have implemeneted my own logger mechanism for this purpose but at the end of the run I am getting only the last class test log file (for the last test class that ran).
This is my logic:
public class TestLogger extends LoggerFormat {
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of(EnvConf.getDefaultTimeZone());
private final ThreadLocal<Map<String, List<String>>> testsLogMap = new ThreadLocal<>();
public void info(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.info(msg);
log(Level.INFO, context, msg);
}
public void error(ITestContext context, Throwable t, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.error(msg, t);
log(Level.ERROR, context, msg, t);
}
public void error(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.error(msg);
log(Level.ERROR, context, msg);
}
public void warn(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.warn(msg);
log(Level.WARN, context, msg);
}
public void warn(ITestContext context, Throwable t, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.warn(msg, t);
log(Level.WARN, context, msg, t);
}
public void debug(ITestContext context, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.debug(msg);
if (LoggerFactory.isDebug()) {
log(Level.DEBUG, context, msg);
}
}
public void debug(ITestContext context, Throwable t, String messageFormat, Object... args) {
String msg = handleFormatMsg(messageFormat, args);
super.debug(msg, t);
if (LoggerFactory.isDebug()) {
log(Level.DEBUG, context, msg, t);
}
}
private void log(Level level, ITestContext context, Object message, Throwable t) {
message = String.format("%s\n%s", message, throwableToString(t));
log(level, context, message);
}
private void log(Level level, ITestContext context, Object message) {
Map<String, List<String>> logsMap = getLogsMap();
if (!logsMap.containsKey(context.getName())) {
logsMap.put(context.getName(), new ArrayList<>());
}
logsMap.get(context.getName()).add(formatMsg(message, level));
if (level.toInt() != Level.DEBUG.toInt()) {
Reporter.log((String) message, 0);
}
}
private static String formatMsg(Object message, Level level) {
LocalDateTime dateTime = LocalDateTime.now(DEFAULT_ZONE_ID);
return String.format("[%s][%s]%s",
TIMESTAMP_FORMAT.format(dateTime),
level, message);
}
public List<String> getAndDeleteLogsByTest(String testName) {
return getLogsMap().remove(testName);
}
private Map<String, List<String>> getLogsMap() {
if (testsLogMap.get() == null) {
testsLogMap.set(new HashMap<>());
}
return testsLogMap.get();
}
private static String throwableToString(Throwable t) {
StringBuilder builder = new StringBuilder();
for (StackTraceElement traceElement : t.getStackTrace()) {
builder.append(traceElement.toString()).append('\n');
}
return builder.toString();
}
private static String handleFormatMsg(String message, Object... args) {
if (args.length == 0 && message.contains("%")) {
message = message.replaceAll("%", "%%");
}
return String.format(message, args);
}
}
this is my BaseTest Class:
#Listeners({NeoTestListener.class})
public class BaseTest {
private static final Browser BROWSER = Browser.valueOf(EnvConf.getProperty("ui.browser.type"));
private static final File SCREENSHOTS_FOLDER = new File(EnvConf.getProperty("test_output.screenshots.folder"));
// private static final File DOWNLOADS_FOLDER = new File(EnvConf.getProperty("workspace.tests.downloads"));
private static final File DOWNLOADS_FOLDER = new File(EnvConf.getProperty("test_output.logs.folder"));
private static final String ADMIN_USERNAME = EnvConf.getProperty("hackeruso.admin.user.email");
private static final String ADMIN_PASSWORD = EnvConf.getProperty("hackeruso.admin.user.password");
protected static DriverWrapper driver;
protected LoginPage loginPage;
protected Date testStartTime;
protected ITestContext context;
protected TopBar topBar;
protected final File testTempFolder;
static {
if (!SCREENSHOTS_FOLDER.exists()) {
FileUtil.createFolder(SCREENSHOTS_FOLDER, true);
}
if(!DOWNLOADS_FOLDER.exists()) {
FileUtil.createFolder(DOWNLOADS_FOLDER, false);
}
}
protected static String randSuffix(String prefix){
return prefix + "_" + String.valueOf(System.nanoTime()).substring(9);
}
public BaseTest() {
this.testTempFolder = new File(DOWNLOADS_FOLDER, randSuffix(getClass().getSimpleName()));
FileUtil.createFolder(testTempFolder, false);
// testTempFolder.deleteOnExit();
}
#BeforeClass
public final void baseSetup(ITestContext context) throws IOException {
this.context = context;
driver = DriverWrapper.open(BROWSER, DOWNLOADS_FOLDER);
loginPage = new LoginPage(driver);
info("<!!! '%s' START !!!>" , context.getName());
testStartTime = new Date();
this.context.setAttribute("test_start_time", testStartTime);
info("testStartTime=[%s]" , testStartTime);
}
private void printBrowserLog() {
List<LogEntry> serverLogLines = driver.manage().logs().get(LogType.BROWSER).getAll();
if (serverLogLines.size() > 0) {
Log.i("<---------Browser [SERVER] log start--------->");
for (LogEntry entry : serverLogLines) {
Log.e(entry.toString());
}
Log.i("<---------Browser [SERVER] log end------------>");
}
}
#AfterClass
public final void baseTeardown(ITestContext context) {
Date testEndTime = new Date();
if (driver != null) {
printBrowserLog();
driver.quit();
}
info("<!!! '%s' END !!!>" , context.getName());
info("testEndTime=[%s]" , testEndTime);
}
public static DriverWrapper getDriver() {
return driver;
}
protected void info(String message , Object...args){
TESTS_LOG.info(context , message , args);
}
public void error(Throwable t , String messageFormat , Object...args) {
TESTS_LOG.error(context , t , messageFormat , args);
}
public void error(String messageFormat , Object...args) {
TESTS_LOG.error(context , messageFormat , args);
}
protected void warn(String messageFormat , Object...args) {
TESTS_LOG.warn(context , messageFormat , args);
}
public void warn(Throwable t ,String messageFormat , Object...args) {
TESTS_LOG.warn(context , t , messageFormat , args);
}
protected void debug(String messageFormat , Object...args) {
TESTS_LOG.debug(context , messageFormat , args);
}
public void debug(Throwable t , String messageFormat , Object...args) {
TESTS_LOG.debug(context , t , messageFormat , args);
}
}
And this is my listener:
public class NeoTestListener implements ITestListener {
private final File SCREENSHOTS_FOLDER = new File(EnvConf.getProperty("test_output.screenshots.folder"));
private static final SimpleDateFormat FOLDER_NAME_FORMAT = new SimpleDateFormat("dd_MM_HH_mm_ss");
private static final SimpleDateFormat LOG_NAME_FORMAT = new SimpleDateFormat("dd_MM_HH_mm_ss");
private static final File TESTS_LOGS_FOLDER = new File(EnvConf.getProperty("test_output.logs.folder"));
static {
if (!TESTS_LOGS_FOLDER.exists()) {
FileUtil.createFolder(TESTS_LOGS_FOLDER, true);
}
}
private static String getTestMethodName(ITestResult iTestResult){
return iTestResult.getMethod().getConstructorOrMethod().getName();
}
#Attachment
public byte[] saveFailureScreenShot(DriverWrapper driver){
return driver.getScreenshotAsByte();
}
#Attachment(value = "{0}", type = "text/plain")
public static String saveTextLog(String message){
return message;
}
#Override
public void onStart(ITestContext context) {
context.setAttribute("WebDriver", getDriver());
}
#Override
public void onFinish(ITestContext context) {
}
#Override
public void onTestStart(ITestResult result) {
TESTS_LOG.info(result.getName() +" " + result.getTestClass() );
// TESTS_LOG.info("[Test: " + getTestClassName(result.getTestContext())+ " Started]");
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
TESTS_LOG.error(String.format("I am in onTestFailure method:=[%s] failed", getTestMethodName(result)));
Object testClass = result.getInstance();
DriverWrapper driver = getDriver();
takeScreenshot(getTestMethodName(result));
//Allure ScreenShot and SaveTestLog
TESTS_LOG.info(String.format("Screenshot for class=[%s], method=[%s]", getTestClassName(result.getTestContext()), getTestMethodName(result)));
saveFailureScreenShot(driver);
try {
saveLogTextFile(result);
} catch (IOException e) {
e.printStackTrace();
}
saveTextLog(getTestMethodName(result) + " failed and screenshot taken!");
}
#Attachment
private byte[] saveLogTextFile(ITestResult result) throws IOException {
return saveToLogFile(result.getTestContext());
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onTestFailedWithTimeout(ITestResult result) {
}
private void takeScreenshot(String filePrefix){
File dest = new File(SCREENSHOTS_FOLDER , filePrefix + "_" + FOLDER_NAME_FORMAT.format(new Date()) + ".png");
takeScreenshot(dest, getDriver());
}
private void takeScreenshot(File destFile, DriverWrapper driver){
File scrFile = driver.getScreenshotAsFile();
Path src = Paths.get(scrFile.toURI());
Path dest = Paths.get(destFile.toURI());
try {
Files.copy(src, dest , StandardCopyOption.REPLACE_EXISTING);
TESTS_LOG.info("[[ATTACHMENT|" + destFile.getAbsolutePath() + "]]");
} catch (IOException e) {
TESTS_LOG.error("Failed to save screen shot at file: " + destFile.getName());
TESTS_LOG.error(e.getMessage());
}
}
private byte[] saveToLogFile(ITestContext context) throws IOException {
File logFile = createLogFile(context);
boolean created = FileUtil.createNewFile(logFile);
if(created){
List<String> testLogLines = TESTS_LOG.getAndDeleteLogsByTest(context.getName());
if(testLogLines == null){
TESTS_LOG.error(context, "test=[%s] don't have any log lines!" , context.getName());
}else{
FileUtil.writeToFile(logFile.getAbsolutePath(), testLogLines);
}
}else{
TESTS_LOG.error(context, " failed to create test log file=[%s]", logFile.getAbsolutePath());
}
return FileUtils.readFileToByteArray(logFile);
}
private static File createLogFile(ITestContext context){
return new File(TESTS_LOGS_FOLDER, String.format("%s_%s.log",getTestClassName(context), LOG_NAME_FORMAT.format(context.getStartDate())));
}
private static String getTestClassName(ITestContext context){
return context.getAllTestMethods()[0].getInstance().getClass().getSimpleName();
}
}
This is a sample of class test in my environment:
public class ForgotPasswordTest extends BaseTest {
private String verifyEmailURL = "";
private static final String AUTOMATION_EMAIL= EnvConf.getProperty("automation.email.user");
private static final String AUTOMATION_EMAIL_PASSWORD=EnvConf.getProperty("automation.email.password");
private static final String AUTOMATION_WEBAPP_USER = "AUTOMATION_TESTER";
private ResetPasswordPage rpp;
private final static String NEW_PASSWORD = "1Qaz2wsx3edc";
private final static String ENVIRONMENT_BASE_URL = EnvConf.getProperty("base.url");
#BeforeClass
public void setup() {
topBar = new TopBar(driver);
rpp = new ResetPasswordPage(driver);
}
#Test(priority = 1)
public void navigateToLoginPage(){
loginPage.navigateAndVerify();
}
#Test(priority=2)
public void sendChangePasswordInstructions() {
ForgotPasswordPage fpp = loginPage.clickAndVerifyForgotPasswordButtonAction();
fpp.sendForgotPasswordInstructions(AUTOMATION_EMAIL);
Assert.assertTrue(loginPage.getForgotMsgAlertText().contains("Thank You, An Email Has Been Send"));
info("Sending forget password instructions phase is successful!");
}
#Test(priority=3)
public void verifyEmail(){
verifyEmailURL = "";
String regex = "href=\"([^\"]*)" ;
String from = "<SOME_URL>";
String subject = getSubject();
String msg = MailHelper.getMessagesFromGmail( AUTOMATION_EMAIL, AUTOMATION_EMAIL_PASSWORD, from, subject, testStartTime);
Pattern linkPattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(msg);
while (pageMatcher.find()) {
if (pageMatcher.group(1).contains("reset-password")) {
verifyEmailURL = pageMatcher.group(1);
verifyEmailURL = ENVIRONMENT_BASE_URL.concat("/").concat(verifyEmailURL.split("/")[3]);
info("Verify URL: " + verifyEmailURL);
}
}
info("Verifying email address is successful!");
}
#Test(priority = 4)
public void navigateToResetPasswordScreen(){
navigateTo(verifyEmailURL);
}
#Test(priority=5)
public void connectToUpdateNewPassword() {
rpp.changeNewPassword(NEW_PASSWORD);
info("Changing password is successful!");
}
#Test(priority=6)
public void verifyPasswordChanged() {
signIn(AUTOMATION_EMAIL, NEW_PASSWORD, true);
assertTrue(topBar.verifyExistenceTopBarNavigationItem(TopRightNavBarItem.SUPPORT));
info(String.format("Password for user=[%s] changed successfully", AUTOMATION_WEBAPP_USER));
}
private String getSubject(){
return "Reset Password";
}
}
Every time I run my program using mvn clean test I am not able to save the log for each test class it always saves me the last test class that was run and other log files not saved as expected.
what is missing ? I tried to search for a solution and tried various actions but I did not get the expected result.
The Maven Surefire plugin has the parameter <redirectTestOutputToFile> which creates the following files in target/surefire-reports in addition with a test project here:
igb.so.so65465538.FirstTest-output.txt:
println(): First test...
22:32:25.537 [main] INFO igb.so.so65465538.FirstTest - log.info(): First test...
igb.so.so65465538.SecondTest-output.txt:
println(): Second test...
22:32:25.561 [main] INFO igb.so.so65465538.SecondTest - log.info(): Second test...
Hi community: I'm facing the next issue: I'm working with Cucumber, Selenium WebDriver using Page Factory. The error getting here is from the Step Definition side:
java.lang.NullPointerException
at pages.page_First.startNavigation(page_First.java:33)
at stepdefs.stepdefs_First.iGoToGoogle(stepdefs_First.java:20)
at ✽.I go to Google (file:src/test/resources/features/first.feature:10)
This is the part of the code (StepDefinition) where issue occurs:
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
From the Page side, this is the code:
public class page_First extends BasePage {
public page_First() {
PageFactory.initElements(driver, this);
}
///////////////////////WEB ELEMENTS///////////////////////
#FindBy(name = "q")
private WebElement searchText;
#FindBy(name="btnK")
private WebElement searchButton;
//////////////////////BASE METHODS//////////////////////
public void startNavigation() {
driver.get(PropertyManager.getInstance().getURL());
}
public void search(String search) {
setTextAs(searchText, search);
}
public void enterButton (){
clickElement(searchButton);
}
}
The feature file:
Scenario Outline: Search google.com to verify google search is working
Given I go to Google
When I query for "<search>" cucumber spring selenium
And click search
Then google page title should become the first page
Examples:
| search |
| Cucumber Selenium |
This is my Browser class:
public class Browser {
// Take the instance of WebDriver
public static WebDriver driver;
public WebDriver initializeBrowser() throws IOException {
//Properties taken from config.properties
String browser = PropertyManager.getInstance().getBrowser();
if(browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if(browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if(browser.equals("ie")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if(browser.equals("edge")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
} else if(browser.equals("opera")) {
WebDriverManager.operadriver().setup();
driver = new OperaDriver();
} else {
System.setProperty("webdriver.safari.driver","/usr/bin/safaridriver");
driver = new SafariDriver();
}
System.out.println("-----> Proceed to initialize driver <-----");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
}
and here is my configuration property reader class:
public class PropertyManager {
private static PropertyManager instance;
private static final Object lock = new Object();
private static String propertyFilePath = System.getProperty("user.dir") + "//src//main//resources//data//config.properties";
///////////////////////////// DATA IN PROPERTIES //////////////////////////
private static String url;
private static String browser;
//Create a Singleton instance. We need only one instance of Property Manager.
public static PropertyManager getInstance () {
if (instance == null) {
synchronized (lock) {
instance = new PropertyManager();
instance.loadData();
}
}
return instance;
}
//Get all configuration data and assign to related fields.
private void loadData() {
//Declare a properties object
Properties prop = new Properties();
//Read config.properties file
try {
prop.load(new FileInputStream(propertyFilePath));
} catch (IOException e) {
System.out.println("Configuration properties file cannot be found");
}
//Get properties from config.properties
url = prop.getProperty("url");
browser = prop.getProperty("browser");
}
public String getURL () {
return url;
}
public String getBrowser () {
return browser;
}
}
I was forgetting this, my Step Definition class:
public class stepdefs_First {
private page_First page_first = PageFactory.initElements(Browser.driver, page_First.class);
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
#When("I query for {string} cucumber spring selenium")
public void iQueryForCucumberSpringSelenium(String search) throws Exception {
page_first.search(search);
}
#And("click search")
public void clickSearch() {
page_first.enterButton();
}
#Then("google page title should become the first page")
public void googlePageTitleShouldBecomeTheFirstPage() {
System.out.println("All OK");
}
}
By the way, this is my config.properties
browser = firefox
url = https://www.google.cl
Please I need your help.
Initialize the Page Object class
page_First page_first=new page_First();
I'm doing automation with Selenium - Page object Model & TestNG & Java. I have 2 testcases in 2 class files and i want to run all my tests in parallel
I passed driver and test object to all my pages.
When running my testng.xml with parallel="classes" two browser windows opened and only in one window, tests is running. The other window is closed. Eclipse showed me Null pointer exception.
Answer:
Later i understood that this is about usage of static in ExtentReport initialization. I corrected my code in reporter class.
Test Class-1:
public class CreateXCase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that X case is successfully created";
testcaseDec = "Create X Case";
category="Regression";
}
#Test(priority=2,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver, test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
}
Test Class-2:
public class CreateYcase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that Y case is successfully created";
testcaseDec = "Create Y Case";
category="Regression";
}
#Test(priority=1,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver,test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
SeleniumBase.java:
public class SeleniumBase extends Reporter implements Browser, Element
{
public static WebDriverWait wait;
#BeforeMethod(alwaysRun=true )
public void configureAndLaunch() throws IOException
{
driver = startApp(ReadPropertyFile.get("Browser"), ReadPropertyFile.get("URL"));
}
#Override
#AfterMethod (alwaysRun=true )
public void closeBrowser()
{
driver.quit();
}
#Override
public RemoteWebDriver startApp(String browser, String url)
{
try
{
if (browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("ie"))
{
System.setProperty("webdriver.ie.driver", "./drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.get(url);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
catch (Exception e)
{
int a = e.toString().indexOf("Exception:");
String str = e.toString().substring(0, a + 30);
System.out.println(str + "Exception captured");
System.err.println("The Browser Could not be Launched. Hence Failed");
}
finally
{
takeSnap();
}
return null;
}
Reporter.java:
public abstract class Reporter {
public RemoteWebDriver driver;
public ExtentHtmlReporter reporter;
public static ExtentReports extent;
public ExtentTest test;
public String testcaseName, testcaseDec, author ;
public String category="";
public static String excelFileName;
public static String extentreportpath;
#BeforeSuite (alwaysRun=true )
public void startReport(ITestContext c) throws IOException
{
String reportName=this.getClass().getName().substring(29, 33).toUpperCase() +" Screen Test Report";
String screenName=this.getClass().getName().substring(29, 33).toUpperCase() +" Tests";
String rptName="h5{font-size: 0px;}h5::after{content:\'"+screenName+"\';font-size: 1.64rem; line-height: 110%;margin: 0.82rem 0 0.656rem 0;}";
String suiteName = c.getCurrentXmlTest().getSuite().getName();
if (suiteName.contains("Default suite")||suiteName.contains("Failed suite"))
suiteName ="";
extentreportpath="./reports/"+suiteName+"Report.html";
reporter = new ExtentHtmlReporter(extentreportpath);
reporter.setAppendExisting(true);
extent = new ExtentReports();
extent.attachReporter(reporter);
reporter.loadXMLConfig(new File("./Resources/extent-config.xml"));
reporter.config().setTheme(Theme.DARK);
reporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
reporter.config().setReportName(reportName);
reporter.config().setCSS(rptName);
}
#BeforeClass(alwaysRun=true )
public ExtentTest report()
{
test = extent.createTest(testcaseName, testcaseDec);
test.assignAuthor(author);
return test;
}
public abstract long takeSnap();
public void reportStep(String desc,String status,boolean bSnap)
{
MediaEntityModelProvider img=null;
if(bSnap && !status.equalsIgnoreCase("INFO"))
{
long snapNumber=100000L;
snapNumber=takeSnap();
try
{
img=MediaEntityBuilder.createScreenCaptureFromPath("./../reports/images/"+snapNumber+".jpg").build();
}
catch(IOException e)
{
}
}
if(status.equalsIgnoreCase("pass"))
{
//test.pass(desc,img);
test.log(Status.PASS, desc, img);
}
else if(status.equalsIgnoreCase("fail"))
{
//test.fail(desc,img);
test.log(Status.FAIL, desc, img);
}
else if(status.equalsIgnoreCase("INFO"))
{
//test.pass(desc);
test.log(Status.INFO, desc,img);
}
}
public void reportStep(String desc,String status)
{
reportStep(desc,status,true);
}
#AfterSuite (alwaysRun=true )
public void stopReport() throws Exception
{
extent.flush();
}
}
Making the ExtentReport variable 'extent' as static solved my issue.
Eg: public static ExtentReports extent;
I modified the code in my question also.
Since i have only one #Test in a class, parallel="methods" is of no use in my case.
Please suggest me how to sent 3 users in 3 browsers for this field
driver.findElement(By.id(PropertiesConfiguration.getMyProperty("PinTextfield"))).sendKeys(PropertiesConfiguration.getMyProperty("user"));
// main class
public class TestHRWW {`main class`
protected WebDriver driver;
#Parameters("browser")`parameter for browser initialization`
#BeforeClass
public void setup(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("iexplorer")) {
System.setProperty("webdriver.ie.driver","Drivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver","Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
else {
throw new IllegalArgumentException("The Browser Type is Undefined");
}
driver.manage().window().maximize();
}
#BeforeMethod
public void open() {
driver.get("http://www.myhrasiapacific.com/");
}
#AfterClass
public void teardown() {
try {
driver.quit();
} catch (Exception e) {
driver = null;
}
}
// sub class
public class Login extends TestHRWW {`sub class`
String x;
static Logger logger = Logger.getLogger(Login.class.getName());
#Test
public void ClickLogon(WebDriver driver) throws InterruptedException, IOException {
driver.findElement(`enter code here`
By.id(PropertiesConfiguration.getMyProperty("logonbutton")))
.click();
Thread.sleep(2000);
// here i need to sent 3 differt users credentials
driver.findElement(
By.id(PropertiesConfiguration.getMyProperty("PinTextfield")))
.sendKeys(PropertiesConfiguration.getMyProperty("user"));
Thread.sleep(2000);
driver.findElement(
By.id(PropertiesConfiguration
.getMyProperty("passwordTextfield"))).sendKeys(
PropertiesConfiguration.getMyProperty("password"));
Thread.sleep(2000);
driver.findElement(
By.id(PropertiesConfiguration.getMyProperty("loginbutton")))
.click();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
}
You shall use TestNG #DataProvider to pass username & passwords
your login method will be like
#Test(dataProvider="dataForLogin")
public void ClickLogon(String userName,String password) {
}
#DataProvider(name="dataForLogin")
public static Object[][] prepareDataForLogin(){
// preparation of login data
}
If you are using QAF then you don't need to manually parse your json data and get rid from data provider class.
public class tDataHelper {
private static List<String> studentsToCreate = new ArrayList<String>();
static void parseData() throws Exception {
studentsToCreate.add("user1");
studentsToCreate.add("user2");
studentsToCreate.add("user3");
}
#DataProvider
public static Object[][] createStudents() {
Object[][] objArray = new Object[studentsToCreate.size()][];
for (int i = 0; i < studentsToCreate.size(); i++) {
objArray[i] = new Object[1];
objArray[i][0] = studentsToCreate.get(i);
}
return objArray;
}
}
public class testStudents {
private static tDataHelper helper = new tDataHelper();
#BeforeClass
public void setup() throws Exception {
tDataHelper.parseData();
}
#Test(dataProvider = "createStudents", dataProviderClass = tDataHelper.class)
public void testCreateStudents(String studentsToCreate) {
System.out.println(studentsToCreate);
}
}
QAF Test Data Driven
Basically, we have a class called OfficeManger which acts as a driver to connect to openoffice software, it needs to be connected all the time so we can use the converter to convert documents. We start the OpenOfficeProcess during the start of the web application, which starts fine. But looks like the executor which running in init() is on different thread and we couldn't able to get the running instance of OfficeManager. How to run in its own thread so that I can have this instance called from different class to use the converter method?
OfficeDocumentConverter converter = OpenOfficeProcessor.getInstance().getDocumentConverter();
converter.convert(inputFile, outputFile, pdf);
OpenOfficeProcessor
public class OpenOfficeProcessor {
private static final OpenOfficeProcessor INSTANCE = new OpenOfficeProcessor();
static ExecutorService executor = Executors.newSingleThreadExecutor();
private final OfficeManager officeManager;
private final OfficeDocumentConverter documentConverter;
public OpenOfficeProcessor(){
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
String homePath = ConfigurationManager.getApplicationProperty(ConfigurationManager.OPENOFFICE_HOME_PATH);
if(homePath != null){
configuration.setOfficeHome(homePath);
} else {
LOG.error("OpenOffice.home.path is not set in the properties file");
new Throwable("Please set OPENOFFICE.HOME.PATH parameter in the properties file");
}
String port = ConfigurationManager.getApplicationProperty(ConfigurationManager.OPENOFFICE_LISTENER_PORT);
if( port != null){
configuration.setPortNumber(Integer.parseInt(port));
}else {
LOG.error("openoffice.listener.port is not set in the properties file");
}
String executionTimeout = ConfigurationManager.getApplicationProperty(ConfigurationManager.OPENOFFICE_EXECUTION_TIMEOUT);
if(executionTimeout != null){
configuration.setTaskExecutionTimeout(Long.parseLong(executionTimeout));
}
String pipeNames = ConfigurationManager.getApplicationProperty(ConfigurationManager.OPENOFFICE_PIPES_NAMES);
if(ConfigurationManager.getApplicationProperty(ConfigurationManager.OPENOFFICE_PIPES_NAMES)!= null){
configuration.setPipeNames(pipeNames);
}
officeManager = configuration.buildOfficeManager();
documentConverter = new OfficeDocumentConverter(officeManager);
}
public static OpenOfficeProcessor getInstance()
{
return INSTANCE;
}
protected static void init() {
LOG.debug("Starting the open office listener...");
executor.submit(new Callable(){
#Override
public Object call() throws Exception {
OpenOfficeProcessor.getInstance().officeManager.start();
return null;
}
});
}
protected static void destroy() {
LOG.debug("Stopping the open office listener...");
OpenOfficeProcessor.getInstance().officeManager.stop();
}
public OfficeManager getOfficeManager() {
return officeManager;
}
public OfficeDocumentConverter getDocumentConverter() {
return documentConverter;
}
}
OfficeManager
public interface OfficeManager {
void execute(OfficeTask task) throws OfficeException;
void start() throws OfficeException;
void stop() throws OfficeException;
boolean isRunning();
}