如何在使用C#(Selenium)进行身份验证时处理错误的凭据?

gpfsuwkq  于 2023-01-26  发布在  C#
关注(0)|答案(1)|浏览(146)

我学习自己编写Selenium C#自动测试。现在我尝试转到身份验证页面并发送错误的凭据,提交并检查页面上的"未授权"文本。看起来很简单,但问题是当我将凭据发送到驱动程序时,身份验证弹出窗口出现,但是没有用户和密码输入。毕竟我得到了OpenQA.Selenium.NoAlertPresentException : no such alert的消息。在C#中有什么简单的方法来解决这个问题吗?
下面是我的代码:

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.Support.UI;

namespace Selenium2.Authorisation
{
    public class Authorisation
    {
        IWebDriver driver;

        [SetUp]
        public void Setup()
        {
            driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            driver.Manage().Window.Maximize();
        }        

[Test]
        public void SendWrongUsernameToAuthenticationPopupTest()
        {
            String username = "abc";
            String password = "admin";

            String URL = "https://" + username + ":" + password + "@" + "the-internet.herokuapp.com/basic_auth";
            driver.Navigate().GoToUrl(URL);

            //tried this but received error: OpenQA.Selenium.NoAlertPresentException : no such alert
            IAlert alert = driver.SwitchTo().Alert();
            alert.SendKeys(username);
            alert.Accept();

            driver.Manage().Timeouts().Equals(TimeSpan.FromSeconds(5));

            String text = driver.FindElement(By.TagName("p")).Text;

            String expectedText = "Not authorized";
            IWebElement p2 = driver.FindElement(By.TagName("body"));
            Assert.AreEqual(expectedText, p2.Text, "The unauthorised texts are not the same");
        }
shyt4zoc

shyt4zoc1#

通过Basic Authentication,用户可以登录。除非明确要求登录,否则不再需要对用户进行身份验证。

[Test]
    public void SendWrongUsernameToAuthenticationPopupTest()
    {
        String username = "abc";
        String password = "admin";

        String URL = "https://" + username + ":" + password + "@" + "the-internet.herokuapp.com/basic_auth";
        driver.Navigate().GoToUrl(URL);
        driver.Manage().Timeouts().Equals(TimeSpan.FromSeconds(5));
        String text = driver.FindElement(By.TagName("p")).Text;
        String expectedText = "Not authorized";
        IWebElement p2 = driver.FindElement(By.TagName("body"));
        Assert.AreEqual(expectedText, p2.Text, "The unauthorised texts are not the same");
    }

相关问题