Tests not appearing in Visual Studio test explorer - c#

I'm having issues setting up my tests. I have tried using a console c# file for my selenium tests which runs the test however it doesn't appear in the test explorer. When I create a unit test c# project it doesn't run or show up in the test explorer. What have done wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SeleniumTests1
{
[TestClass]
class SeleniumTest
{
[TestMethod]
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.bing.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("sb_form_q"));
searchInput.SendKeys("Hello World");
searchInput.SendKeys(Keys.Enter);
searchInput = driver.FindElement(By.Id("sb_form_q"));
string actualvalue = searchInput.GetAttribute("value");
Assert.AreEqual(actualvalue, "Hello World");
driver.Close();
}
}
}

This may work. I think your TestMethod needs to be public and non-static in order for it to appear in Test Explorer.
namespace SeleniumTests1
{
[TestClass]
public class SeleniumTest
{
[TestMethod]
public void Main()
{

You're making a Main method the test method?
Make a separate test project, then reference the project you're testing and move your code to that instead e.g.
namespace Tests
{
[TestClass]
public class MyProjTests
{
[TestMethod]
public void Test{
//your code
}
}
}

Although this one's a rather obvious and straightforward answer, but, looking at the code posted originally by Peter and my own silly mistake I realized that one more place where we can go wrong is by not making our outer test class public without which they would default to internal and the contained tests would not show up in the test explorer. So, the final form of a unit test code would begin with something like this
namespace SeleniumTests1
{
[TestClass]
public class SeleniumTest
{
[TestMethod]
public void testMethod(string[] args)
{

I think I may have managed to resolve the issue in this instance by importing the 4 dlls from the net40 file from the selenium website.

Related

dotnet test command not finding any test to execute in nUnit

I am using 3.12.0 version of nunit and 3.15.1 version of nunit test adapter.
I have created a project in .net and added a simple code in class to run tests.
From Test->Windows->Test Explorer, I am able to view and run test cases but when I try to run from command line, It is not running anything and not giving any error also.
I am not sure what I am missing. Can anyone suggest what could be the possible reason for this?
screenshot
My code looks like this
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpecFlow.API.Test
{
public class Class1
{
[SetUp]
public void setupclass()
{
// Console.ReadLine();
}
[Test]
public void setuptest()
{
Assert.Fail("ERROR");
Console.ReadLine();
}
[TearDown]
public void tearDown()
{
Assert.Fail("ERROR");
}
}
}
```
It seems that you are missing the TestFixture attribute
using System;
using NUnit.Framework;
namespace NUnit.Tests
{
// Add TestFixture attribute
[TestFixture]
public class SuccessTests
{
// ...
}
}

Why am I facing "The type or namespace name 'UnitTestClassBase' could not be found (are you missing a using directive or an assembly reference?)"?

I am using Testleft to automate test scenarios.
Using VS for the 1st time.
This is the code:
############################################################################
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Text;
using SmartBear.TestLeft;
using SmartBear.TestLeft.TestObjects;
using SmartBear.TestLeft.TestObjects.Win;
using System.IO;
namespace TestLeftProject1
{
[TestClass]
public class TestLeftTest : UnitTestClassBase
{
#region Class initializers
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
UnitTestClassBase.InitializeClass(context);
}
[ClassCleanup]
public static void ClassCleanUp()
{
UnitTestClassBase.FinalizeClass();
}
#endregion
[TestMethod]
public void TestMethod1()
{
// Runs the Notepad application
IProcess process = Driver.Applications.Run("notepad.exe");
// Gets Notepad's edit box
IWinTextEdit edit = process.Find<ITopLevelWindow>(new WindowPattern()
{
WndClass = "Notepad"
}).Find<IWinTextEdit>(new WindowPattern()
{
WndClass = "Edit"
});
// Simulates a mouse click in Notepad
edit.Click();
// Simulates text input in Notepad
string inputText = "test";
edit.SetText(inputText);
// Verifies the text that Notepad contains
Assert.AreEqual(inputText, edit.wText);
// Posts messages to the TestLeft test log
Driver.Log.Screenshot(edit, "Notepad's edit box screenshot");
Driver.Log.Warning("A warning message");
// Saves the TestLeft test log
string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), DateTime.Now.ToString("MM_dd_yyyy_H_mm_ss"));
Driver.Log.Save(logPath, Log.Format.Html);
}
}
}
I have tried other solutions like changing the target framework from 4.5 to 4 and 4.5.1.
I am not sure what to do. I am new to VS. Please help
you need to add a class with the name UnitTestClassBase.
Anyway have a look how to write good unit tests. You should also use the pattern Arrange, Act and Assert
You are most likely missing a reference to the assembly SmartBear. To validate this, go to the references in the solution explorer and check this assembly is referenced. If it isn't, add it as a reference.

TestContext is null when running test from a Windows Form

I have an issue related to running CodedUITests from a Windows Form. (it works in the CodedUITestProject with Test-Explorer).
This is my CodedUITest's structure :
[CodedUITest]
public class DBTest
{
#region Static Fields
public static CSVReader csvReader;
#endregion
#region Fields
public string logFileName;
public string timer = String.Empty;
public TestRead testRead;
public UploadResults uploadResults;
private DateTime testStart;
#endregion
[ClassInitialize]
public static void MyTestInitialize(TestContext test)
{
csvReader = new CSVReader();
csvReader.LoadTestValues("steam.csv");
}
[TestInitialize]
public void testInit()
{
testStart = DateTime.Now;
}
[TestMethod(), TestCategory("Reflection"), TestCategory("DataDriven"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", #"|DataDirectory|\CSV's\steam.csv", "steam#csv", DataAccessMethod.Sequential), DeploymentItem(#"..\..\CSV's\steam.csv")]
public void steamAccess()
{
testRead = new TestRead();
SteamMap a = new SteamMap();
testRead.Read(a, TestContext);
}
[TestCleanup]
public void TestCleanup()
{
uploadResults = new UploadResults();
//timer for each test ( in seconds )
double diffSecs = (DateTime.Now - testStart).TotalSeconds;
uploadResults.TestUpload(testRead.TestResults, csvReader.DataTable, diffSecs,TestContext);
}
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
private TestContext testContextInstance;
}
This runs perfectly from VS's Test Explorer, testContextInitialize variable gets initialized.
In the same Solution I've added a second project, a simple Windows Form application, added a reference to my DLL ( from References) which runs the following code :
Playback.Initialize();
DBTest a = new DBTest();
a.steamAccess();
Playback.Cleanup();
NullReferenceException occurs, my testContex is null when I run my test from outside it's assembly.
I need some help in this matter, Thanks
Edit 1:
Test Class :
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using System.Linq;
using System.Reflection;
using SimarpiDB.GLobal;
using SimarpiDB.UITestMaps.SteamMapClasses;
using SimarpiDB.Global;
using System.Data;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("TestLauncher")]
namespace SimarpiDB
{
[CodedUITest]
public class.....
Edit 2:
Temporary workaround until I find the cause of this error :
From my Windows Form I launch a MSTest with few required parameters and most of the what-methods-to-run logic will come from my database. I already did this few months ago but I scraped it because it's an additional performance overhead to use a tool such as MsTest within a launcher such as mine.
For anyone interested, there's a file located within VS's installation directory, it's called VsDevCmd.bat, I load this .bat within a hidden-in-background cmd with few additional commands ( mstest, testcontainer, test). This works but as I said I have no other plausible ideas.
There may also be a lack of referenced libraries within my Form ? Maybe something, a .dll that initialized the testenvironment and the testContext variable.
I wrote this because there may be others seeking the same result.
To clarify on my comment: internal is default in C#, so declaring something as abstract is like declaring it as "internal abstract".
For InternalsVisibleTo, you must make the library project visible to the test project, not the other way around:
[assembly:InternalsVisibleTo("MyTestProject")]

Selenium Test Case writing practice

I am new to automation testing and selenium and have been watching alot of selenium tutorials. I realized that selenium test cases are written in 2 formats and im not sure which one to go with.
1)
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://chapters.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");
driver.FindElement(By.Id("loginCtrl_UserName")).Clear();
driver.FindElement(By.Id("loginCtrl_UserName")).SendKeys("operations");
driver.FindElement(By.Id("loginCtrl_Password")).Clear();
driver.FindElement(By.Id("loginCtrl_Password")).SendKeys("welcome");
driver.FindElement(By.Id("loginCtrl_LoginButton")).Click();
driver.FindElement(By.Id("btnInitialLoad")).Click();
Assert.AreEqual("Chapters", driver.Title);
}
}
}
2)
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace TestProject1
{
public class UnitTest1
{
public void main()
{
FirefoxDriver driver = new FirefoxDriver();
string baseURL = "http://seleniumhq.org/";
driver.Navigate().GoToUrl(baseURL);
driver.FindElement(By.LinkText("Projects")).Click();
driver.FindElement(By.LinkText("Selenium IDE")).Click();
Assert.AreEqual(driver.FindElement(By.XPath("//div[#id='mainContent']/table/tbody/tr/td/p/b")).Text, "Selenium IDE");
driver.Close();
}
}
}
Which one do I go with?
Thanks
The second scenario is simple sequential flow of statements without added advantage of any frameworks like Junit,TestNG,Nunit. It is good for people who have just started with Selenium 2.0 and want to practice with different methods provided by webdriver.
The first scenario is logical division of the code into different annotations provided by Nunit, with these annotations one can get tremendous power of the underlining framework being used, in your case Nunit, these annotation are automatically called by the Nunit framework in a defined order. Apart from this there are multliple other functionalities provided by these frameworks like Reporting,Assertions,Support for Mock Objects,etc
Always use the first scenario for writing Selenium code because along with understanding of the webdriver code, one also gets hang of the underlining framework.

Selenium IE Automation

I'm a beginner in C# and automation. I want to try automate IE with Selenium and NUnit. I was able to lunch IE and navigate to google.com. But from some reason the prog don't find the elementID. Therefore I can't "send keys" to the field. My other problem is how do I submit a form that has no ID or Name.
Here is the code :
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium;
using NUnit.Framework;
using OpenQA.Selenium.Internal;
namespace ClassLibrary1
{
public class Class1
{
public IWebDriver driver;
public string baseUrl;
[SetUp]
public void Setup()
{
baseUrl ="https://www.google.com";
driver = new InternetExplorerDriver();
}
[Test]
public void TestCase1()
{
driver.Navigate().GoToUrl(baseUrl);
System.Threading.Thread.Sleep(500);
driver.FindElement(By.Id("gbqfq")).SendKeys("WhatIsMyIP");
System.Threading.Thread.Sleep(500);
driver.FindElement(By.Id("gbqfba")).Click();
}
[TearDown]
public void TearDown() { }
}
}
I've experienced this issue before with google search. The thing that happens is, as your script sends the keys to get textbox, the "smart search" thing from google comes up, and the element disappears.
Try this, this should work.
[Test]
public void TestCase1()
{
driver.Navigate().GoToUrl(baseUrl);
driver.FindElement(By.Name("q")).SendKeys("WhatIsMyIP");
driver.FindElement(By.Name("btnG")).Click();
}
Observe it for yourself. Perform a search, and watch the DOM.

Categories

Resources