-1

Identified xpath is not working in testng, if the xpath is in first line of the method logout. The same xpath is working without using testng.

I am getting error:

Unable to locate element: {"method":"xpath","selector":"//*[@class='level1 menu static']/li[2]/a"}

Program is below:

@Test
public void login(){
driver1.findElement(By.id("txtUsername")).sendKeys("***");
driver1.findElement(By.id("txtPassword")).sendKeys("***");
driver1.findElement(By.id("btnLogin")).click();
System.out.println("Logged into the application");
}       

@Test
public void Logout() throws InterruptedException 
{   
    WebElement l =driver1.findElement(By.xpath("//*[@class='level1 menu static']/li[2]/a"));
            act.moveToElement(l).perform();                 
   driver1.findElement(By.xpath("//*[@class='level1 menu static']/li[2]/ul/li[1]/a")).click();    
                }}

Please help me to identify the problem

2
  • 1
    You need to wait for the element, make sure you are logged in before logging out.
    – lauda
    Commented Sep 1, 2016 at 13:36
  • What's with the extra ul/li[1] in the second line ? Commented Jan 1, 2017 at 1:13

1 Answer 1

1

Firstly, you should make sure the tests are executed in the correct order. This can be achieved in several ways:

  1. Implicitly set test method order in testng.xml file like this:

    <test name="Login/logout test" preserve-order="true">
        <classes>
            <class name="com.test.LoginLogout">
                <methods>
                    <include name="login" />
                    <include name="Logout" />
                </methods>
            </class>
        </classes>
    </test>
    
  2. Use additional attributes of the @Test annotation:

    @Test(dependsOnMethods="login")
    public void Logout() throws InterruptedException
    

Secondly, you should make sure the element is accessible when the logout test is executed. This can be achieved, using some impementation of wait (see this SO answer for some examples), like:

WebDriverWait wait = new WebDriverWait(driver1, timeoutInSeconds);    
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@class='level1 menu static']/li[2]/a"));
2
  • Hi, thanks a lot.my code is working fine when i used 2nd option using @test annotation.
    – saran
    Commented Sep 6, 2016 at 5:32
  • @saran - please mark this as the accepted answer.
    – Kate Paulk
    Commented Mar 2, 2017 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.