0

我确实有一个用于登录功能的页面对象和测试类,同时将该测试登录方法调用到另一个测试类中,它显示空指针异常,该登录必须重用于不同的功能,它必须登录才能进入另一个功能。

        public class VerifySignIn extends BaseClass{
        public SignIn sign;
        public String expectedSignpage = "Checkmark Canada Cloud Payroll | 
        Dashboard";

        @Test(priority=1)
        public void VerifySigninpage() {
        try {
        test = report.startTest("Verify Signin Test");
        test.log(LogStatus.INFO, "Test Started" + test.getStartedTime());
        sign = PageFactory.initElements(driver, SignIn.class);
        sign.enterEmailID(userid);
        sign.enterPassword(pwd);
        sign.clickSigninBtn();
        String dashboardTitle = driver.getTitle();
        Assert.assertEquals(expectedSignpage, dashboardTitle);
        System.out.println("the title after signin is: "+dashboardTitle);
        } catch (Exception e) {
        System.out.println("Test signin not executed msg is: " + 
        e.getMessage());
        }
        }
        }

i have called that signin method in this class it show `NullPointerException` COULD ANYONE HELP ME,how to call `@test` method of one class into another `@test` method of another class.how to write sign-in functionality using `PageFactory` so it can reuse for different functionality.


public class VerifyAddOtherDeductions extends BaseClass {
public SignIn sign;
public AddOtherDeductions deductions;
String expectedtitle="Checkmark Canada Cloud Payroll | Deductions";

@Test(priority=1)
  public void verifySignIn() {
    try {
        test = report.startTest("Verify to signin Test");
        test.log(LogStatus.INFO, "Test Started" + test.getStartedTime());
        sign=PageFactory.initElements(driver, SignIn.class);
        sign.enterEmailID(userid);
        sign.enterPassword(pwd);
        sign.clickSigninBtn();
        String dashboardTitle = driver.getTitle();
        System.out.println("After signin page title is: "+dashboardTitle);
    } catch (Exception e) {
System.out.println("verify signin exception is: "+e.getMessage());
    }

}

@Test(priority=2)
public void verifyOtherDeductionsAddFromList() {
    test = report.startTest("Verify OtherDeductions Add From List Test");
    test.log(LogStatus.INFO, "Test Started" + test.getStartedTime());
    deductions=PageFactory.initElements(driver, AddOtherDeductions.class);
    deductions.companySetupClick();
    deductions.clickOtherDeductions();
    Assert.assertEquals(driver.getTitle(), expectedtitle);
    deductions.addFromListBtn();
    deductions.selectFromList();
    deductions.addList();
    deductions.confirmbtnclick();
    }


    package com.baseclass;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import com.utilities.ReadConfig;

public class BaseClass {
    ReadConfig readconfig = new ReadConfig();
    public String baseurl = readconfig.getApplicationURL();
    public String userid = readconfig.getUserId();
    public String pwd = readconfig.getPassword();
    public String departmentname=readconfig.departmentName();
    public WebDriver driver;
    public static Logger logger;

    public static String dest;
    public static String time;

    public static ExtentReports report;
    public static ExtentTest test;

    public static String takeScreenshot(WebDriver driver) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
            Date date = new Date();
            // System.out.println(dateFormat.format(date)); // 2016/11/16 12:08:43

