Automation script element Identified first time but dont verified second time - selenium

public void iclickontemplatetab(){
SeleniumDriver.getDriver().findElement(By.xpath("//*[#id=\"global_nav_sidebar\"]/div/div[2]/nav/ul/li[4]/a")).click();
}
public void iclickonanalyticstab(){
SeleniumDriver.getDriver().findElement(By.xpath("//*[#id=\"global_nav_sidebar\"]/div/div[2]/nav/ul/li[6]/a")).click();
}

Try adding a wait (Implicit or explicit) if you are doing some actions before revisiting the elements for second time

public void iclickontemplatetab(){
SeleniumDriver.getDriver().findElement(By.xpath("....")).click();
}
Avoid using copy paste Xpaths. Instead use manual xpaths. Like: //tagname[#attribute=’Value‘]

Related

WebDriverWait Selenium approach

Regarding the WebDriverWait data type, I am assuming that only one instance is needed of such data type, which means I could potentially create a wrapper and allow only one instance creation by using a singleton pattern approach.
At the present time I used thread.sleep and basically everywhere I need that function to be called I am extending from the class which probably not the best approach. Also of course I should be using WebDriverWait instead of thread. What should the approach be?
So far I created a page object with web elements and a separate service for the logic itself, so now I need also WebDriverWait in every service since it’s a necessary operation.
A cookie window that gets popped up once customer opened the page:
/**
* acceptCookies -> clickable
* cookieBanner -> just to identify that cookie component showed up.
* PageFactory -> will initialize every WebElement variable with a reference to a corresponding element on the actual web page.
*/
public class CookieModal {
WebDriver driver;
#FindBy(css = ".cookie-accept-all")
public WebElement acceptCookies;
public CookieModal(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
}
Then I separated the service (actions):
public class CookieService {
private final CookieModal cookieModal;
public CookieService(WebDriver driver) {
this.cookieModal = new CookieModal(driver);
}
public void acceptCookies() {
cookieModal.acceptCookies.click();
}
}
This must be changed to WebDriverWait, but I also think extending from AbstractPage in every page object is not necessary. Is my structure OK and how should I initialise WebDriverWait?
public class AbstractPage {
// This is not good as thread sleep is not dynamic and you
// have to specify time yourself change to webdriver wait
private AbstractPage microsleep(Integer milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (Throwable e) {
String error = String.format("Unable to put thread to sleep (requested %d milliseconds).", milliseconds);
throw new RuntimeException(error, e);
}
return this;
}
public AbstractPage emulateWaitingUser() {
return microsleep(800);
}
public AbstractPage sleep(Integer seconds) {
return microsleep(1000 * seconds);
}
Selenium supports integrating explicit waits into page objects. This is achieved by using a special way of how you initialize your page. In your example you are doing this:
PageFactory.initElements(driver, this);
which involves some basic default way. However, you can add more complexity here, but you get a more effective architecture at the same time.
You can extend the AjaxElementLocator class where you will override isElementUsable method in the way that would involve any sort of condition and waits. Then you will be initializing your page(s) with that locator through a dedicated LocatorFactory. Some example of how to use all that classes you can find here.
WebDriverWait is commonly used with the ExpectedConditions class. In that case, you cannot just wait for 800 ms. You need to wait until a condition is met. For example, wait until page title is displayed, or wait until loader icon is not visible, wait until login button is clickable, etc.
That means if you wish to instantiate a wait in an abstract method, you will need to add an unknown (and non-abstract) wait condition. You could just instantiate a general wait object and then add a condition when it is known, but it seems a bit incomplete.
Another idea that comes to my mind is declaring WebDriverWait as a field in Cookie Service class and pass it to its methods.

clear() clears the value but retains the value in Selenium Appium when sendkeys() is used

clear method clears the value but retains and when send keys new value is passed the text box shows previous value + new value in selenium Appium. Kindly suggest.
Version:java-client-4.1.2
Appium Server:v1.7.2
Selenium: 3.0.1
I tried this but it did not work out.
public void clearTextBox(WebElement element,String text) throws Exception
{
element.click();
Thread.sleep(3000);
element.clear();
element.sendKeys(text);
}
Getting this
The reason your code is failing (and you should have included your code in the original question) is because you are doing it through TWO separate calls to the page object element.
Each time you call the page object, it looks-up the element freshly, so the first time you call it and issue a .clear() and then you are calling it again after an unnecesary sleep with the .sendkeys() method. The click is also unnecessary.
You should write a public method in your page object model to perform the sendkeys() for you which does the clear() and then the sendkeys(), i.e.:
public void setMsisdnValue(String text) {
Msisdn.clear();
Msisdn.sendKeys(text);
}
Personally, I use a set of helper methods so that I can error-trap and log things like sendkeys, but I would still call it from within the page object model itself. That helper would do the same two steps, but also do it inside a try/catch and report any errors, so it would be simplified to:
public void setMsisdnValue(String text) {
helper.sendKeys(Msisdn, text);
}
Hope this helps.

Selenium how to make click and hold button

In webpage I test is a modal which appears after pressing a button for circa 5sec.
And now I'm trying to make this in selenium.
I have method like this:
public static void ClickHold(IWebElement by)
{
SpecialInteractions.ClickAndHold(by);
}
where
public static Actions SpecialInteractions { get; set; }
and there is no hold time to set.
It looks like just clicking and releasing. Is there a way to wait for particular amount of time and then release?
Without digging dipper I can tell you the program above probably returns NulReference exception. I suspect you need to instantiate the Actions by wrapping the current driver instance.
Possible solution could be:
public void ClickHold(IWebElement element)
{
Actions action = new Actions(driver);
action.clickAndHold(webelement).build().perform();
//you need to release the control from the test
//actions.MoveToElement(element).Release();
}
Keep in mind that this will not work if you are using Selenium Grid. There is a bug that makes moveToElement an unrecognized command.
public static Boolean moveToThenSlowClickElement(final WebDriver driver, final WebElement toElement, final int millisecondsOfWaitTime) {
final Actions clickOnElementAndHold = new Actions(driver);
final Actions release = new Actions(driver);
clickOnElementAndHold.moveToElement(toElement).clickAndHold(toElement).perform();
sleep(millisecondsOfWaitTime);
release.release(toElement).perform();
final Action hoverOverCheckBox = clickOnElementAndHold.build();
hoverOverCheckBox.perform();
return true;
}

A central location for catching throwables of JUnit tests?

I would like to catch any throwable during a Selenium test e.g. in order to make a screenshot. The only solution I could come up with for now is to separately surround the test steps with a try and catch block in every test method as following:
#Test
public void testYouTubeVideo() throws Throwable {
try {
// My test steps go here
} catch (Throwable t) {
captureScreenshots();
throw t;
}
}
I'm sure there is a better solution for this. I would like a higher, more centralized location for this try-catch-makeScreenshot routine, so that my test would be able to include just the test steps again. Any ideas would be greatly appreciated.
You need to declare a TestRule, probably a TestWatcher or if you want to define the rules more explicitly, ExternalResource. This would look something like:
public class WatchmanTest {
#Rule
public TestRule watchman= new TestWatcher() {
#Override
protected void failed(Description d) {
// take screenshot here
}
};
#Test
public void fails() {
fail();
}
#Test
public void succeeds() {
}
}
The TestWatcher anonymous class can of course be factored out, and just referenced from the test classes.
I solved a similar problem using Spring's AOP. In summary:
Declare the selenium object as a bean
Add an aspect using
#AfterThrowing
The aspect can take the screenshot and save it to a
file with a semirandom generated name.
The aspect also rethrows the exception, with the exception message including the filename so you can look at it afterwards.
I found it more helpful to save the HTML of the page due to flakiness of grabbing screenshots.

How do I sense if my unit test is a member of an ordered test and, if it is, which position in that ordered test it is at?

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();
}
}
}