NUNIT 3.10.1 C# Selenium - c#

I am only able to execute the 1st test methods. All subsequent test methods fail to execute even though the code is correct. See attached image for error message. Using test.sdk(15.8.0), NUNIT(3.10.1), Selenium.WebDriver(3.13.0), Selenium.IEDriverServer.win64(3.9.0),Selenium.InternetExplorer.WebDriver(3.3.0)
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
using System;
using OpenQA.Selenium.Interactions;
using System.Threading;
namespace Tests
{
public class LandingPage
{
IWebDriver driver = new InternetExplorerDriver("C:\\Users\\M\\Desktop\\SL\\SLAutomation\\Core\\CoreLandingPage\\CoreLandingPage\\CoreLandingPage\\Drivers\\");
[SetUp]
public void Initialize()
{
driver.Navigate().GoToUrl("http://www.google.com");
Console.WriteLine("Opened URL");
}
[Test]
public void TestCase1()
{
Assert.That(2+2, Is.EqualTo(4));
Console.WriteLine("Test case 1");
}
[Test]
public void TestCase2()
{
Assert.That(2 * 2, Is.EqualTo(4));
Console.WriteLine("Test case 2");
}
[TearDown]
public void CleanUp()
{
driver.Close();
Console.WriteLine("Closed Browser");
}
}
}

