为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
噜噜哒 2023-12-17 10:22:36
我必须在 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        }    }}'''
查看完整描述

2 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

您可以在 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 将保存在配置文件文件夹中,第二次执行后,您将被记录,您可以调用每个测试,而无需在每个测试中登录


查看完整回答
反对 回复 2023-12-17
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

将 driver.Url = "http:/yoururlhere 添加到 [SetUp],因为它在每次测试之前执行一次

https://nunit.org/docs/2.2.10/fixtureSetup.html


查看完整回答
反对 回复 2023-12-17
  • 2 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信