skip to Main Content

I’m new to selenium webdriver and the programming world.

I’m creating several tests in visual studio, and most of them will have a few steps that will be the same functions, for example Login function.

I put this function in a public void according to the code below

public void Login()
{
    IWebElement inputUsuario = driver.FindElement(By.XPath("//input[@id='username']"));
    inputUsuario.SendKeys("pablo@qms");

    IWebElement inputSenha = driver.FindElement(By.XPath("//input[@id='password']"));
    inputSenha.SendKeys("5550123!");

    IWebElement botaoEntrar = driver.FindElement(By.XPath("//div[@class='full-container']"));
    botaoEntrar.Click();
    Thread.Sleep(2000);

    IWebElement agenda = driver.FindElement(By.XPath("//h3[normalize-space()='Agenda']"));
    agenda.Equals("Agenda");
    Assert.Contains("Agenda", driver.PageSource);
}

Now I would like to call this function in another test in the same project, without having to rewrite all the code
Can you help me to do this?

2

Answers


  1. If the method is in a class the answer should be:

    ClassName.Login();

    Login or Signup to reply.
  2. C# does not have stand-alone functions, the only place you will see a function outside of a class (as far as I´m aware) are in top-level statements, which are just syntax sugar that is wrapped into a static class by the compiler and are most likely not a solution to your issue.

    You should put your function either into a static class

    static class LoginHelper{
        public static void Login(Webdriver drive) //not sure about the class name of driver here
        {
            //login code
        }
    }
    

    or better yet, use a proper object oriented approach

    abstract class BaseTest{
        Webdriver driver;
        public BaseTest(Webdriver driver)
        {
           this.driver = driver;
        }
        public void Login()
        {
            //login code
        }
        public abstract void RunTests();
    }
    
    class Test1 : BaseTest
    {
        public Test1(Webdriver driver) : base(driver)
        {
        }
        public void SomeTest()
        {
            //define additional Tests
        }
        public override void RunTests(){
            Login();
            SomeTest();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search