Selenium c#: reuse existing browser session, instead of opening new windows? - c#

How can i run all test methods in single browser session instead of opening and closing browser for each test method using selenium c#.
E.g.
[TestInitialize]
public void Startup()
{
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://testurl:2022");
driver.FindElement(By.XPath("//a[contains(#id, 'tabDrugDimention')]")).Click();
System.Console.WriteLine("Dimension page loaded");
driver.FindElement(By.XPath("//a[contains(text(), 'Testcontent')]")).Click();
System.Console.WriteLine("Drug Item clicked");
}
[TestMethod]
public void DrugAnalysisclick()
{
...
}
[TestMethod]
public void DrugAnalysisclick()
{
...
}
[TestCleanup]
public void TearDown()
{
driver.Quit();
}
For all test method, new browser window is opening and getting closed for each test method.
Can anyone help, how to run all test method in single browser?
Thanks in advance.

You just have to reuse the same driver for every test instead of calling driver.Quit() after each test. As pointed out in the comments you have to be careful with this as you break up the test isolation by reusing the driver.

Related

Selenium grid mixing up tests between browsers

Lets say i have to open google in 2 browsers, search Test1 in 1st, search Test 2 in 2nd. It opens 2 browsers, writes Test1Test2 in one browser and pass the test. how do i get around it?
it works well if i declare driver in every test function, but this cannot be done if i want to use RemoteWebDriver later to run it on different machines.(because it then uses only one node and doesn't do anything on other) Heard about using non static browser as well, but not sure how to use it, and not sure if that is solution of the problem?
namespace ParallelGrid
{
[TestFixture]
[Parallelizable]
public class ParallelGrid1
{
[ThreadStatic]
public static IWebDriver driver;
[SetUp]
public void Setup()
{
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver();
// driver = new RemoteWebDriver(new Uri("http://xxx.xxx.xx.xxx:4444/wd/hub"), options.ToCapabilities(), TimeSpan.FromSeconds(600));//hub id goes here
}
[Test]
[Parallelizable]
public void Test1()
{
driver.Navigate().GoToUrl("https://www.google.com");
driver.FindElement(By.Name("q")).Click();
driver.FindElement(By.Name("q")).SendKeys("Test");
}
[Test]
[Parallelizable]
public void Test2()
{
driver.Navigate().GoToUrl("https://www.google.com");
driver.FindElement(By.Name("q")).Click();
driver.FindElement(By.Name("q")).SendKeys("Grid");
}
}
}
For parallelization to work with NUnit and C# you can only parallelize on Test class at a time. So you have to have one test per class.
https://github.com/nunit/nunit/issues/2252

Nunit Selenium Parallel Tests with Values

I'm trying to run the same nunit Test method with different values in parallel. However the second test seems to fail (i think it's trying to use the first instance of the browser;
This is the test;
namespace AutomationProject.Login_Test_Cases
{
[TestFixture]
[Parallelizable(ParallelScope.Children)]
class Login_Test_Cases: BaseTest
{
[Test]
public void LoginPar([Values("skynet" ,"skynet2")] string username)
{
lg.Log_In(username, "password");
}
}
}
This is the baseTest where the browser is set up;
namespace AutomationProject.BaseClasses
{
public class BaseTest
{
public Log_In_Methods lg;
public IWebDriver driver;
[SetUp]
public void StartBrowser()
{
System.Diagnostics.Trace.AutoFlush = true;
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("useAutomationExtension", false);
driver = new ChromeDriver(//path to chrome driver);
lg = new Log_In_Methods(driver);
driver.Manage().Window.Maximize();
driver.Url = "http://login-test.com";
}
I've also added [assembly: Parallelizable(ParallelScope.Children)]
[assembly: LevelOfParallelism(2)] to AssemblyInfo
The second test always seems to fail (the browser does not even get the url)
I can run different classes and tests in parallel with no issues.
Does anyone know if it's possible to run the same test method in parallel with different values?
Does anyone know if it's possible to run the same test method in parallel with different values?
This is absolutely possible. The issue here is that both tests run in parallel on a single instance of the BaseTest class, and thus you only have a lg field which both tests are trying to create/use simultaneously.
Being able to run the two separate tests with two separate BaseTest objects is an open feature request, see here: https://github.com/nunit/nunit/issues/2574
In the meantime, if you were to include your [SetUp] logic within your test method and use local variables, what you're trying to do should work.

Having issues initialising my selenium tests using the [TestInitialize]

I've been attempting to learn selenium in c# and in the past day or so it's developed into using the testinitialize. Before I ran everything from my test method and it worked great the long term goal is for me to be able to load a page on the initialize then login in one test add posts on another test etc. I don't want to be loading up and logging in every time I'd like it to be free flowing from the point of logging in. At the moment I'm getting something in the wrong place as now it's just firing up a blank firefox page and doing nothing. I've kept it simple at the moment so I can get to grips with it. So the code below should load up wikipedia and check for some text in the heading.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumPractice
{
[TestClass]
public class Setup
{
IWebDriver driver;
[TestInitialize]
public void GoToWiki()
{
//Create an instance of the firefox driver.
IWebDriver driver = new FirefoxDriver();
}
[TestMethod]
public void VerifyHelloWorld()
{
driver.Navigate().GoToUrl("https://en.wikipedia.org/wiki/%22Hello,_World!%22_program");
driver.Manage().Window.Maximize();
string actualvalue = driver.FindElement(By.Id("firstHeading")).Text;
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
Assert.AreEqual(actualvalue, "\"Hello, World!\" program");
}
[TestCleanup]
public void Teardown()
{
driver.Close();
}
}
}
Also I'm getting a green line under IwebDriver driver; in my class. With this error.
field 'seleniumPractice.Setup.driver' is never assigned to, and always have its default value null
I put this here because i noticed the test method didn't recognise the driver anymore when I moved it out of the test method.
The reason for the compiler warning and the blank Firefox window is that you are not actually assigning the driver field with a reference to a new FirefoxDriver object in GoToWiki(), you are actually declaring a new variable that is scoped only to that method and assigning a reference to a new FirefoxDriver object to that variable. The field is null when you call GoToUrl on it in VerifyHelloWorld(). Try this edit:
[TestInitialize]
public void GoToWiki()
{
//Create an instance of the firefox driver.
driver = new FirefoxDriver();
}

How to distinguish between testsuite and testcase on the report

Using Selenium C# web driver with NUnit for automation. I am generating Allure report using command line and my report gets fantastically created but I need help on the following issue:
I have the following structure using Page object model (2 Test and 1 Page). Now when I see the report it shows at the top Test run (2 testsuites, 2 testcases) and each testcase is a testsuite. I want it to say 1 testsuites, 2 testcases. How do I do that?
namespace ApplicationName.TestCases
{
[TestFixture]
class VerifyCreateOrder
{
IWebDriver driver;
[SetUp]
public void Initialize()
{
driver = new FirefoxDriver();
}
[TestCase]
public void doCreateOrder()
{
LoginPage loginPage = new LoginPage();
//some Assertion
}
}
}
namespace ApplicationName.TestCases
{
[TestFixture]
class SearchOrder
{
IWebDriver driver;
[SetUp]
public void Initialize()
{
driver = new FirefoxDriver();
}
[TestCase]
public void doSearchOrder()
{
LoginPage loginPage = new LoginPage();
//some Assertion
}
}
}
The below is my LoginPage Page object:
namespace ApplicationName.Pages
{
class LoginPage
{
public void doLogin(IWebDriver driver, String username, String password)
{
driver.Navigate().GoToUrl("http://www.myxyzsite.com");
driver.FindElement(By.Id("xyz")).SendKeys(username);
driver.FindElement(By.Id("xyz")).SendKeys(password);
driver.FindElement(By.Id("xyz")).Click();
}
}
}
I read about the NUnit suite attribute at http://www.nunit.org/index.php?p=suite&r=2.5.5 and created a c# class with enumerator as described but how do i call it/wire it? What changes do I need to make for my test classes?
namespace NUnit.Tests
{
public class MyTestSuite
{
[Suite]
public static IEnumerable Suite
{
get
{
ArrayList suite = new ArrayList();
suite.Add(new VerifyCreateOrder());
suite.Add(new SearchOrder());
return suite;
}
}
}
}
I want it to say 1 testsuites, 2 testcases. How do I do that?
Without adding a Suite or similar, you could put both Test cases into the same TestFixture, since that's what the testsuite output is built from. You may be able to do that using a partial class, or you can simply conflate the two classes. However, your Suite solution is a better choice.
What changes do I need to make for my test classes?
Call NUnit with the option /fixture:NUnit.Tests.MyTestSuite.
Note that all of this has changed with NUnit 3 and the Suite attribute is gone. I can't see any way to do what you want in NUnit 3 short of reorganizing your test cases.
If it's very important to merge tests into suites, you can use XSLT. The NUnit test result schema is quite straightforward and easy to manipulate using XSLT.

NUnit, TestDriven.NET, WatiN and Specflow

I am trying to do some BDD testing using Specflow, NUnit and WatiN. I am using TestDriven.NEt to run the test. Here is my first test:
[Binding]
[TestFixture, RequiresSTA]
public class RegisterUserSteps
{
private IE _ie = new IE();
[When(#"the user visits the registration page")]
public void WhenTheUserVisitsTheRegistrationPage()
{
_ie.GoTo("http://localhost:1064/Register/");
}
[When(#"enter the following information")]
public void WhenEnterTheFollowingInformation(Table table)
{
foreach(var tableRow in table.Rows)
{
var field = _ie.TextField(Find.ByName(tableRow["Field"]));
if(!field.Exists)
{
Assert.Fail("Field does not exists!");
}
field.TypeText(tableRow["Value"]);
}
}
[When(#"click the ""Register"" button")]
public void WhenClickTheRegisterButton()
{
ScenarioContext.Current.Pending();
}
[Then(#"the user should be registered")]
public void ThenTheUserShouldBeRegistered()
{
ScenarioContext.Current.Pending();
}
}
The problem is that it never goes to the
[When(#"enter the following information")]
public void WhenEnterTheFollowingInformation(Table table)
It just launches the browser and perform the first step. Am I missing something?
Without looking at the test, it seems you are missing an important step (Given). Usually it is like this:
Given I go to some page
And all the set up data are available - optional
When I enter the following info
And I click "Register" button
Then I see something
Basically the steps are GWT (Given, When, Then). It's Gherkin language, so if you google for it you'll see more info. When you have multiple things for a given step, you have to use And, example, When ...... And......., not When...... When........

Categories

Resources