You need to instantiate the driver in the method Initialize() tagged with [SetUp]. The error happens because at the end of TestCase1(), CleanUp() is called and the driver is closed. Then TestCase2() comes along and Initialize() is called but the driver no longer exists. You can verify this by commenting out the driver.Close(); line in CleanUp().
Your code should look more like
public class LandingPage
{
IWebDriver driver;
[SetUp]
public void Initialize()
{
driver = new InternetExplorerDriver("C:\\Users\\M\\Desktop\\SL\\SLAutomation\\Core\\CoreLandingPage\\CoreLandingPage\\CoreLandingPage\\Drivers\\");
driver.Navigate().GoToUrl("http://www.google.com");
Console.WriteLine("Opened URL");
}
...

Related

Driver is going null, not sure whats wrong. Selenium C#: Console App (.Net Core 2.0)

Selenium C#: Getting error "Make sure test project has a nuget reference of package "Microsoft.NET.Test.Sdk" and framework version settings are appropriate. Rerun with /diag option to diagnose further."
Project Structure: Console App (.Net Core 2.0)
Here is my main code:
using NUnit.Framework;
using OpenQA.Selenium;
using System.Threading;
namespace Portal
{
class Program
{
private IWebDriver driver;
public Program()
{
driver = BaseDriver.GetDriver();
}
private static void Main(string[] args)
{
}
[SetUp]
public void Initialize()
{
driver.Navigate().GoToUrl("https://Portal.com");
}
[Test]
public void ExecuteTests()
{
driver.FindElement(By.Id("UserName")).SendKeys("Admin");
driver.FindElement(By.Id("Password")).SendKeys("Admin");
driver.FindElement(By.XPath(
"html/body/div[3]/div/div/form/div/div[4]/button/span")).Click();
}
}
}
Here is my Driver Class Definition:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace portal
{
class BaseDriver
{
private static IWebDriver driver;
public static IWebDriver GetDriver()
{
if (driver == null)
{
driver = new ChromeDriver(#"C:\SeleniumC#\portal\portal");
driver.Manage().Window.Maximize();
}
return driver;
}
}
}

I am trying to run a test on multiple Browsers using MSTest and Selenium

I am simultaneously teaching myself Selenium 3.0 and Programming to learn how to Automate my tests (previously a manual tester with no IT background, fell into testing via UAT).
I have successfully written a handful of tests all of which work :). I can define which browser to run the test set on, but cant run the test set on multiple browsers as 1 test run. (I have to define the browser in my Test Initialise and comment out the other browsers). When I try to run the test on 2 browsers at once Browser A opens but nothing runs, Browser B then opens and runs the tests.
I have looked through the posts on this site and on google generally but have not found a clear answer to how to get this to work using MSTest and Semenium in C#
My Code
One of my tests
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Kukd_Consumer_Tests;
namespace Kukd_Consumer_Test
{
//login from Hompage
[TestClass]
public class Login : Consumer_Standard_Functionality
{
[TestMethod]
public void User_Can_Login()
{
LoginPage.LoginAs("Richard.Cariven#Kukd.Com").WithPassword("Test1234").Login();
Assert.IsTrue(AccountPageAssert.IsAtAccountPage("Hi Richard"), "Failed to login");
}
}
}
My std Functionality Test Class (Initialise and Cleanup steps)
using Kukd_Consumer_Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kukd_Consumer_Test
{
public class Consumer_Standard_Functionality
{
[TestInitialize]
public void Init()
{
driver.InitializeChrome();
driver.InitializeFireFox();
Homepage.GoTo_HomePage();
}
[TestCleanup]
public void Cleanup()
{
driver.Quit();
}
}
}
My driver class
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Remote;
using System;
namespace Kukd_Consumer_Tests
{
public class driver
{
public static IWebDriver Instance { get; set; }
public static void InitializeChrome()
{
Instance = new ChromeDriver(#"C:\Users\xxxxxxxxx.xxxxxxxx\Documents\Visual Studio 2015\Drivers\Chrome");
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
public static void InitializeFireFox()
{
Instance = new FirefoxDriver();
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
public static void Quit()
{
Instance.Quit();
}
}
}
My LoginPage class
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kukd_Consumer_Tests
{
public class LoginPage
{
public static LoginCommand LoginAs(string userName)
{
return new LoginCommand(userName);
}
public class LoginCommand
{
private readonly string userName;
private string password;
public LoginCommand(string userName)
{
this.userName = userName;
}
public LoginCommand WithPassword(string password)
{
this.password = password;
return this;
}
public void Login()
{
var accountButton = driver.Instance.FindElement(By.LinkText("My Account"));
accountButton.Click();
var loginInput = driver.Instance.FindElement(By.Id("login-email"));
loginInput.SendKeys(userName);
var passwordInput = driver.Instance.FindElement(By.Id("login-password"));
passwordInput.SendKeys(password);
var loginButton = driver.Instance.FindElement(By.Id("loginBtn"));
loginButton.Click();
}
}
}
}
When I run the above Chrome opens a blank window and does nothing more. Firefox opens the homepage, then runs the test as expected and closes the window when done.

Is there a way to continue your test without logging in again in selenium. C#

Hi this may be related to an issue I was having with the driver initiating a blank page. I'd like to get my tests flowing in a way where I don't have to login everytime. Or is that the norm? In my code below Test method LoginToWordpress() works and passes. CreateAPost() fires a blank instance of firefox. Is there a way around this?
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace WordpressAutomation
{
[TestClass]
public class WordpressTests
{
IWebDriver driver;
[TestInitialize]
public void GoToWordpress()
{
//Create an instance of the firefox driver.
driver = new FirefoxDriver();
driver.Manage().Window.Maximize();
}
[TestMethod]
public void LoginToWordPress()
{
driver.Navigate().GoToUrl("https://moodpk01.wordpress.com/wp-login.php");
driver.FindElement(By.Id("user_login")).SendKeys("");
driver.FindElement(By.Id("user_pass")).SendKeys("");
driver.FindElement(By.Id("wp-submit")).Click();
string actualvalue = driver.FindElement(By.Id("wp-admin-bar-blog")).Text;
Assert.AreEqual(actualvalue, "My Site");
}
[TestMethod]
public void CreateAPost()
{
driver.FindElement(By.ClassName("wp-menu-name")).Click();
driver.FindElement(By.ClassName("page-title-action")).Click();
}
[TestCleanup]
public void Teardown()
{
//driver.Close();
}
}
}
Take this code:
driver.Navigate().GoToUrl("https://moodpk01.wordpress.com/wp-login.php");
driver.FindElement(By.Id("user_login")).SendKeys("");
driver.FindElement(By.Id("user_pass")).SendKeys("");
driver.FindElement(By.Id("wp-submit")).Click();
in TestInitialize() method, that way, it will execute only at the start of test. Assuming you can continue with logging only once !!

How to de-cypher structure of Selenium Scripts exported from IDE - NUnit Framework

I'm new to writing test scripts so I apologize for my lack of understanding here, I'm certainly willing to learn though!
I've recorded a number of scripts in the Selenium IDE, but have found it lacking in flexibility (a reliance on static UI elements for example) so I'm going to swap to writing scripts in Selenium WebDriver.
To avoid the complexity of recreating all of these test cases from the ground up I plan on exporting my existing test cases in C# with NUnit and modifying the scripts from there. But the scripts spat out by the IDE are structured in a way I'm not familiar with.
Here's a script that I wrote from scratch, that should help explain my linear understanding:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using System;
namespace UnitTestProject
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
}
}
}
class GoogleSuggest
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
driver.Navigate().GoToUrl("http://website.com/account/Login.aspx");
IWebElement query = driver.FindElement(By.Name("LoginForm$UserName"));
query.SendKeys("username");
query = driver.FindElement(By.Name("LoginForm$Password"));
query.SendKeys("password");
System.Threading.Thread.Sleep(500);
driver.FindElement(By.Name("LoginForm$Button1")).Click();
System.Threading.Thread.Sleep(1500);
action.ContextClick(driver.FindElement(By.Id("uielementid"))).Perform();
}
}
That's a script I wrote that signs in to a website. What I understand about that script is that it starts up a Firefox instance with the lines
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
It has a Main where the application starts, then using referential commands it starts up Firefox. please correct me if I'm wrong here
However, when I export cases from the IDE into C# with the NUnit Framework and copy it into a test project in VS I can't find where to put my Main to make the program compilable. The test case reads:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTests
{
[TestFixture]
public class Login
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://website.com/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheLoginTest()
{
driver.Navigate().GoToUrl(baseURL + "/account/Login.aspx");
driver.FindElement(By.Id("LoginForm_UserName")).Clear();
driver.FindElement(By.Id("LoginForm_UserName")).SendKeys("username");
driver.FindElement(By.Id("LoginForm_Password")).Clear();
driver.FindElement(By.Id("LoginForm_Password")).SendKeys("password");
driver.FindElement(By.Id("LoginForm_Button1")).Click();
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText() {
try {
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert) {
alert.Accept();
} else {
alert.Dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
}
I've not been able to find where to insert my Main in this test case, nor (perhaps more importantly) do I understand this structure.
Any help or feedback is appreciated, thank you!

WebDriver i am trying to use isElementPresent but error shows not exist in the current context

I am new to WebDriver and writing this code in C# Visual Studio (code snippet below)
I am verifying if a text field is present on the home page using IsElementPresent.
I get the error The name IsElementPresent does not exist in the current context.
What am i doing wrong?
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace Homepage_check2
{
[TestFixture]
public class Driver
{
IWebDriver driver;
[SetUp]
public void Setup()
{
// Create a new instance of the Firefox driver
driver = new FirefoxDriver();
}
[TearDown]
public void Teardown()
{
driver.Quit();
}
[Test]
public void homepage()
{
//Navigate to the site
driver.Navigate().GoToUrl("http://www.milkround.com");
Assert.IsTrue(IsElementPresent(By.Id("ctl00_uxToolbar_uxQueryTextBoxToolbar")));
}
catch
{
//verificationErrors.Append(e.Message);
}
}
}
}
Where does "IsElementPresent" come from? I have never seen that used in WebDriver.
In WebDriver you need to do wrap a try catch around the findElement method.
e.g
Boolean elementDisplayed;
try {
WebElement element = driver.findElement(By.Id("ctl00_uxToolbar_uxQueryTextBoxToolbar"));
elementDisplayed = element.displayed;
}
catch (NoSuchElementException e) {
elementDisplayed = false;
}
Obviously you can wrap this in a helper method of some kind of perhaps add it to the WebDriver classes.
I'll leave that to you, but this is the general idea

Categories

Resources