当前位置: 首页 > 知识库问答 >
问题:

为什么浏览器实例在Selenium和TestNG中执行后无法关闭/退出?

米树
2023-03-14

我试图以顺序的方式自动化不同测试用例中的几个测试用例。i、 e.一个接一个的测试类执行。

在某些情况下,web应用程序不会关闭/退出。i、 e.驱动程序实例未关闭/退出。我试图在@AfterClass方法和测试类级别中退出/关闭驱动程序,但在这两种情况下都不起作用。

在TestNG套件结果中,它显示为已尝试执行,但webdriver实例未关闭,新网页实例已打开。

作为参考,我分享了前两个测试类的代码。

请查看下面的代码片段:

package managers;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import enums.EnvironmentType;

public class VMSBaseDriver {
    public WebDriver driver;
//  private static DriverType driverType;
    private static EnvironmentType environmentType;
    private static final String CHROME_DRIVER_PROPERTY = "webdriver.chrome.driver";
    private static final String IE_DRIVER_PROPERTY = "webdriver.ie.driver";

    public WebDriver getDriver() {
        return driver;
    }

    @SuppressWarnings("deprecation")
    @Parameters("browserName")

    @BeforeClass

    public void initialize(String browser) throws IOException, InterruptedException {

        environmentType = FileReaderManager.getInstance().getConfigReader().getEnvironment();
//      driverType = FileReaderManager.getInstance().getConfigReader().getBrowser();

        switch (environmentType) {
        case LOCAL:
            System.out.println("(In Local) Selected environment from config :: " + environmentType);
            if (browser.equalsIgnoreCase("firefox")) {

                driver = new FirefoxDriver();
            } else if (browser.equalsIgnoreCase("chrome")) {
                System.setProperty(CHROME_DRIVER_PROPERTY,
                        FileReaderManager.getInstance().getConfigReader().getDriverPath() + "/chromedriver.exe");
                driver = new ChromeDriver();
            } else if (browser.equalsIgnoreCase("internetexplorer")) {

                System.setProperty(IE_DRIVER_PROPERTY,
                        FileReaderManager.getInstance().getConfigReader().getDriverPath() + "/IEDriverServer.exe");
                DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
                capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                        true);
                capabilities.setCapability(InternetExplorerDriver.IE_USE_PRE_PROCESS_PROXY, true);
                capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
                capabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false);
                driver = new InternetExplorerDriver(capabilities);

            }

            if (FileReaderManager.getInstance().getConfigReader().getBrowserWindowSize())
                driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(
                    FileReaderManager.getInstance().getConfigReader().getImplicitlyWait(), TimeUnit.SECONDS);
            // driver.get(FileReaderManager.getInstance().getConfigReader().getApplicationUrl());
            driver.get("http://" + getIPAddress());
            Thread.sleep(3000);

            break;

        case REMOTE:
            System.out.println("(In Remote) Selected environment from config :: " + environmentType);
            if (browser.equalsIgnoreCase("firefox")) {

                FirefoxOptions firefoxOptions = new FirefoxOptions();
                FirefoxProfile profile = new FirefoxProfile();

                profile.setAcceptUntrustedCertificates(true);
                profile.setAssumeUntrustedCertificateIssuer(false);
                profile.setPreference("network.proxy.type", 0);
                firefoxOptions.setCapability(FirefoxDriver.PROFILE, profile);
                driver = new RemoteWebDriver(new URL("http://172.20.1.24:4444/wd/hub"), firefoxOptions);
            } else if (browser.equalsIgnoreCase("chrome")) {

                ChromeOptions options = new ChromeOptions();
                options.addArguments("--start-maximized");
                options.addArguments("--ignore-certificate-errors");
                options.addArguments("--disable-popup-blocking");
                DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                capabilities.setCapability(ChromeOptions.CAPABILITY, options);
                capabilities.setCapability("browserName", "chrome");

                driver = new RemoteWebDriver(new URL("http://172.20.1.24:4444/wd/hub"), capabilities);
            } else if (browser.equalsIgnoreCase("internetexplorer")) {

                DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
                iecapabilities.setBrowserName("internet explorer");
                iecapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                        true);
                iecapabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
                iecapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
                iecapabilities.setCapability("ignoreProtectedModeSettings", true);
                iecapabilities.setCapability("nativeEvents", false);
                iecapabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "");
                iecapabilities.setCapability(InternetExplorerDriver.LOG_LEVEL, "DEBUG");

                iecapabilities.setPlatform(Platform.WINDOWS);

                driver = new RemoteWebDriver(new URL("http://172.20.1.24:4444/wd/hub"), iecapabilities);

            }

            if (FileReaderManager.getInstance().getConfigReader().getBrowserWindowSize())
                driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(
                    FileReaderManager.getInstance().getConfigReader().getImplicitlyWait(), TimeUnit.SECONDS);
            driver.get("http://" + getIPAddress());
            Thread.sleep(3000);

            break;
        }

    }

    @AfterClass
    public void TeardownTest() {

        driver.quit();

    }

    public String getIPAddress() {

        InetAddress IP = null;
        try {
            IP = InetAddress.getLocalHost();
            // System.out.println("IP of my system is := " + IP.getHostAddress());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return IP.getHostAddress();
    }

    public By extendedLocator(String locString, String value)

    {

        return By.xpath(String.format(locString, value));

    }

}

