Reputation: 548
I am automating my github profile and Following are my test cases:
namespace GitAutomationTest { using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium.IE; using OpenQA.Selenium.Remote; using System; [TestClass] public class GitTest { private string baseURL = "https://github.com/login"; private RemoteWebDriver driver; public TestContext TestContext { get; set; }
[TestMethod]
public void LoadURL() {
driver.Navigate().GoToUrl(baseURL);
Console.Write("Loaded URL is :" + baseURL);
}
[TestMethod]
public void PerformLogin() {
driver.FindElementById("login_field").SendKeys("USERNAME");
driver.FindElementById("password").SendKeys("PASSWORD");
Console.Write("password entered \n ");
driver.FindElementByClassName("btn-primary").Click();
driver.GetScreenshot().SaveAsFile(@"screenshot.jpg", format: System.Drawing.Imaging.ImageFormat.Jpeg);
Console.Write("Screenshot Saved: screenshiot.jpg");
}
[TestCleanup()]
public void MyTestCleanup()
{
driver.Quit();
}
[TestInitialize()]
public void MyTestInitialize()
{
driver = new InternetExplorerDriver();
driver.Manage().Window.Maximize();
Console.Write("Maximises The window\n");
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
}
}
}
OUTPUT
Everytime I run all tests:
- Test is initialized : the internet explorer is loaded
- The base url is loaded
- Then the driver quits with TestCleanUP()
Next time the driver runs testperformLogin() - The test cannot find the username and password elements to perform login, because the base url is not loaded this time.
How can we manage the TestInitialize() class such that: - browser is up with baseurl until all the tests are completed. How can we manage TestCleanup() such that: - browser closes only after all the test are completed.
Upvotes: 0
Views: 1867
Reputation: 348
You need to move following code to "PerformLogin" test method
driver.Navigate().GoToUrl(baseURL);
OR another approach is to add following code at in "Mytestinitialize" method and remove "LoadURL" method
driver.Navigate().GoToUrl(baseURL);
You are facing the issue since [TestInitialize] is called before every [TestMethod] and [TestCleanup] is called after every [TestMethod].
In your case "LoadURL" test is able to get the URL but "PerformLogin" is not able to get the URL since it is not mentioned in "MyTestInitialize".
Upvotes: 0
Reputation: 920
There is a AssemblyCleanup
attribute which runs after all the tests are executed.
You can find more info on attributes here - Unit Testing Framework.
Upvotes: 0