目錄
问题内容
解决方法
首頁 Java 無法呼叫'com.aventstack.extentreports.ExtentTest.info(String)”,因為'extentlisteners.ExtentListeners.test”為空

無法呼叫'com.aventstack.extentreports.ExtentTest.info(String)”,因為'extentlisteners.ExtentListeners.test”為空

Feb 11, 2024 pm 04:39 PM
webdriver

在PHP开发中,我们经常会遇到各种问题和错误提示。其中一个常见的问题是“无法调用‘com.aventstack.extentreports.ExtentTest.info(String)’,因为‘extentlisteners.ExtentListeners.test’为空”。这个错误提示可能让人感到困惑,不知道如何解决。在本文中,php小编百草将为大家解析这个问题的原因,并提供解决方法,帮助大家顺利解决这个错误。

问题内容

我正在学习 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 行,它工作正常,因此提取数据或将数据插入到元素中没有问题。这段代码工作过一次,所以我很困惑为什么它不工作并抛出这个错误。

错误消息:

FAILED: testCases.LoginTest.doLogin("[email&#160;protected]", "kjsdfnvjndklsv")
java.lang.NullPointerException: Cannot invoke "com.aventstack.extentreports.ExtentTest.info(String)" because "extentlisteners.ExtentListeners.test" is null
at base.BaseTest.type(BaseTest.java:64)
at testCases.LoginTest.doLogin(LoginTest.java:13)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.testng.internal.invokers.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:139)
at org.testng.internal.invokers.TestInvoker.invokeMethod(TestInvoker.java:664)
at org.testng.internal.invokers.TestInvoker.invokeTestMethod(TestInvoker.java:227)
at org.testng.internal.invokers.MethodRunner.runInSequence(MethodRunner.java:50)
at org.testng.internal.invokers.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:957)
at org.testng.internal.invokers.TestInvoker.invokeTestMethods(TestInvoker.java:200)
at org.testng.internal.invokers.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:148)
at org.testng.internal.invokers.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:848)
at org.testng.TestRunner.run(TestRunner.java:621)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:443)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:437)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:397)
at org.testng.SuiteRunner.run(SuiteRunner.java:336)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:95)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1280)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1200)
at org.testng.TestNG.runSuites(TestNG.java:1114)
at org.testng.TestNG.run(TestNG.java:1082)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
登入後複製

解决方法

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

“extentlisteners.test”为 null 的原因可能仅与 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 方法中的测试初始化​​行上设置断点,并在调试模式下执行测试以检查为其设置的值。

以上是無法呼叫'com.aventstack.extentreports.ExtentTest.info(String)”,因為'extentlisteners.ExtentListeners.test”為空的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
Python與WebDriver擴充:在網頁中模擬滑鼠滾輪操作 Python與WebDriver擴充:在網頁中模擬滑鼠滾輪操作 Jul 09, 2023 pm 11:55 PM

Python和WebDriver擴充:在網頁中模擬滑鼠滾輪操作引言:隨著網頁互動設計的不斷發展,模擬使用者操作在自動化測試中變得越來越重要。在一些網頁上,滑鼠滾輪的使用已經成為了常見的操作之一。然而,對於使用Python編寫自動化測試腳本的開發人員來說,如何在WebDriver中模擬滑鼠滾輪操作可能會成為一個挑戰。本文將介紹一種使用Python和WebDriv

使用Python和WebDriver實現網頁截圖並儲存為PDF文件 使用Python和WebDriver實現網頁截圖並儲存為PDF文件 Jul 08, 2023 pm 10:55 PM

使用Python和WebDriver實作網頁截圖並儲存為PDF文件摘要:在Web開發和測試過程中,經常需要對網頁進行截圖以便進行分析、記錄和報告。本文將介紹如何使用Python和WebDriver來實現網頁截圖,並將截圖儲存為PDF文件,以方便分享和存檔。一、安裝與設定SeleniumWebDriver:安裝Python:造訪Python官網(https:

使用Python和WebDriver實作網頁自動填寫驗證碼 使用Python和WebDriver實作網頁自動填寫驗證碼 Jul 07, 2023 am 10:19 AM

使用Python和WebDriver實現網頁自動填寫驗證碼隨著網路的發展,越來越多的網站在用戶註冊、登入等操作中引入了驗證碼機制,以提高安全性和防止自動化攻擊。然而,手動輸入驗證碼不僅麻煩,還增加了使用者體驗的複雜度。那麼,有沒有一種方法能夠自動填入驗證碼呢?答案是肯定的。本文將介紹如何使用Python和WebDriver實作網頁自動填入驗證碼的方法。首先,我

使用Python和WebDriver實現網頁自動刷新 使用Python和WebDriver實現網頁自動刷新 Jul 08, 2023 pm 01:46 PM

使用Python和WebDriver實現網頁自動刷新引言:在日常的網頁瀏覽中,我們常常會遇到需要頻繁刷新網頁的場景,例如監控即時資料、自動刷新動態頁面等。手動刷新網頁會浪費大量的時間和精力,因此我們可以使用Python和WebDriver來實現自動刷新網頁的功能,並提高我們的工作效率。一、安裝和配置環境在開始之前,我們需要安裝和配置對應的環境。安裝Python

Python和WebDriver擴充:在網頁中模擬滑鼠右鍵點擊 Python和WebDriver擴充:在網頁中模擬滑鼠右鍵點擊 Jul 07, 2023 am 11:22 AM

Python和WebDriver擴充:在網頁中模擬滑鼠右鍵點擊在使用Python和WebDriver進行網頁自動化測試時,我們經常需要模擬使用者的滑鼠行為,例如點擊、拖曳和右鍵選單等操作。 WebDriver會提供一些基本的滑鼠行動函數,如click、drag_and_drop等,但卻沒有直接提供模擬滑鼠右鍵點擊的函數。本文將介紹如何使用Python和WebD

使用Python和WebDriver實現網頁自動填充表格數據 使用Python和WebDriver實現網頁自動填充表格數據 Jul 07, 2023 pm 08:37 PM

使用Python和WebDriver實現網頁自動填充表格資料自動化測試是軟體開發過程中重要的一環,其中之一是網頁表單的自動填充。對於開發人員來說,手動填寫表單是一個枯燥且容易出錯的過程。而使用Python和WebDriver,在自動測試過程中實現自動填入表格數據,能夠減少人工重複勞動,並提高測試效率。在這篇文章中,我將介紹如何使用Python的Selenium

利用Python和WebDriver擴充自動化處理網頁的拖放操作 利用Python和WebDriver擴充自動化處理網頁的拖放操作 Jul 10, 2023 pm 07:09 PM

利用Python和WebDriver擴充自動化處理網頁的拖放操作在實際的Web應用中,拖放(DragandDrop)是一個常見的互動操作,它可以增強使用者的體驗和便利性。對測試人員而言,自動化處理網頁的拖放操作是一項重要且常見的任務。本文將介紹如何利用Python和WebDriver擴充功能自動化處理網頁的拖放作業。一、準備工作在開始前,我們需要安裝Pyt

使用Python和WebDriver實作表單自動填寫功能 使用Python和WebDriver實作表單自動填寫功能 Jul 07, 2023 am 10:25 AM

使用Python和WebDriver實作表單自動填寫功能在日常的網站瀏覽中,我們經常會遇到需要填寫表單的情況。當我們需要頻繁填寫相同或類似的表單時,手動填寫顯得很繁瑣而且耗時。幸運的是,我們可以藉助Python和WebDriver來實現自動填寫表單的功能,提高我們的工作效率。首先,我們要安裝selenium庫。 Selenium是一個自動化測試工具,可以模擬