无法调用“com.aventstack.extentreports.ExtentTest.info(String)”,因为“extentlisteners.ExtentListeners.test”为空

问题描述 投票:0回答:1

我正在学习 Selenium,主题是范围报告。现在,当我在框架中实现以前的代码时,我收到此错误。这段代码在重新启动 IDE 后可以工作,但现在不再工作了。 这是我的代码。

基础测试文件:

package base;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Duration;
import java.util.Properties;

import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.log4testng.Logger;

import extentlisteners.ExtentListeners;
import utilities.DbManager;
import utilities.ExcelReader;
import utilities.MonitoringMail;

public class BaseTest {
    
    public static WebDriver driver;
    public static Properties OR = new Properties();
    public static Properties config = new Properties();
    public static FileInputStream fis;
    public static ExcelReader excel = new ExcelReader("./src/test/resources/excel/testdata.xlsx");
    public static Logger log = Logger.getLogger(BaseTest.class);
    public static MonitoringMail mail = new MonitoringMail();
    public static WebDriverWait wait;
    
    
    //findEle finds the element based on the select type and enters the value : ID/Xpath/Css
    public void type(String key, String value) {
        
        if(key.endsWith("ID")) {
            driver.findElement(By.id(OR.getProperty(key))).sendKeys(value);;
        }else if(key.endsWith("XPATH")) {
            driver.findElement(By.xpath(OR.getProperty(key))).sendKeys(value);
        }else if(key.endsWith("CSS")) {
            driver.findElement(By.cssSelector(OR.getProperty(key))).sendKeys(value);
        }
        log.info("Typing in an Element : " + key + " , entered the values as : " + value);

        ExtentListeners.test.info("Typing in an Element : " + key + " , entered the values as : " + value); //Getting error on this line
        
    }
    
