Selenium C#成功运行测试,但在上一次测试完成后,浏览器仍处于打开状态

时间:2019-01-18 00:25:23

标签: selenium selenium-webdriver automated-tests

目前只有4个测试全部通过。前三个确实在两次测试之间关闭了浏览器窗口。第四项测试完成后,浏览器保持打开状态。我使用哪个浏览器都没关系。任何指导都是很棒的。

代码:

测试类文件:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;
using NUnit.Framework;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Safari;

namespace Resolver.TestCases
{
    /// <summary>
    /// 
    /// </summary>
    [TestClass]
    public class NavigationTests: Common.Base
    {
        public static string Url = "some url";
        public static string browser = "chrome";

        public static string userName = "wayne1234@yahoo.com";
        public static string password = "password";

        public static string bogusUserName = "stimpycom";
        public static string bogusPassword = "123";

        [AssemblyInitialize]
        public static void Setup(TestContext context)
        {

            Common.BrowserActions.ChooseDriverInstance(browser);

            HomePage.GoTo(Url);
            NUnit.Framework.Assert.IsTrue(HomePage.IsAt());
            Pages.LoginPage.SetUserName(userName);
            Pages.LoginPage.SetUserPassword(password);

            Pages.LoginPage.LoginIntoApp();
            Common.Base.Extras.Sleep(3000);


        }

        [TestMethod]
        public void InvalidLogin()
        {
            ////log out
            Pages.UserMenu.OpenUserMenu();

            Pages.UserMenu.Logout();

            //click in the email/username and password fields - leave blank
            Pages.LoginPage.SetUserName("");


            Pages.LoginPage.ValidateMissingUsername();
            Pages.LoginPage.SetUserPassword("");


            Pages.LoginPage.ValidateMissingPassword();

            Pages.LoginPage.ValidateLoginNotEnabled();


            //enter just password
            Pages.LoginPage.SetUserPassword(password);

            Pages.LoginPage.ValidateLoginNotEnabled();


            //set the user name and password to bogus values
            Pages.LoginPage.SetUserName(bogusUserName);
            Pages.LoginPage.SetUserPassword(bogusPassword);

            Pages.LoginPage.ValidateLoginNotEnabled();


            //validate can log in
            HomePage.GoTo(Url);
            Pages.LoginPage.SetUserName(userName);
            Pages.LoginPage.SetUserPassword(password);

            Pages.LoginPage.LoginIntoApp();
            Common.Base.Extras.Sleep(500);



        }

        [TestMethod]
        public void Go_toLeftNavigationOption()
        {

            Pages.CasesPage.SelectCases();

            Pages.CasesPage.SelectTypeofCases("Active");
            Pages.CasesPage.SelectTypeofCases("Resolved");
            Pages.CasesPage.SelectTypeofCases("Closed");
            Pages.CasesPage.SelectTypeofCases("Recent");
            Pages.CasesPage.SelectTypeofCases("All Cases");
            Pages.EasyEstimatePage.SelectNav("Easy Estimate");
            Pages.ReferACasePage.SelectNav("Refer a Case");
            Pages.QuestionsPage.SelectNav("Questions");
            Pages.SettingsPage.SelectNav("Settings");
            Pages.CasesPage.SelectCases();

        }

        [TestMethod]
        public void Go_toTopNavigationOption()
        {

            Pages.NotificationsTopNav.OpenNotificationsTopNav();

            //user pulldown - My Profile
            Pages.UserMenu.OpenUserMenu();
            Pages.UserMenu.OpenMyProfile();

            //Search
            //Pages.CaseSearch.SearchForCase();


        }

        [TestMethod]
        public void RememberMeValidation()
        {
            ////log out first
            Pages.UserMenu.OpenUserMenu();
            Pages.UserMenu.Logout();
            Common.Base.Extras.Sleep(150);
            ////set the user name and password
            Pages.LoginPage.SetUserName(userName);
            Pages.LoginPage.SetUserPassword(password);

            //check the remember me check box
            Pages.LoginPage.CheckRememberMe();
            Pages.LoginPage.LoginIntoApp();
            Common.Base.Extras.Sleep(2000);

            //log out
            Pages.UserMenu.OpenUserMenu();
            Pages.UserMenu.Logout();
            Common.Base.Extras.Sleep(150);

            //only enter the user password ID to login
            if (browser == "ie")
            {
                Pages.LoginPage.SetUserName(userName);

            }
            Pages.LoginPage.SetUserPassword(password);
            Pages.LoginPage.LoginIntoApp();
            Common.Base.Extras.Sleep(350);
            Pages.UserMenu.OpenUserMenu();
            Pages.UserMenu.Logout();
        }



        [TestCleanup]
        public void CleanUp()
        {
            Common.BrowserActions.Close();

        }



    }
}