ViewTest类

package testCases;

import java.io.IOException;
import java.lang.reflect.Method;

import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.aventstack.extentreports.Status;

import managers.ExtentReportTestManager;
import managers.VMSBaseDriver;
import pageObjects.CamerasAndEncodersPage;
import pageObjects.MonitoringPage;
import pageObjects.ViewsPage;

public class ViewsTest extends VMSBaseDriver {

    public MonitoringPage monitoringPage;
    public ViewsPage viewsPage;
    CamerasAndEncodersPage camerasAndEncodersPage;
    public String[] Servers;

    @BeforeClass
    public void init() throws InterruptedException, IOException {

        monitoringPage = PageFactory.initElements(driver, MonitoringPage.class);
        viewsPage = PageFactory.initElements(driver, ViewsPage.class);
        Servers = viewsPage.getServersList();

        driver.navigate().to("http://" + Servers[0]);
        Thread.sleep(2000);
        viewsPage.SignIn();
        Thread.sleep(1000);
        viewsPage.WaitUntilLoadingBlockAppears();
        Thread.sleep(1000);
        viewsPage.WaitUntilLoadingBlockDisappears();
        Thread.sleep(1000);
        viewsPage.GoToViewsPageFromLanding();
        Thread.sleep(1000);
        viewsPage.GoToViewsPage();
        Thread.sleep(1000);
    }
    
    /*
     * @AfterMethod public void browserCategory(Method method) {
     * ExtentReportTestManager.startTest(method.getName()).assignCategory(((
     * RemoteWebDriver) driver).getCapabilities().getBrowserName().toUpperCase());
     * 
     * }
     */

