You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium C# PageFactory登录后重复打开登录页及单登录实现咨询

Hey there! Let's work through that duplicate login page issue you're hitting with Selenium C# and PageFactory. Here are some practical, actionable ways to maintain a single login session:

1. Stick to One WebDriver Instance Throughout Your Tests

The biggest culprit here is usually creating multiple WebDriver instances by accident. Your BasePage accepts a driver, so make sure you only initialize that driver once in your test setup, then pass the same instance to every page object.

For example, here's how your test class should look:

[TestClass]
public class LoginFlowTests
{
    private IWebDriver _driver;
    private HomePage _homePage;

    [TestInitialize]
    public void TestSetup()
    {
        // Initialize driver ONCE - this is your single session
        _driver = new ChromeDriver();
        _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
        
        // Pass the same driver to your HomePage
        _homePage = new HomePage(_driver);
    }

    [TestMethod]
    public void SuccessfulLoginMaintainsSession()
    {
        _homePage.NavigateToLoginPage();
        _homePage.PerformValidLogin("your-username", "your-password");
        
        // All subsequent page interactions use the same _driver instance
        var dashboardPage = new DashboardPage(_driver);
        Assert.IsTrue(dashboardPage.IsDashboardLoaded());
    }

    [TestCleanup]
    public void TestTeardown()
    {
        _driver.Quit();
    }
}

If you create a new WebDriver every time you instantiate a page, you'll get fresh browser instances with no shared session—hence the duplicate login pages.

2. Handle New Windows/Tabs Created During Login

Sometimes login triggers a new browser window or tab with another login page. You can detect this, clean up the extra window, and switch back to your original session:

Add this logic to your PerformLogin method in HomePage:

public void PerformValidLogin(string username, string password)
{
    // Save the original window handle to return to later
    string originalWindow = driver.CurrentWindowHandle;

    // Execute login steps
    usernameInput.SendKeys(username);
    passwordInput.SendKeys(password);
    loginButton.Click();

    // Wait for new window to open, then clean it up
    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(d => d.WindowHandles.Count > 1);

    foreach (string windowHandle in driver.WindowHandles)
    {
        if (windowHandle != originalWindow)
        {
            driver.SwitchTo().Window(windowHandle);
            driver.Close(); // Close the duplicate login page
            break;
        }
    }

    // Switch back to your original session window
    driver.SwitchTo().Window(originalWindow);
}

This ensures you're only keeping the browser instance with your active logged-in session.

3. Use a Singleton Pattern for Page Objects

To avoid accidentally creating multiple instances of your login page (which might re-trigger login flows), implement a singleton pattern for your page classes. Here's how to adjust your HomePage:

public class HomePage : BasePage
{
    private static HomePage _instance;

    // Make constructor private to force using GetInstance
    private HomePage(IWebDriver driver) : base(driver) { }

    public static HomePage GetInstance(IWebDriver driver)
    {
        if (_instance == null || _instance.driver != driver)
        {
            _instance = new HomePage(driver);
        }
        return _instance;
    }

    // Your PageFactory elements go here
    [FindsBy(How = How.Id, Using = "username")]
    private IWebElement usernameInput;

    [FindsBy(How = How.Id, Using = "password")]
    private IWebElement passwordInput;

    [FindsBy(How = How.Id, Using = "login-btn")]
    private IWebElement loginButton;

    // Rest of your methods...
}

Then in your tests, use HomePage.GetInstance(_driver) instead of new HomePage(_driver)—this guarantees you're always working with the same page instance tied to your single session.

4. Persist Login Session with Cookies

If your app uses cookies to maintain login state, you can save the cookies after login and reuse them across test steps to avoid re-logging in:

// After successful login, save the session cookies
var loginCookies = _driver.Manage().Cookies.AllCookies;

// If you need to navigate back to the app later, load the cookies first
_driver.Navigate().GoToUrl("your-app-base-url");
foreach (var cookie in loginCookies)
{
    _driver.Manage().Cookies.AddCookie(cookie);
}

// Refresh to apply the cookies and restore the logged-in session
_driver.Navigate().Refresh();

This is especially useful if your test flow involves navigating away and coming back to the app—you won't get redirected to a new login page.


内容的提问来源于stack exchange,提问作者Manish B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:28:07