selenium C#:如何在测试方法中跳过登录

我必须在 C# Selenium 中测试一个 Web 应用程序,并且所有功能都需要在测试之前登录。有什么方法可以在测试中跳过登录步骤吗?因为它们在重复并浪费时间...我已经阅读了有关将登录详细信息保存到 cookie 的信息,但不确定如何以及在何处添加 cookie 以及如何在测试方法中调用它们。另外,如果我使用 cookie,我将无法通过在其中添加 [Parallelizable] 来并行运行它们


namespace ParallelGrid {


[TestFixture]

[Parallelizable]

public class ParallelGrid1

{

    public static IWebDriver driver;

      [SetUp]

       public void Setup()

       {

          ChromeOptions options = new ChromeOptions();

          driver = new ChromeDriver();

       }


    [Test]

    public void Test1()

    {

        driver.Navigate().GoToUrl(" ");

        //enter username

        //enter password

        //press submit

       //go to home screen

       //perform test 1

    }


    [Test]      

        public void Test2()

        {         

        driver.Navigate().GoToUrl(" ");

        //enter username

        //enter password

        //press submit

        //go to home screen

        //perform test 2

        }


       [Test]      

        public void Test3()

        {         

        driver.Navigate().GoToUrl(" ");

        //enter username

        //enter password

        //press submit

        //go to home screen

        //perform test 3

        }

    }

}'''


噜噜哒
浏览 73回答 2
2回答

慕码人8056858

您可以在 chromeoptions 中使用 user-data-dir 来保存配置文件数据,您可以在每次测试的初始化时检查您是否已登录。例子: public void Setup ( ){    string ProfileDirect=Directory.GetCurrentDirectory()+"\\MyProfile";    if ( !Directory.Exists ( ProfileDirect ) )    {        //create data folder if not exist         Directory.CreateDirectory ( ProfileDirect );    }    // Create new option with data folder     var options=new ChromeOptions();    options.AddArgument ( @"user-data-dir="+ProfileDirect );    // Instance new Driver , with our current profile data.    Driver=new ChromeDriver(options);    if ( !IsLoggedIn ( ) )    {        Login ( );    }}public bool IsLoggedIn ( ){    // Check if button logout is visible    return Driver.FindElement(By.XPath ( "//a[contains(@href,'logout')]" ))!=null;}public void Login ( ){    //Some code to login}第一次执行后,cookie 将保存在配置文件文件夹中,第二次执行后,您将被记录,您可以调用每个测试,而无需在每个测试中登录

吃鸡游戏

将 driver.Url = "http:/yoururlhere 添加到 [SetUp],因为它在每次测试之前执行一次https://nunit.org/docs/2.2.10/fixtureSetup.html
打开App,查看更多内容
随时随地看视频慕课网APP