    @Test
    public void AddNewViewTest(Method method) throws Exception {
        //logger = report.startTest("AddNewViewTest");
        ExtentReportTestManager.startTest(method.getName()).assignCategory(((RemoteWebDriver) driver).getCapabilities().getBrowserName().toUpperCase());

        int viewsCount = viewsPage.GetViewsSize();
        ExtentReportTestManager.getTest().log(Status.INFO, "Click on New button");
        viewsPage.ClickOnNewButton();

        String viewName = "ViewName" + viewsPage.GetRandomDigit(0, 10000);
        ExtentReportTestManager.getTest().log(Status.INFO, "Input name " + viewName + " in name field");
        viewsPage.InputIntoNameField(viewName);

        String remarks = "Remarks for " + viewName;
        ExtentReportTestManager.getTest().log(Status.INFO, "Input remarks " + remarks + " in remarks field");
        viewsPage.InputIntoRemarksField(remarks);

        int layoutSize = viewsPage.GetLayoutSize();
        int random = viewsPage.GetRandomDigit(0, layoutSize);
        ExtentReportTestManager.getTest().log(Status.INFO, "Select layout ");
        viewsPage.ClickOnLayoutByIndex(random);

        int viewSize = viewsPage.GetLayoutViewSize();
        int resourcesSize = viewsPage.GetResourcesSize();
        int rand = viewsPage.GetRandomDigit(1, viewSize);

        ExtentReportTestManager.getTest().log(Status.INFO, "Drag " + rand + " resources ");
        for (int i = 0; i < rand; i++) {
            int viewIndex = viewsPage.GetRandomDigit(0, viewSize);
            int resIndex = viewsPage.GetRandomDigit(0, resourcesSize);
            String viewId = viewsPage.GetViewIDByIndex(viewIndex);
            String resourceId = viewsPage.GetResourcesIDByIndex(resIndex);
            viewsPage.DragAndDropCameraToView(resourceId, viewId);
        }

        int fullViewSize = viewsPage.GetFullViewsSize();
        int audioViewsSize = viewsPage.GetAudioViewsSize();
        ExtentReportTestManager.getTest().log(Status.INFO, "Press Save button");
        viewsPage.PressSaveButton();

        String viewNameSaved = viewsPage.GetViewName();
        String viewRemarksSaved = viewsPage.GetRemarksText();
        int fullViewSizeSaved = viewsPage.GetFullViewsSize();
        int audioViewsSizeSaved = viewsPage.GetAudioViewsSize();

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that view name is equals to inputed");
        AssertJUnit.assertEquals(viewNameSaved, viewName);

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that view remarks is equals to inputed");
        AssertJUnit.assertEquals(viewRemarksSaved, remarks);

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that layout has " + fullViewSize + "resources");
        AssertJUnit.assertEquals(fullViewSizeSaved, fullViewSize);
//        Assert.assertEquals(audioViewsSizeSaved,audioViewsSize);

        ExtentReportTestManager.getTest().log(Status.INFO, "Refresh page ");
        viewsPage.Refresh();
        // int viewsCount = viewsPage.GetViewsSize();
        int viewsCountAfterRefresh = viewsPage.GetViewsSize();
        ExtentReportTestManager.getTest().log(Status.INFO, "Check that new view is added ");
        AssertJUnit.assertEquals(viewsCountAfterRefresh, viewsCount + 1);

        ExtentReportTestManager.getTest().log(Status.INFO, "Click on " + viewName + " view");
        viewsPage.ClickOnViewByName(viewName);
        Thread.sleep(1000);

        String viewNameRefreshed = viewsPage.GetViewName();
        String viewRemarksRefreshed = viewsPage.GetRemarksText();
        int fullViewSizeRefreshed = viewsPage.GetFullViewsSize();
        int audioViewsSizeRefreshed = viewsPage.GetAudioViewsSize();

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that view name is equals to inputed after refresh");
        AssertJUnit.assertEquals(viewNameRefreshed, viewName);

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that view remarks is equals to inputed after refresh");
        AssertJUnit.assertEquals(viewRemarksRefreshed, remarks);

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that layout has " + fullViewSize + "resources after refresh");
        AssertJUnit.assertEquals(fullViewSizeRefreshed, fullViewSize);
//        Assert.assertEquals(audioViewsSizeRefreshed,audioViewsSize);

        ExtentReportTestManager.getTest().log(Status.INFO, "Go to Monitoring page");
        viewsPage.GoToMonitoringPage();

        ExtentReportTestManager.getTest().log(Status.INFO, "Input into filter field");
        monitoringPage.FilterField(viewName);

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that new view is present in Monitoring Resources list");
        boolean viewIsExist = monitoringPage.VerifyThatResourceIsExist(viewName);
        AssertJUnit.assertTrue(viewIsExist);
    }

    

}

网页测试类

package testCases;

import java.io.IOException;
import java.lang.reflect.Method;

import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.aventstack.extentreports.Status;

import managers.ExtentReportTestManager;
import managers.VMSBaseDriver;
import pageObjects.MonitoringPage;
import pageObjects.WebPagesPage;

public class WebPagesTest extends VMSBaseDriver {


    public MonitoringPage monitoringPage;
    public WebPagesPage webPagesPage;
    public String[] Servers;

    /*
     * @AfterMethod public void browserCategory(Method method) {
     * ExtentReportTestManager.startTest(method.getName())
     * .assignCategory(((RemoteWebDriver)
     * driver).getCapabilities().getBrowserName().toUpperCase());
     * 
     * }
     */

    @BeforeClass
    public void init() throws IOException, InterruptedException {

        monitoringPage = PageFactory.initElements(driver, MonitoringPage.class);
        webPagesPage = PageFactory.initElements(driver, WebPagesPage.class);
        Servers = webPagesPage.getServersList();
        webPagesPage.SignIn();
        webPagesPage.WaitUntilLoadingBlockAppears();
        webPagesPage.WaitUntilLoadingBlockDisappears();
        webPagesPage.GoToWebPagesPageFromLanding();

        /*
         * driver.navigate().to("http://" + Servers[0]); try{
         * driver.switchTo().alert().accept(); }catch(Exception a){}
         * 
         * webPagesPage.WaitUntilLoadingBlockAppears();
         * webPagesPage.WaitUntilLoadingBlockDisappears();
         * webPagesPage.GoToWebPagesPage();
         */
    }