            time = dateFormat.format(date);
            // System.out.println("Time is" + time);
            TakesScreenshot scrnshot = (TakesScreenshot) driver;
            File src = scrnshot.getScreenshotAs(OutputType.FILE);
            dest = System.getProperty("user.dir") + "\\Screenshots\\" + time + ".png";
            File destination = new File(dest);
            FileUtils.copyFile(src, destination);
            System.out.println("Screenshot taken");
        } catch (Exception e) {
            System.out.println("Screenshot error is :" + e.getMessage());
        }
        return dest;
    }

    @BeforeTest
    public void reportSetup() {
        try {
            DateTimeFormatter timelapse= DateTimeFormatter.ofPattern("yyyy.MM.dd.HH.mm.ss");
                        ZonedDateTime zone= ZonedDateTime.now();
                    String reportTime=  timelapse.format(zone);
            String repName = "Test-Report-" + reportTime + ".html";
            report = new ExtentReports(System.getProperty("user.dir") + "/ExtentReport/" + repName, true);
            report.addSystemInfo("HostName", "phani").addSystemInfo("Environment", "QA")
                    .addSystemInfo("User", "Ambadas").addSystemInfo("Project Name", "Automation Demo");
            report.loadConfig(new File(System.getProperty("user.dir") + "\\extent-config.xml"));
        } catch (Exception e) {
            System.out.println("Report issue is :" + e.getMessage());
        }

    }

    @AfterMethod
    public void getReport(ITestResult result) {
        try {
            String screenshot = takeScreenshot(driver);
            if (result.getStatus() == ITestResult.FAILURE) {

                test.log(LogStatus.FAIL, result.getThrowable());
                test.log(LogStatus.FAIL, "Below is the screen shot:-" + test.addScreenCapture(screenshot));
                test.log(LogStatus.FAIL, "Test Case Fail is:- " + result.getName());

            } else if (result.getStatus() == ITestResult.SUCCESS) {
                test.log(LogStatus.PASS, "Test Case pass is:- " + result.getName());
                //test.log(LogStatus.PASS, "Below is the screen shot:-" + test.addScreenCapture(screenshot));
            } else if (result.getStatus() == ITestResult.SKIP) {
                test.log(LogStatus.SKIP, "test Case skip is:- " + result.getName());
            } else if (result.getStatus() == ITestResult.STARTED) {
                test.log(LogStatus.INFO, "Test Case started");

            }
            report.endTest(test);
        } catch (Exception e) {

            System.out.println("Report generation exception is :" + e.getMessage());
        }

    }

    @AfterTest
    public void endTest() {
        report.flush();
        report.close();
    }

    @Parameters("browser")
    @BeforeClass
    public void baseSetup(String browser) {
        Logger.getLogger("Payroll");
        PropertyConfigurator.configure("log4j.properties");
        if (browser.equals("chrome")) {
            System.setProperty("webdriver.chrome.driver", readconfig.getChromePath());
            driver = new ChromeDriver();
        } else if (browser.equals("firefox")) {
            System.setProperty("webdriver.gecko.driver", readconfig.getFirefoxPath());
            driver = new FirefoxDriver();
        } else if (browser.equals("ie")) {
            System.setProperty("webdriver.chrome.driver", readconfig.getIEPath());
            driver = new InternetExplorerDriver();
        }

        driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get(baseurl);
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
    }

    @AfterClass
    public void tearDown() {
        driver.close();

}   

}

我在另一个测试类中提到了相同的登录方法,所以我提到了不同类的相同登录方法,任何帮助我如何调用登录方法而不是为不同的功能类编写冗长的代码

4

2 回答 2

0

我猜你传入了一个无效的浏览器参数,要么不是小写,要么不等于chromefirefox要么ie。如果传入的浏览器参数尚未设置/无法匹配,我已将您的代码调整为默认为 Firefox,并且我还强制传入的参数为小写以处理由于输入而导致的潜在错误Firefox

@Parameters("browser")
@BeforeClass
public void baseSetup(String browser) {
    //I assigned the logger here since it wasn't being done, you may not want to do this
    logger = Logger.getLogger("Payroll");
    PropertyConfigurator.configure("log4j.properties");
    switch (browser.toLowerCase()) {
        case "chrome": {
            //Setting a property like this is generally bad practice, you may be overwriting a property that has already been set on a build agent
            System.setProperty("webdriver.chrome.driver", readconfig.getChromePath());
            driver = new ChromeDriver();
            break;
        }
        case "ie": {
            //Setting a property like this is generally bad practice, you may be overwriting a property that has already been set on a build agent
            System.setProperty("webdriver.chrome.driver", readconfig.getIEPath());
            driver = new InternetExplorerDriver();
            break;
        }
        case "firefox": {
            //Setting a property like this is generally bad practice, you may be overwriting a property that has already been set on a build agent
            System.setProperty("webdriver.gecko.driver", readconfig.getFirefoxPath());
            driver = new FirefoxDriver();
            break;
        }
        default: {
            //Set a default of firefox, you can change this to whatever you want.
            logger.info(String.format("Unable to resolve %s, defaulting to `firefox`...", browser));
            //Setting a property like this is generally bad practice, you may be overwriting a property that has already been set on a build agent
            System.setProperty("webdriver.gecko.driver", readconfig.getFirefoxPath());
            driver = new FirefoxDriver();
        }
    }

    driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
    //Don't use implicit waits, use explicit waits instead.  Any checks to make sure a element does not exist will take 50 seconds
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
    driver.get(baseurl);
    driver.manage().window().maximize();
    driver.manage().deleteAllCookies();
}

@AfterClass
public void tearDown() {
    //Don't use driver.close() for cleanup!
    //It will throw an additional exception if the browser window has already been closed due to error
    driver.quit();
}

我添加了内联注释来解释我所做的更改并指出我可以看到的明显问题。这应该有望让您启动并运行并注销作为参数传入的值,browser以便您可以查看发送的内容(如果它不是预期值之一)。

于 2019-06-18T07:26:22.783 回答
0

在查看您的代码后,我有两种方法来处理这种情况:1)在 BaseClass 的@BeforeTest 中包含“VerifySigninpage”方法代码。默认情况下,可以在实际测试开始之前处理登录功能并执行特定的主页/任何其他页面测试,而不依赖于 SignIn 2) 将 SignIn 方法编写为单独的类中的实例方法,并通过创建 Object 在 @Test 方法中调用 SignIn 方法对于 LoginFunctionality 类

VerifySignIn page = new VerifySignIn();
page.SignIn();
于 2019-06-15T17:41:51.537 回答