BrowserActions类文件(也许我的逻辑已关闭)

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Remote;
using static Dapper.SqlMapper;

namespace Resolver.Common
{
    public enum BrowserType
    {
        Chrome,
        Firefox,
        IE,
        Edge
    }

    public class BrowserActions
    {
        public static BrowserType _browserType;

        private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
        private static readonly IDictionary<string, WebDriverWait> Waits = new Dictionary<string, WebDriverWait>();
        private static IWebDriver driver;
        private static WebDriverWait wait;


        public static IWebDriver webDriver
        {
            get
            {
                if (driver == null)
                {
                    throw new NullReferenceException("IWebDriver is null.  The WebDriver browser instance was not initialized. " +
                        "You should first call the method 'InitBrowser'.");
                }
                return driver;
            }
            private set
            {
                driver = value;
            }
        }
        public static WebDriverWait Wait
        {
            get
            {
                if (wait == null)
                {
                    throw new NullReferenceException("WebDriverWait is null, The WebDriver browser instance was not initialized. " +
                        "You should first call the method 'InitBrowser'.");
                }
                return wait;
            }
            private set
            {
                wait = value;
            }
        }


        public static string Title
        {
            get { return driver.Title; }

        }



        public static void Goto(string url)
        {

            driver.Url = url;
            driver.Manage().Window.Maximize();
            Thread.Sleep(5000);
            driver.Manage().Cookies.DeleteAllCookies();
        }



        public static void ScrollToBottom()//IWebDriver driver
        {
            long scrollHeight = 0;

            do
            {
                IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver;
                var newScrollHeight = (long)js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight); return document.body.scrollHeight;");

                if (newScrollHeight == scrollHeight)
                {
                    break;
                }
                else
                {
                    scrollHeight = newScrollHeight;
                    Thread.Sleep(400);
                }
            } while (true);
        }

        public BrowserActions(BrowserType browser)
        {
            _browserType = browser;
        }

        public static void ChooseDriverInstance(string browser)  
        {
            switch (browser)
            {
                case "chrome":
                    driver = new ChromeDriver();

                    break;

                case "ie":
                    var optionsIE = new InternetExplorerOptions()
                    {
                        IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                        IgnoreZoomLevel = true,
                        EnableNativeEvents = false,
                        RequireWindowFocus = false,
                        //maybe helpful
                        UnhandledPromptBehavior = UnhandledPromptBehavior.Accept,
                        EnablePersistentHover = true,
                        EnsureCleanSession = true

                    };

                    driver = new InternetExplorerDriver(optionsIE);
                    //driver = new RemoteWebDriver(new Uri("https://test-resolver-web.azurewebsites.net/"), optionsIE.ToCapabilities(), TimeSpan.FromSeconds(300));
                    break;

                case "firefox":
                    driver = new FirefoxDriver();


                    break;

                case "Chrome-headless":
                    ChromeOptions opts1 = new ChromeOptions();
                    opts1.AddArgument("ignore-certificate-errors");
                    opts1.AddArgument("headless");
                    opts1.AddUserProfilePreference("credentials_enable_service", false);
                    opts1.AddUserProfilePreference("profile.password_manager_enabled", false);
                    ChromeDriverService service1 = ChromeDriverService.CreateDefaultService();
                    driver = new ChromeDriver(service1, opts1, TimeSpan.FromMinutes(2));
                    // wait = new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                    Drivers.Add("chrome", driver);
                    Waits.Add("chrome", wait);

                    break;
                case "Edge":
                    driver = new EdgeDriver();
                    //wait = new WebDriverWait(driver, TimeSpan.FromSeconds(Properties.Settings.Default.DefaultTimeout));
                    Drivers.Add("Edge", driver);
                    Waits.Add("Edge", wait);

                    break;


                default:
                    driver = new ChromeDriver();
                    break;


            }



        }
        public static void Close()
        {
            foreach (var key in Drivers.Keys)
            {

                Waits[key] = null;
                Drivers[key].Close();
                Drivers[key].Quit();

                driver = null;

                GC.Collect();

            }


        }



    }

}

此外,也许不必包含-Pages类文件:

using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.PageObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using Resolver;
using Microsoft.VisualStudio.TestTools.UITesting;
using OpenQA.Selenium.Support.UI;

namespace Resolver

{
    public static class Pages
    {
        public static HomePage HomePage
        {
            get
            {
                var homePage = new HomePage();

                //    PageFactory.InitElements(Browser.Driver, homePage);
                //    //static method takes the driver instance of the given class 
                //    //and the class type, and returns a Page Object with its fields 
                //    //fully initialized.
                return homePage;
            }

        }