    @Test
    public void AddNewWebPageTest(Method method) throws InterruptedException {
        // logger = report.startTest("AddNewWebPageTest");
        
        
        ExtentReportTestManager.startTest(method.getName())
         .assignCategory(((RemoteWebDriver)
         driver).getCapabilities().getBrowserName().toUpperCase());

        ExtentReportTestManager.getTest().log(Status.INFO, "Click on new button");
        webPagesPage.ClickOnNewButton();

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that Save button is disabled");
        AssertJUnit.assertFalse(webPagesPage.SaveButtonIsEnabled());

        ExtentReportTestManager.getTest().log(Status.INFO, "Check that Cancel button is enabled");
        AssertJUnit.assertTrue(webPagesPage.CancelButtonIsEnabled());
    }

    

}

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Test Suite">
    <listeners>
        <listener class-name="reporter.BaseListener" />
    </listeners>



    <test name="R121 Internet Explorere Execution"  thread-count="2" >
        <parameter name="browserName" value="internetexplorer" />
        <classes>
            <class name="testCases.ViewsTest" />
            <class name="testCases.WebPagesTest" />
            <class name="testCases.AddCameraManually" />
            <class name="testCases.AudioChannelsElementsTest" />
            <class name="testCases.AudioChannelsTest" />
            <class name="testCases.CamerasAndEncodersElementsTest" />
        </classes>
    </test>
</suite>

共有1个答案

吕永寿
2023-03-14

您可以在@AfterClass注释中添加alwaysRun=true。例如@AfterClass(alwaysRun=true)。

如果您的测试类彼此独立,那么最好为每个测试类使用单独的会话。在这种情况下,您必须在每个测试类中编写@AfterClass方法来关闭单独的会话。

 类似资料:
  • 我试图创建一个类,该类将有一个接一个地测试超文本传输协议代理的方法,直到我有一个工作的代理,我可以添加到一个selenium网络驱动程序实例中。 我有一个原始输入来验证代理是否在webdriver中工作,如果它不工作,它应该测试另一个代理并请求我确认,然后关闭驱动程序或保持打开状态。(我删除了使用测试方法的if语句,因为我得到了一个错误) 当我在终端中输入“n”时,当我被要求确认时,它会关闭浏览器

  • 本文向大家介绍在vue中阻止浏览器后退的实例,包括了在vue中阻止浏览器后退的实例的使用技巧和注意事项,需要的朋友参考一下 如下所示: vue阻止浏览器后退按钮与js相同,同样没有脱离原生的js 以上这篇在vue中阻止浏览器后退的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • 问题内容: 我使用以下代码处理使用+ 终止正在运行的Python脚本的情况。 但是,这也会终止我的浏览器。 有没有办法终止脚本并使浏览器保持活动状态,以便我可以继续使用它? 我通常要做的是通过+ 暂停脚本。不幸的是,这经常导致浏览器死机并且不响应。 问题答案: 您可以将CTRL + C +替换为方法以终止脚本,而无需关闭浏览器会话。只需使用以下形式:

  • 问题内容: 我在www.darknovagames.com上运行了基于浏览器的游戏。最近,我一直在努力使用CSS重新格式化该网站,试图让其所有页面都根据HTML标准进行验证。 我一直在想着要在页面左侧放置AJAX导航菜单的想法(而不是每次都将用户带到一个单独的页面,而是需要重新加载标题和导航栏,而这几乎是不会改变的),我知道如果这样做,我可能会破坏浏览器中的“前进/后退”按钮。我的问题是,我应该继

  • 通常情况下,您使用selenium来自动化测试用例,在测试用例运行完毕后,浏览器关闭。 然而,我尝试使用selenium webdriver编写特定任务的脚本,例如登录到特定页面,但浏览器在登录后应保持打开状态。 我开发了门户,这样,如果我早上开始工作,我就不必登录所有的后端,我只需要登录一次我的门户,从那里我就可以触发我需要的一切。 我这样做是为了登录到typo3后端(片段): 您可以看到,我在

  • 本文向大家介绍python selenium 对浏览器标签页进行关闭和切换的方法,包括了python selenium 对浏览器标签页进行关闭和切换的方法的使用技巧和注意事项,需要的朋友参考一下 1.关闭浏览器全部标签页 2.关闭当前标签页(从标签页A打开新的标签页B,关闭标签页A) 3.关闭当前标签页(从标签页A打开新的标签页B,关闭标签页B) 可利用浏览器自带的快捷方式对打开的标签进行关闭 F