目次
问题内容
解决方法
ホームページ Java 「extentlisteners.ExtentListeners.test」が空であるため、「com.aventstack.extentreports.ExtentTest.info(String)」を呼び出すことができません

「extentlisteners.ExtentListeners.test」が空であるため、「com.aventstack.extentreports.ExtentTest.info(String)」を呼び出すことができません

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 方法中的测试初始化​​行上设置断点,并在调试模式下执行测试以检查为其设置的值。

以上が「extentlisteners.ExtentListeners.test」が空であるため、「com.aventstack.extentreports.ExtentTest.info(String)」を呼び出すことができませんの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Python と WebDriver を使用して Web ページをキャプチャし、PDF ファイルとして保存する Python と WebDriver を使用して Web ページをキャプチャし、PDF ファイルとして保存する Jul 08, 2023 pm 10:55 PM

Python と WebDriver を使用して Web ページのスクリーンショットを作成し、PDF ファイルとして保存する 概要: Web 開発およびテスト中に、分析、記録、レポート作成のために Web ページのスクリーンショットを作成することが必要になることがよくあります。この記事では、Python と WebDriver を使用して Web ページのスクリーンショットを撮り、そのスクリーンショットを PDF ファイルとして保存して簡単に共有したりアーカイブしたりする方法を紹介します。 1. SeleniumWebDriver をインストールして構成します。 Python をインストールします。 Python 公式 Web サイト (https:

Python および WebDriver 拡張機能: Web ページでのマウス ホイール操作をシミュレートします。 Python および WebDriver 拡張機能: Web ページでのマウス ホイール操作をシミュレートします。 Jul 09, 2023 pm 11:55 PM

Python および WebDriver 拡張機能: Web ページでのマウス ホイール操作のシミュレート はじめに: Web インタラクション デザインの継続的な開発に伴い、自動テストにおけるユーザー操作のシミュレートがますます重要になってきています。一部の Web ページでは、マウス ホイールの使用が一般的な操作の 1 つになっています。ただし、Python を使用して自動テスト スクリプトを作成する開発者にとって、WebDriver でマウス ホイール操作をシミュレートする方法が課題になる場合があります。この記事ではPythonとWebDrivを使った方法を紹介します。

Python と WebDriver を使用して Web ページを自動的に更新する Python と WebDriver を使用して Web ページを自動的に更新する Jul 08, 2023 pm 01:46 PM

Python と WebDriver を使用して Web ページの自動更新を実装する はじめに: 毎日の Web ブラウジングでは、リアルタイム データの監視、動的ページの自動更新など、Web ページの頻繁な更新が必要なシナリオによく遭遇します。 Web ページを手動で更新すると多くの時間とエネルギーが無駄になります。そのため、Python と WebDriver を使用して Web ページを自動的に更新する機能を実装し、作業効率を向上させることができます。 1. インストールと構成環境 開始する前に、対応する環境をインストールして構成する必要があります。 Pythonをインストールする

Python と WebDriver を使用して Web ページに検証コードを自動的に入力します Python と WebDriver を使用して Web ページに検証コードを自動的に入力します Jul 07, 2023 am 10:19 AM

Python と WebDriver を使用して、Web ページに認証コードを自動的に入力します。インターネットの発展に伴い、セキュリティの向上と自動攻撃の防止を目的として、ユーザー登録やログインなどの操作に認証コードの仕組みを導入する Web サイトが増えています。ただし、検証コードを手動で入力するのは面倒なだけでなく、ユーザー エクスペリエンスが複雑になります。では、認証コードを自動的に入力する方法はあるのでしょうか?答えは「はい」です。この記事では、PythonとWebDriverを使ってWebページに認証コードを自動入力する方法を紹介します。まず、私は

Python と WebDriver を使用して Web ページ上のテーブル データを自動的に入力する Python と WebDriver を使用して Web ページ上のテーブル データを自動的に入力する Jul 07, 2023 pm 08:37 PM

Python と WebDriver を使用して Web ページ上のフォーム データを自動的に入力することは、ソフトウェア開発プロセスの重要な部分であり、Web フォームの自動入力もその 1 つです。開発者にとって、フォームに手動で入力するのは面倒でエラーが発生しやすいプロセスです。 Python と WebDriver を使用して自動テスト プロセス中にテーブル データを自動的に入力すると、手動での作業の重複が減り、テストの効率が向上します。この記事ではPythonでSeleniumを使う方法を紹介します。

Python および WebDriver 拡張機能: Web ページでのマウスの右クリックをシミュレートします Python および WebDriver 拡張機能: Web ページでのマウスの右クリックをシミュレートします Jul 07, 2023 am 11:22 AM

Python および WebDriver 拡張機能: Web ページでの右クリックのマウス クリックをシミュレートする Python と WebDriver を使用して自動 Web ページ テストを行う場合、多くの場合、クリック、ドラッグ、右クリック メニュー操作などのユーザーのマウス動作をシミュレートする必要があります。 WebDriver は、クリック、ドラッグ アンド ドロップなどのいくつかの基本的なマウス アクション関数を提供しますが、マウスの右クリックをシミュレートする関数を直接提供するわけではありません。この記事ではPythonとWebDの使い方を紹介します。

Python および WebDriver 拡張機能を使用して、Web ページでのドラッグ アンド ドロップ操作を自動化する Python および WebDriver 拡張機能を使用して、Web ページでのドラッグ アンド ドロップ操作を自動化する Jul 10, 2023 pm 07:09 PM

Python と WebDriver の拡張機能を使用して、Web ページのドラッグ アンド ドロップ操作を自動化します。実際の Web アプリケーションでは、ドラッグ アンド ドロップ (ドラッグ アンド ドロップ) は一般的な対話型操作であり、ユーザー エクスペリエンスと利便性を向上させることができます。 Web ページのドラッグ アンド ドロップ操作を自動化することは、テスターに​​とって重要かつ一般的なタスクです。この記事では、Python と WebDriver 拡張機能を使用して、Web ページ上のドラッグ アンド ドロップ操作を自動化する方法を紹介します。 1. 準備 始める前に、Pyt をインストールする必要があります

Python と WebDriver を使用して、Web ページ上の都道府県と都市のドロップダウン ボックスを自動的に入力する Python と WebDriver を使用して、Web ページ上の都道府県と都市のドロップダウン ボックスを自動的に入力する Jul 10, 2023 am 11:56 AM

Python と WebDriver を使用して Web ページ上の都道府県と都市のドロップダウン ボックスに自動的に入力する はじめに: Web フォームでは、都道府県と都市の選択ドロップダウン ボックスが頻繁に表示されますが、これらのドロップダウン ボックス間には特定の依存関係があります。これらのドロップダウン ボックスを手動で入力するのは面倒で時間のかかる作業ですが、Python と WebDriver を使用することで、これらのドロップダウン ボックスを自動的に入力することができ、作業効率が向上します。この記事では、Python と WebDriver を使用して、Web ページ上の都道府県と都市のドロップダウン ボックスを自動的に入力する方法を紹介します。