        public static LoginPage LoginPage
        {
            get
            {
                var loginPage = new LoginPage();

                //    //PageFactory.InitElements(Browser.Driver, homePage);
                //    ////static method takes the driver instance of the given class 
                //    ////and the class type, and returns a Page Object with its fields 
                //    ////fully initialized.
                return loginPage;
            }

        }



        public static CasesPage CasesPage
        {
            get
            {
                var casesPage = new CasesPage();

                return casesPage;
            }

        }

        public static EasyEstimatePage EasyEstimatePage
        {
            get
            {
                var easyEstimatePage = new EasyEstimatePage();

                return easyEstimatePage;
            }

        }


        public static ReferACasePage ReferACasePage
        {
            get
            {
                var referACasePage = new ReferACasePage();

                return referACasePage;
            }

        }


        public static QuestionsPage QuestionsPage
        {
            get
            {
                var questionsPage = new QuestionsPage();

                return questionsPage;
            }

        }


        public static SettingsPage SettingsPage
        {
            get
            {
                var settingsPage = new SettingsPage();

                return settingsPage;
            }

        }


        public static UserMenu UserMenu
        {
            get
            {
                var userMenu = new UserMenu();

                return userMenu;
            }

        }

        public static CaseSearch CaseSearch
        {
            get
            {
                var caseSearch = new CaseSearch();

                return caseSearch;
            }

        }

        public static NotificationsTopNav NotificationsTopNav
        {
            get
            {
                var notificationsTopNav = new NotificationsTopNav();

                return notificationsTopNav;
            }

        }



        public static CreateAnAccount CreateAnAccount
        {
            get
            {
                var createAnAccount = new CreateAnAccount();

                return createAnAccount;
            }

        }

    }

    public class LoginPage
    {

        public LoginPage()
        {
        }


        IWebElement userNameField => Common.BrowserActions.webDriver.FindElement(By.Id("username"));

        IWebElement passwordField => Common.BrowserActions.webDriver.FindElement(By.Id("password"));

        IWebElement emailRequiredMessage => Common.BrowserActions.webDriver.FindElement(By.Id("email-required"));
        IWebElement passwordRequiredMessage => Common.BrowserActions.webDriver.FindElement(By.Id("password-error"));


        IWebElement loginInformationIncorrectErrorMsg => Common.BrowserActions.webDriver.FindElement(By.Id("invalid-login"));
        IWebElement emailInvalidMessage => Common.BrowserActions.webDriver.FindElement(By.Id("email-error"));

        IWebElement loginButton => Common.BrowserActions.webDriver.FindElement(By.Id("login_button"));

        IWebElement rememberMeCheckbox => Common.BrowserActions.webDriver.FindElement(By.Id("remember_me"));
        //IList<IWebElement> oCheckBox = BrowserActions.Driver.FindElements(By.Id("mat-checkbox-1"));

        IWebElement forgotUsernamePassword => Common.BrowserActions.webDriver.FindElement(By.Id("forgot_username_password"));

        IWebElement createAnAccount => Common.BrowserActions.webDriver.FindElement(By.Id("create_account"));

        IWebElement logoutSuccessMessage => Common.BrowserActions.webDriver.FindElement(By.Id("logout-message"));

        public void SetUserName(string userName)
        {
            userNameField.SendKeys(userName);
            passwordField.Click();
            Common.Base.Extras.Sleep(5000);

        }

        public string GetUserName()
        {
            var userNameCurrent = userNameField.Text;
            return userNameCurrent;

        }

        public void SetUserPassword(string password)
        {
            passwordField.SendKeys(password);
            userNameField.Click();

        }


        public void CheckRememberMe()
        {
            rememberMeCheckbox.Click();


        }

        public void LoginIntoApp()
        {
            loginButton.Click();

        }

        public void ValidateLoginNotEnabled()
        {
            Assert.IsFalse(loginButton.Enabled);

        }

        public void ValidateMissingUsername()
        {
            DefaultWait<IWebElement> wait = new DefaultWait<IWebElement>(emailRequiredMessage);
            wait.Timeout = TimeSpan.FromSeconds(250);
            Assert.IsTrue(emailRequiredMessage.Displayed);

        }

        public void ValidateMissingPassword()
        {
            Assert.IsTrue(passwordRequiredMessage.Displayed);

        }
    }


    public class CaseSearch
    {

        public CaseSearch()
        {
        }


        IWebElement searchButton => Common.BrowserActions.webDriver.FindElement(By.Id("search-icon"));
        //IWebElement searchButton2 => BrowserActions.Driver.FindElement(By.XPath("//button[contains(text(), 'search-icon')]"));
        IWebElement closeSearch => Common.BrowserActions.webDriver.FindElement(By.Id("collapse-search"));

        public void SearchForCase()
        {
            searchButton.Click();

        }

        public void CloseCaseSearch()
        {

            closeSearch.Click();

        }



    }

    public class NotificationsTopNav
    {