    //clickEle clicks on the element based on the select type : ID/Xpath/Css
    public void click(String key) {
        
        if(key.endsWith("ID")) {
            driver.findElement(By.xpath(OR.getProperty(key))).click();
        }else if(key.endsWith("XPATH")) {
            driver.findElement(By.xpath(OR.getProperty(key))).click();
        }else if(key.endsWith("CSS")) {
            driver.findElement(By.xpath(OR.getProperty(key))).click();
        }
        log.info("Clicking on element : " + key);
        ExtentListeners.test.info("Clicking on element : " + key);
        
    }
    
    
    @BeforeSuite
    public void setUp() {
        
        if(driver == null) {
            
            PropertyConfigurator.configure("./src/test/resources/properties/log4j.properties"); //Configuring Log4j
            log.info("Test Execution Started");
            
            
            try {
                fis = new FileInputStream("./src/test/resources/properties/config.properties"); //Loading config file into FIS
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } 
            try {
                config.load(fis); //Loading FIS to config properties
                log.info("config.properties file loaded");
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            
            try {
                fis = new FileInputStream("./src/test/resources/properties/OR.properties"); //Loading OR file into FIS
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } 
            try {
                OR.load(fis); //Loading FIS to OR properties
                log.info("config.properties file loaded");
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            
            //Launching browser by checking which browser to launch from config file
            if(config.getProperty("browser").equals("chrome")){
                driver = new ChromeDriver();
                log.info("Chrome browser launched");
            }
            else if(config.getProperty("browser").equals("firefox")){
                driver = new FirefoxDriver();
                log.info("Firefox browser launched");
            }
            
            
            //navigating to URL provided in config file
            driver.get(config.getProperty("testsiteurl"));
            log.info("Navigating to test site : " + config.getProperty("testsiteurl"));
            
            
            //Maximizing browser window
            driver.manage().window().maximize();
            
            //Applying Implicit wait
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(Integer.parseInt(config.getProperty("implicit.wait"))));
            
            //Applying Explicit wait
            wait = new WebDriverWait(driver, Duration.ofSeconds(Integer.parseInt(config.getProperty("explicit.wait"))));
            
            
            //JDBC Connection
            try {
                DbManager.setMysqlDbConnection();
                log.info("Database Connection established");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
    @AfterSuite
    public void tearDown() {
        driver.quit();
        log.info("Test Execution Completed");
    }

}

登录测试文件:

package testCases;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import base.BaseTest;

public class LoginTest extends BaseTest {
    
    @Test(dataProvider = "Data")
    public void doLogin(String username, String password) {
        
        type("username_ID",username);
        type("password_ID",password);
        click("loginBtn_XPATH");
        
    }
    
    @DataProvider(name="Data")
    public Object[][] getData() {
        
        String sheetName = "LoginTest";
        int rowNum = excel.getRowCount(sheetName);
        int colNum = excel.getColumnCount(sheetName);
        
        excel.getCellData(sheetName, colNum, rowNum);
        
        Object[][] data = new Object[rowNum-1][colNum];
        int row,col;
        for(row=2;row<=rowNum;row++){
            for(col=0;col<colNum;col++){
                data[row-2][col]=excel.getCellData(sheetName, col, row);
            }
        }
        return data;
        
    }

}

范围监听器:

package extentlisteners;

import java.util.Date;

import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.Markup;
import com.aventstack.extentreports.markuputils.MarkupHelper;



public class ExtentListeners implements ITestListener, ISuiteListener {

    static Date d = new Date();
    static String fileName = "Extent_" + d.toString().replace(":", "_").replace(" ", "_") + ".html";

    private static ExtentReports extent = ExtentManager
            .createInstance(".\\reports\\" + fileName);

    public static ExtentTest test;
    
    

    public void onTestStart(ITestResult result) {

        test = extent
                .createTest(result.getTestClass().getName() + "     @TestCase : " + result.getMethod().getMethodName());
    

    }

    public void onTestSuccess(ITestResult result) {

        String methodName = result.getMethod().getMethodName();
        String logText = "<b>" + "TEST CASE:- " + methodName.toUpperCase() + " PASSED" + "</b>";
        Markup m = MarkupHelper.createLabel(logText, ExtentColor.GREEN);
        test.pass(m);

    }

    public void onTestFailure(ITestResult result) {
        

        ///test.fail(result.getThrowable().getMessage());
        /*try {
            ExtentManager.captureScreenshot();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        String methodName=result.getMethod().getMethodName();
        String logText="<b>"+"TEST CASE:- "+ methodName.toUpperCase()+ " FAILED"+"</b>";        
    
    

        //test.fail("<b><font color=red>" + "Screenshot of failure" + "</font></b><br>",MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.fileName)
        //      .build());
    
        
        Markup m = MarkupHelper.createLabel(logText, ExtentColor.RED);
        test.log(Status.FAIL, m);
        
    }

    public void onTestSkipped(ITestResult result) {
        String methodName = result.getMethod().getMethodName();
        String logText = "<b>" + "Test Case:- " + methodName + " Skipped" + "</b>";
        Markup m = MarkupHelper.createLabel(logText, ExtentColor.AMBER);
        test.skip(m);

    }

    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
        // TODO Auto-generated method stub

    }

    public void onStart(ITestContext context) {

    }

    public void onFinish(ITestContext context) {

        if (extent != null) {

            extent.flush();
        }

    }

    public void onStart(ISuite suite) {
        // TODO Auto-generated method stub
        
    }

    public void onFinish(ISuite suite) {
        // TODO Auto-generated method stub
        
    }

}

我尝试对

ExtentListener
行进行注释,效果很好,因此在元素中提取或插入数据没有问题。这段代码工作过一次,所以我很困惑为什么它不工作并抛出这个错误。

错误信息:

失败:testCases.LoginTest.doLogin(“[电子邮件受保护]”,“kjsdfnvjndklsv”) java.lang.NullPointerException:无法调用“com.aventstack.extentreports.ExtentTest.info(String)”,因为“extentlisteners.ExtentListeners.test”为空 在base.BaseTest.type(BaseTest.java:64) 在 testCases.LoginTest.doLogin(LoginTest.java:13) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机方法) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) 在java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:568) 在 org.testng.internal.invokers.MethodInitationHelper.invokeMethod(MethodInitationHelper.java:139) 在 org.testng.internal.invokers.TestInvoker.invokeMethod(TestInvoker.java:664) 在 org.testng.internal.invokers.TestInvoker.invokeTestMethod(TestInvoker.java:227) 在 org.testng.internal.invokers.MethodRunner.runInSequence(MethodRunner.java:50) 在 org.testng.internal.invokers.TestInvoker$MethodInvokerAgent.invoke(TestInvoker.java:957) 在 org.testng.internal.invokers.TestInvoker.invokeTestMethods(TestInvoker.java:200) 在 org.testng.internal.invokers.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:148) 在 org.testng.internal.invokers.TestMethodWorker.run(TestMethodWorker.java:128) 在 java.base/java.util.ArrayList.forEach(ArrayList.java:1511) 在 org.testng.TestRunner.privateRun(TestRunner.java:848) 在 org.testng.TestRunner.run(TestRunner.java:621) 在 org.testng.SuiteRunner.runTest(SuiteRunner.java:443) 在 org.testng.SuiteRunner.runSequentially(SuiteRunner.java:437) 在 org.testng.SuiteRunner.privateRun(SuiteRunner.java:397) 在 org.testng.SuiteRunner.run(SuiteRunner.java:336) 在 org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) 在 org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:95) 在 org.testng.TestNG.runSuitesSequentially(TestNG.java:1280) 在 org.testng.TestNG.runSuitesLocally(TestNG.java:1200) 在 org.testng.TestNG.runSuites(TestNG.java:1114) 在 org.testng.TestNG.run(TestNG.java:1082) 在 org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115) 在 org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) 在 org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

java selenium-webdriver automated-tests testng extentreports
1个回答
0
投票

看起来你的代码没有任何问题。

“ExtentListeners.test”为空的原因可能仅与测试之前未运行onTestStart有关。

确保您的侦听器已添加到 TestNG XML 中:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="MyTestSuite">
    <listeners>
        <listener class-name="extentlisteners.ExtentListeners"/>
    </listeners>
    <test name="MyTest">
        <packages>
            <package name="testCases"/>
        </packages>
    </test>
</suite>

或者,如果您以编程方式创建套件,请不要忘记在那里添加您的侦听器:

    TestNG testng = new TestNG();
    testng.setTestClasses(new Class[] { LoginTest.class });
    testng.addListener(new ExtentListener());
    testng.run();

此外,您可以在 onTestStart 方法中的测试初始化行上设置断点,并在调试模式下执行测试以检查为其设置的值。

© www.soinside.com 2019 - 2024. All rights reserved.