I am a fresher in Selenium. I have lots of doubt about Selenium functions. I am using Selenium RC with Java and Eclipse.
I need to write one simple function for adding two numbers. Where will I write that function inside the test()?
How can I call that function if we want any other object for this function? Do we need to declare any header file for calling this function? Please help me.
I would look at this helpful tutorial part 1, part 2
Lets say the function is:
public void waitForElementExistance(final String elementLocator,
final int seconds, final boolean exists) throws Exception {
waitTimeFor(new Condition() {
#Override
public boolean verify() {
return selenium.isElementPresent(elementLocator) == exists;
}
}, 10);
}
You write this function -- for example -- just above the test()
You can call it in your test() like this:
waitForElementExistance("css=div.buttonlabel:contains(Upload)", 10, true);
Related
I am very new to Java, and I have been tasked with creating Junit5 tests for already written code. To start, I have the below method that I need to write a test for. I am unsure how to approach a test for this method.
public static Double getFormattedDoubleValue(Number value){ return getFormattedDoubleValue(value, -1); }
I tried the below test, and it passes, but I feel like I am testing the wrong thing here.
#Test
public void testDoubleString() {
Double num = 41.1212121212;
String expected = "41.12";
String actual = String.format("%.2f", num);
assertEquals(expected, actual, "Should return 41.12");}
Writing tests are simpler than they are sometimes made out to be, all it is is just calling your code from a test class instead of a business logic class and making sure that you get the right output based on what you input.
Here is an excellent article that will take you from the very beginning of the process: Baeldung: JUnit 5
Possible Sample Test
As I'm not quite certain what the expectations of your method are, I am just going to pretend that your method should take a Double, and return that number minus one:
#Test
void getFormattedDoubleValue_Test() {
Double expected = 5.0L
Double actual = getFormattedDoubleValue(expected + 1L)
assertEquals(expected, actual)
}
I'm using maven and selenium for testing in java. I would like to know if there is a way to call a function every time a test fails. I already have a function that takes an screenshot of the browser. I would like to use it every time selenium throws NoSuchElNoSuchElementExeption for example.
Is there an "easy" way to implement this?
Thank you!
You can create a method to find the element and implement a try-catch block inside that to catch the NoSuchElementException. Call your function to take the screenshot inside that catch block.
e.g.
public WebElement findElement(By locator) {
try {
WebElement element = driver.findElement(locator);
return element;
} catch (NoSuchElementException nse) {
// call the function to take a screenshot
}
}
I eventually found this solution to the problem:
https://darrellgrainger.blogspot.com/2011/02/generating-screen-capture-on-exception.html?m=1
Consists on using WebDriverEventListener.
I want to pass an integer variable to web element using Sendkey function and i'm getting that integer vaiable from another class and passing through a method and calling in sendkey funciton but getting type casting error.
I'm very new to selenium. Please help me to improve my selenium knowledge wider. Attached screen shot for your better understand.
public static WebElement setQuantityPage(WebDriver driver,int **individual_units**,int noOFCaseUnit, int noOfBox)
{
Select packType = new Select(driver.findElement(By.xpath(".//*[#id='fba-core-view-meta-data-pkg-type']/**strong text**dl/dd[1]")));
packType.selectByVisibleText("Individual products");
String type=packType.toString();
if(type.equalsIgnoreCase("Individual products"))
{
driver.findElement(By.xpath(".//*[#id='batch-update-number-cases']")).sendKeys(**individual_units**);
}
I'm asking for above bold letters.
else
{
}
return element;
}
Sendkeys methods takes only CharSequence as it's parameter. But your are passing an integer as an argument. That's why you are getting a type casting error. Replacing
driver.findElement(By.xpath(".//[#id='batch-update-number-cases']")).sendKeys(individual_units);
with
driver.findElement(By.xpath(".//[#id='batch-update-number-cases']")).sendKeys(individual_units+"");
or
driver.findElement(By.xpath(".//[#id='batch-update-number-cases']")).sendKeys(String.valueOf(individual_units));
will resolve your problem.
Environment:
I have a program - named CSIS - which I need to run a lot of automated tests on in Visual Studio 2010 using C#. I have a series of functions which need to be run in many different orders but which all start and end at the same 'home screen' of CSIS. The tests will either be run on their own as a single CodedUITest (.cs filetype) or as an ordered test (.orderedtest filetype).
Goal:
The goal is to open to the CSIS homepage once no matter which of the unit tests is run first and then, after all CodedUITests are finished, no matter which unit test is last, the automated test will close CSIS. I don't want to create a separate unit test to open CSIS to the homepage and another to close CSIS as this is very inconvenient for testers to use.
Current Solution Development:
UPDATE: The new big question is how do I get '[ClassInitialize]' to work?
Additional Thoughts:
UPDATE: I now just need ClassInitialize to execute code at the beginning and ClassCleanUp to execute code at the end of a test set.
If you would like the actual code let me know.
Research Update:
Because of Izcd's answer I was able to more accurately research the answer to my own question. I've found an answer online to my problem.
Unfortunately, I don't understand how to implement it in my code. I pasted the code as shown below in the 'Code' section of this question and the test runs fine except that it executes the OpenWindow() and CloseWindow() functions after each test instead of around the whole test set. So ultimately the code does nothing new. How do I fix this?
static private UIMap sharedTest = new UIMap();
[ClassInitialize]
static public void ClassInit(TestContext context)
{
Playback.Initialize();
try
{
sharedTest.OpenCustomerKeeper();
}
finally
{
Playback.Cleanup();
}
}
=====================================================================================
Code
namespace CSIS_TEST
{
//a ton of 'using' statements are here
public partial class UIMap
{
#region Class Initializization and Cleanup
static private UIMap sharedTest = new UIMap();
[ClassInitialize]
static public void ClassInit(TestContext context)
{
Playback.Initialize();
try
{
sharedTest.OpenWindow();
}
finally
{
Playback.Cleanup();
}
}
[ClassCleanup]
static public void ClassCleanup()
{
Playback.Initialize();
try
{
sharedTest.CloseWindow();
}
finally
{
Playback.Cleanup();
}
}
#endregion
Microsoft's unit testing framework includes ClassInitialise and ClassCleanUp attributes which can be used to indicate methods that execute functionality before and after a test run.
( http://msdn.microsoft.com/en-us/library/ms182517.aspx )
Rather than try and make the unit tests aware of their position, I would suggest it might be better to embed the opening and closing logic of the home screen within the aforementioned ClassInitialise and ClassCleanUp marked methods.
I figured out the answer after a very long process of asking questions on StackOverflow, Googling, and just screwing around with the code.
The answer is to use AssemblyInitialize and AssemblyCleanup and to write the code for them inside the DatabaseSetup.cs file which should be auto-generated in your project. You should find that there already is a AssemblyInitialize function in here but it is very basic and there is no AssemblyCleanup after it. All you need to do is create a static copy of your UIMap and use it inside the AssemblyInitialize to run your OpenWindow() code.
Copy the format of the AssemblyInitialize function to create an AssemblyCleanup function and add your CloseWindow() function.
Make sure your Open/CloseWindow functions only contains basic code (such as Process.Start/Kill) as any complex variables such as forms have been cleaned up already and won't work.
Here is the code in my DatabaseSetup.cs:
using System.Data;
using System.Data.Common;
using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Data.Schema.UnitTesting;
using System.Windows.Input;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using Mouse = Microsoft.VisualStudio.TestTools.UITesting.Mouse;
using MouseButtons = System.Windows.Forms.MouseButtons;
namespace CSIS_TEST
{
[TestClass()]
public class DatabaseSetup
{
static private UIMap uIMap = new UIMap();
static int count = 0;
[AssemblyInitialize()]
public static void InitializeAssembly(TestContext ctx)
{
DatabaseTestClass.TestService.DeployDatabaseProject();
DatabaseTestClass.TestService.GenerateData();
if(count < 1)
uIMap.OpenWindow();
count++;
}
[AssemblyCleanup()]
public static void InitializeAssembly()
{
uIMap.CloseWindow();
}
}
}
I am experimenting with WatiN for our UI testing, I can get tests to work, but I can't get IE to close afterwards.
I'm trying to close IE in my class clean up code, using WatiN's example IEStaticInstanceHelper technique.
The problem seems to be attaching to the IE thread, which times out:
_instance = IE.AttachTo<IE>(Find.By("hwnd", _ieHwnd));
(_ieHwnd is the handle to IE stored when IE is first launched.)
This gives the error:
Class Cleanup method
Class1.MyClassCleanup failed. Error
Message:
WatiN.Core.Exceptions.BrowserNotFoundException:
Could not find an IE window matching
constraint: Attribute 'hwnd' equals
'1576084'. Search expired after '30'
seconds.. Stack Trace: at
WatiN.Core.Native.InternetExplorer.AttachToIeHelper.Find(Constraint
findBy, Int32 timeout, Boolean
waitForComplete)
I'm sure I must be missing something obvious, has anyone got any ideas about this one?
Thanks
For completeness, the static helper looks like this:
public class StaticBrowser
{
private IE _instance;
private int _ieThread;
private string _ieHwnd;
public IE Instance
{
get
{
var currentThreadId = GetCurrentThreadId();
if (currentThreadId != _ieThread)
{
_instance = IE.AttachTo<IE>(Find.By("hwnd", _ieHwnd));
_ieThread = currentThreadId;
}
return _instance;
}
set
{
_instance = value;
_ieHwnd = _instance.hWnd.ToString();
_ieThread = GetCurrentThreadId();
}
}
private int GetCurrentThreadId()
{
return Thread.CurrentThread.GetHashCode();
}
}
And the clean up code looks like this:
private static StaticBrowser _staticBrowser;
[ClassCleanup]
public static void MyClassCleanup()
{
_staticBrowser.Instance.Close();
_staticBrowser = null;
}
The problem is that when MSTEST executes the method with the [ClassCleanup] attribute, it will be run on a thread that isn't part of the STA.
If you run the following code it should work:
[ClassCleanup]
public static void MyClassCleanup()
{
var thread = new Thread(() =>
{
_staticBrowser.Instance.Close();
_staticBrowser = null;
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
The WatiN website briefly mentions that WatiN won't work with threads not in the STA here but it isn't obvious that [TestMethod]'s run in the STA while methods like [ClassCleanup] and [AssemblyCleanupAttribute] do not.
By default when IE object are destroyed, they autoclose the browser.
Your CleanUp code may try to find a browser already close, which why you have an error.
Fixed this myself by dumping mstest and using mbunit instead. I also found that I didn't need to use any of the IEStaticInstanceHelper stuff either, it just worked.