        public NotificationsTopNav()
        {
        }


        IWebElement notificationBell => Common.BrowserActions.webDriver.FindElement(By.Id("notifications-bell"));


        public void OpenNotificationsTopNav()
        {

            notificationBell.Click();

        }



    }



    public class UserMenu
    {

        public UserMenu()
        {
        }


        IWebElement userMenu => Common.BrowserActions.webDriver.FindElement(By.Id("userMenu"));
        IWebElement openMyProfile => Common.BrowserActions.webDriver.FindElement(By.Id("my-profile"));
        IWebElement logout => Common.BrowserActions.webDriver.FindElement(By.Id("logout"));

        IWebElement userNameField => Common.BrowserActions.webDriver.FindElement(By.Id("username"));

        public void OpenUserMenu()
        {
            Common.Base.Extras.Sleep(3000);
            userMenu.Click();

        }

        public void OpenMyProfile()
        {

            openMyProfile.Click();

        }

        public void Logout()
        {

            logout.Click();
            Common.Base.Extras.Sleep(2000);
            //validate returned to the login page
            NUnit.Framework.Assert.IsTrue(userNameField.Displayed);
        }

    }

    public class CasesPage
    {

        public CasesPage()
        {
        }

        IWebElement myCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("My Cases"));
        IWebElement activeCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Active (10)"));
        IWebElement resolvedCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Resolved (12)"));
        IWebElement closedCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Closed (13)"));
        IWebElement recentCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Recent (16)"));

        IWebElement allCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("All Cases (71)"));

        public void SelectCases()
        {
            myCases.Click();
            Common.Base.Extras.Sleep(2000);
        }

        public void SelectTypeofCases(string caseCategory)
        {
            switch (caseCategory)
            {
                case "Active":
                    activeCases.Click();
                    break;

                case "Resolved":
                    resolvedCases.Click();
                    break;

                case "Closed":
                    closedCases.Click();
                    break;

                case "Recent":
                    recentCases.Click();
                    break;

                case "All Cases":
                    allCases.Click();
                    break;
                default:
                    myCases.Click();
                    break;

            }

        }


    }


    public class EasyEstimatePage
        {

            public EasyEstimatePage()
            {
            }


            IWebElement myCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Easy Estimate"));

            public void SelectNav(string leftNavigationOption)
            {

                myCases.Click();

            }

        }
    public class ReferACasePage
    {

        public ReferACasePage()
        {
        }


        IWebElement myCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Refer a Case"));

        public void SelectNav(string leftNavigationOption)
        {

            myCases.Click();

        }

    }
    public class QuestionsPage
    {


        public QuestionsPage()
        {
        }



        IWebElement myCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Questions"));


        public void SelectNav(string leftNavigationOption)
        {

            myCases.Click();

        }


    }
    public class SettingsPage
    {

        public SettingsPage()
        {
        }


        IWebElement myCases => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Settings"));

        public void SelectNav(string leftNavigationOption)
        {
            myCases.Click();



        }

    }

    public class CreateAnAccount
    {
        public CreateAnAccount()
        {
        }


        IWebElement name => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText(""));
        IWebElement userName => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText(""));
        IWebElement password => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText(""));
        IWebElement passwordConfirm => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Settings"));
        IWebElement readAndAcceptTerms => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Settings"));
        IWebElement createAnAccountButton => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Create an account"));

        IWebElement loginLink => Common.BrowserActions.webDriver.FindElement(By.PartialLinkText("Login"));


        public void EnterRequiredData(string name, string username, string password, string passwordConfirm)
        {




        }

        public void AlreadyHaveAccountClick()
        {
            createAnAccountButton.Click();

        }

    }

    public class HomePage
    {
        //public static string Url = "https://test-resolver-web.azurewebsites.net";
        public static string PageTitle = "Resolver";

        public RemoteWebDriver _driver;
        public object webDriver;


        public HomePage(RemoteWebDriver driver) => _driver = driver;


        public HomePage()
        {
        }



        public static void GoTo(string Url)
        {

            Common.BrowserActions.Goto(Url);
            //_driver.Manage().Window.Maximize();

            Console.WriteLine("Go to url in the home page : " + Url);


        }


        public static bool IsAt()
        {
            return Common.BrowserActions.Title == PageTitle;

        }

    }


}

1 个答案:

答案 0 :(得分:0)

从共享的代码示例中,您将使用ChooseDriverInstance()方法中的“添加”仅将“ Edge”和“ Chrome无头”浏览器添加到“ Drivers”字典中。

在测试结束时,仅关闭“驱动程序”词典中的浏览器驱动程序。这可能是个问题。请尝试将所有创建的浏览器实例添加到“驱动程序”字典中。

始终使用Quit()方法关闭WebDriver和浏览器。