"No tests found. Nothing was run" message in console , unable to understand why - selenium

Below is the code am trying to execute
Not sure why am getting [TestNG] No tests found. Nothing was run
if I remove the before class annotation method, it executes but fails due the dependency
public class TestNG_Practice3 {
static WebDriver driver ;
String url = "https://in.linkedin.com/";
#BeforeClass(description = "To open the browser")
public void openBrowser()
{ driver = new FirefoxDriver();
driver.get(url);
System.out.println("Browser got open");
}
#Test (dependsOnMethods ="openBrowser",description = "To signin")
public void login()
{
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
WebElement signin = driver.findElement(By.id("login-email"));
Assert.assertTrue(signin.isDisplayed());
WebElement password = driver.findElement(By.id("login-password"));
WebElement signinbutton = driver.findElement(By.id("login-submit"));
signin.sendKeys("xyz");
password.sendKeys("abc");
signinbutton.click();
Assert.assertTrue(driver.getCurrentUrl().contains("feed/"));
}
#Test(dependsOnMethods = "login")
public void logout()
{
WebElement meDropdown = driver.findElement(By.xpath("//*[#id=\"nav-settings__dropdown-trigger\"]/div/span[2]/li-icon/svg"));
meDropdown.click();
WebElement logout = driver.findElement(By.id("ember545"));
logout.click();
}
#AfterClass
public void closebrowser()
{
driver.quit();
}
}

Step-1 : Basic trial with Project Build,
public class TestNG_Demo {
#BeforeClass
public void openbrowser()
{
System.out.println("Browser got open");
}
#Test
public void testbrowser()
{
System.out.println("Test execution");
}
#AfterClass
public void closebrowser()
{
System.out.println("Browser got close");
}
}
So you will be have idea, Your project build get successful execution.
If you have maven project and Build did not get pass, you will be have trigger what is causing from maven build dependency.
Update
Step-2 : After tracing first trial
public class TestNG_Demo {
#Test
public void testbrowser()
{
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
}
}

Remove dependsOnMethods ="openBrowser" because it's not a test method and will be execute before test without it

Related

Cannot pass from login popup page to password popup page in Selenium

I am trying to create a Selenium test for the account login. Each time when a 'continue' button is clicked it says:
no such element: Unable to locate element:
{"method":"xpath","selector":"//INPUT[#id='password']"}
and remains on the email page, doesn't move to the password page. Though xpath of 'password' textbox is correct. My code is below.
login class
public class login {
WebDriver driver;
public login(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//LI[#data-cy='account']")
WebElement CreateorLoginButtonXpath;
#FindBy(xpath="//INPUT[#id='username']")
WebElement EmailTextBoxXpath ;
#FindBy(xpath="//BUTTON[#class='capText font16']")
WebElement ContinueButtonXpath;
#FindBy(xpath="//INPUT[#id='password']")
WebElement PasswordTextBoxXpath;
#FindBy(xpath="//BUTTON[#data-cy='login']")
WebElement LoginButtonXpath;
public void clickCreateorLoginButtonXpath()
{
CreateorLoginButtonXpath.click();
System.out.println("login or create button is clicked");
}
public void TypeEmailTextBoxXpath(String email)
{
EmailTextBoxXpath.sendKeys(email);
System.out.println("email is typed");
}
public void clickContinueButtonXpath()
{
ContinueButtonXpath.click();
System.out.println("Continue Button is clicked");
}
public void TypePasswordTextBoxXpath(String password)
{
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(PasswordTextBoxXpath)).sendKeys(password);
System.out.println("Password is given");
}
public void clickLoginButtonXpath()
{
LoginButtonXpath.click();
System.out.println("Login Button is clicked");
}
}
main class
public class RunloginTestCase {
WebDriver driver = new ChromeDriver();
login lg = new login(driver);
#BeforeTest
public void openBrowser() throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.makemytrip.com/");
System.out.println("Broweser opened");
}
#Test
public void loginTestPositive() throws InterruptedException
{
lg.clickCreateorLoginButtonXpath();
lg.TypeEmailTextBoxXpath("test1992#test.com");
Thread.sleep(2000L);
lg.clickContinueButtonXpath();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS) ;
lg.TypePasswordTextBoxXpath("!Qwerqwer1");
lg.clickLoginButtonXpath();
Thread.sleep(3000L);
lg.clickSkipVerificationPopupPageButtonXpath();
}
}
I think you provided a wrong formatted email address. Please try with a valid sample email like "test#test.test" ...
public class RunloginTestCase {
WebDriver driver = new ChromeDriver();
#BeforeTest
public void openBrowser() throws InterruptedException
{
driver.get("https://www.makemytrip.com/");
System.out.println("Broweser opened");
Thread.sleep(3000L);
}
#Test
public void loginTestPositive() throws InterruptedException{
login lg = new login(driver);
lg.clickCreateorLoginButtonXpath();
lg.TypeEmailTextBoxXpath("email");
Thread.sleep(5000L);
lg.clickContinueButtonXpath();
Thread.sleep(5000L);
lg.TypePasswordTextBoxXpath("password");
lg.clickLoginButtonXpath();
}
}
Please try with this one

Running selenium, cucumber and Page Factory. Second step definition fail to run

I wrote a cucumber framework that has two feature files and two stepdefinitions which are glued to the feature files. When i run the test together, it ran for the first stepDefinition and fail to enter the second stepDefinition. I have initialize my pages and yet couldn't get it to work.
Error and Codes below
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy19.click(Unknown Source)
at Pages.HomePage.CreateANewOrderPage.createOrderLink(CreateANewOrderPage.java:35)
at StepDefinitions.CreateOrderStep.user_click_on_create_a_new_order(CreateOrderStep.java:24)
at ✽.When user click on create a new order(CreateOrder.feature:5)
public class CreateANewOrderPage {
WebDriver driver;
public CreateANewOrdePage(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy (linkText= "Create a new order")
public WebElement createOrderLink;
public void createOrderLink(){
createOrderLink.click();
}
public class SigninPage {
WebDriver driver;
public SigninPage(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//*[#id=\"userName\"]")
public WebElement usernameField;
#FindBy(name="password")
public WebElement passwordField;
#FindBy(id="buttonSubmitLogin")
public WebElement submitBtn;
public void loginDetails(String uname, String psw) {
usernameField.sendKeys(uname);
passwordField.sendKeys(psw);}
public void clickLogin(){
submitBtn.click();
}
}
public class SigninStep {
WebDriver driver;
SigninPage logIn = new SigninPage(driver);
#Given("^user navigates to mySite$")
public void userNavigatesToMysite() throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\mypc\\Documents\\Automation\\drivers\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("www.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#And("^user enter \"([^\"]*)\" and \"([^\"]*)\"$")
public void userEnterValidCredentials(String validuname, String validpsw) throws Throwable {
SigninPage logIn = new SigninPage(driver);
logIn.loginDetails("jdjdjdj","jjdjdj");
}
#When("^user click on Sign in$")
public void userClickSignIn() throws Throwable {
SigninPage logIn = new SigninPage(driver);
logIn.clickLogin();
}
}
public class CreateOrderStep {
WebDriver driver;
CreateANewOrderPage ordercreate;
#When("^user click on create a new order$")
public void user_click_on_create_a_new_order() throws Throwable {
ordercreate= PageFactory.initElements(driver,CreateANewOrderPage.class);
ordercreate.createOrderLink();
}
#RunWith(Cucumber.class)
#CucumberOptions (features = "src\\test\\java\\Features\\",
glue ={"StepDefinitions"},
tags={"#Signin, #CreateOrder"}
//format = {"pretty", "html:target/Destination.."}
// format={"json:target/Destination/cucumber.json"
)
public class SigninRunner {
}

screenshot listener in selenium with TestNG

I have a testcase that will invoke the driver as a non static variable. I also have added screenshot listener in my test case. When the test case fails The control is automatically sent to the screenshot listener, however since my driver is a NON-STATIC variable it could not be accessed in the screenshot listener. So I get nullpointer exception.
To solve this I created a simple base test class with help of stackoverflow like below and extend it in each testclass
public asbtract baseTest() {
private WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#BeforeMethod
public void createDriver() {
Webdriver driver=XXXXDriver();
}
#AfterMethod
public void tearDownDriver() {
if (driver != null)
{
try
{
driver.quit();
}
catch (WebDriverException e) {
System.out.println("***** CAUGHT EXCEPTION IN DRIVER TEARDOWN *****");
System.out.println(e);
}
}
}
In my listener, I access the base class as follows
public class ScreenshotListener extends TestListenerAdapter {
#Override
public void onTestFailure(ITestResult result)
{
Object currentClass = result.getInstance();
WebDriver webDriver = ((baseTest) currentClass).getDriver();
if (webDriver != null)
{
File f = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
//etc.
}
}
My test class looks like this
#Listeners(value = FailureReport.class)
public class LoginTest extends baseTest{
Login login = new Login(getDriver());
#Test(description = "Verify Expand the Menu", priority = 0)
public void navigateloginpage() {
login.expandMenuScreenLogin();
login.navigateLoginPage();
}
#Test(description = "User login Sucessfully", priority = 1)
public void successLogin() {
login.login();
}
When I run this it gives me the error
org.testng.TestNGException:
Cannot find class in classpath: com.fbf.automation.tests.LoginTest
at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
at org.testng.xml.XmlClass.init(XmlClass.java:73)
at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:548)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:745)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1359)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:327)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at org.testng.xml.XMLParser.parse(XMLParser.java:38)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9)
at org.testng.xml.Parser.parse(Parser.java:172)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:302)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:45)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Process finished with exit code 0
Later when I changed my test class as follows it ran correctly
#Listeners(value = FailureReport.class)
public class LoginTest extends baseTest{
Login login;
#Test(description = "Verify Expand the Menu", priority = 0)
public void navigateloginpage() {
login = new Login(getDriver());
login.expandMenuScreenLogin();
login.navigateLoginPage();
}
#Test(description = "User login Sucessfully", priority = 1)
public void successLogin() {
login.login();
}
Isn't it possible to declare the code
login = new Login(getDriver());
outside #test method rather than writing it inside the #test method. Or are there anyother alternative ways I can call the above code
You may create Login object inside #BeforeClass method
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
login = new Login(getDriver());
}

Selenium extent reports framework not generating failed status

Currently, I am using Selenium TestNG and Extent Reports framework for reporting. I am facing a problem where all are my test cases are showing Pass and not showing Fail.
#BeforeTest
public void setUp()
{
//where we need to generate the report
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/test-output/MyReport.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Set our document title, theme etc..
htmlReporter.config().setDocumentTitle("My Test Report");
htmlReporter.config().setReportName("Test Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
#Test
public void On_Page_IM() throws InterruptedException {
test = extent.createTest("On_Page_IM");
wd.manage().window().maximize();
Thread.sleep(10000);
test.log(Status.INFO,"On page intent media: Show");
}
#AfterSuite
public void tearDown()
{
extent.flush();
wd.quit();
}
After Added this code its solved
#AfterMethod
public void getResult(ITestResult result)
{
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(Status.FAIL, result.getThrowable());
}
// extent.endTest(test);
}
Just add below code at end of ur tests
#AfterMethod
public void AfterMethod(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL,
MarkupHelper.createLabel(result.getName()
+ " Test case FAILED due to below issues:",
ExtentColor.RED));
test.fail(result.getThrowable());
} else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(
Status.PASS,
MarkupHelper.createLabel(result.getName()
+ " Test Case PASSED", ExtentColor.GREEN));
} else {
test.log(
Status.SKIP,
MarkupHelper.createLabel(result.getName()
+ " Test Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
}
#AfterTest
public void AfterTest() {
extent.flush();
}
Selenium WebDriver 4 + JUnit 5 + Extent Reports 5 (JDK 17)
I used this and this to write the modern JUnit 5 solution, since most examples are for the older TestNG. ExtentHtmlReporter has also been deprecated.
abstract class BaseTest {
private static ExtentReports extent; // Prevent overwriting reports per test
protected WebDriver driver; // WebDriver should never be static
#RegisterExtension
protected AfterEachExtension afterEachExtension = new AfterEachExtension();
#BeforeAll
public static void beforeAll() {
extent = new ExtentReports();
spark = new ExtentSparkReporter("target/spark-reports/index.html");
extent.attachReporter(spark);
spark.config(
ExtentSparkReporterConfig.builder()
.theme(Theme.DARK)
.documentTitle("Extent Reports")
.build()
);
}
#BeforeEach
public void beforeEach() {
driver = // Initialise driver
}
#AfterEach
public void afterEach() {
AfterEachExtension.setExtent(extent);
afterEachExtension.setDriver(driver);
}
#AfterAll
public static void afterAll() {
extent.flush();
}
}
import com.aventstack.extentreports.Status;
// Other imports
public class AfterEachExtension implements AfterEachCallback {
private static ExtentReports extent;
private WebDriver driver;
public static void setExtent(ExtentReports extent) {
AfterEachExtension.extent = extent;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
}
#Override
public void afterEach(ExtensionContext context) throws Exception {
var test = extent.createTest(context.getDisplayName());
context.getExecutionException().ifPresent(value -> test.log(Status.FAIL, value));
driver.quit();
}
}

Capture WebDriver Screenshots When Running Parallel Tests With TestNG

I am currently capturing screenshots on failure and success in TestNG by way of overriding the TestListenerAdapter methods onTestFailure, and onTestSuccess respectively. In order to do this you need to specify which driver you want to take a screenshot of.
My question: Is there a good way to capture screenshots when running tests in parallel on the method level?
In order to run tests in parallel, each individual test needs a unique driver instance. So, at any given time you have x number of driver instances running. When it comes time to capture a screenshot, how do you determine which driver to use?
Code excerpts below:
public class OnFailureListener extends TestListenerAdapter {
#Override
public void onTestFailure(ITestResult tr) {
Screenshots.captureScreenshot(tr);
super.onTestFailure(tr);
}
--
public static void captureScreenshot(ITestResult tr) {
WebDriver driver = TestClass.driver;
if (driver instanceof TakesScreenshot) {
String filename = "path/to/screenshot/file";
try {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(filename));
} catch (IOException e) { e.printStackTrace(); }
}
If you create a base test class with access to the driver, then that driver will always be the correct driver
The following will achieve this;
All test classes must extend a simple base test class;
public asbtract baseTestCase() {
private WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#BeforeMethod
public void createDriver() {
driver=XXXXDriver();
}
#AfterMethod
public void tearDownDriver() {
if (driver != null){
try{
driver.quit();
}
catch (WebDriverException e) {
System.out.println("***** CAUGHT EXCEPTION IN DRIVER TEARDOWN *****");
System.out.println(e);
}
}
}
In your listener, you need to access the base class:
public class ScreenshotListener extends TestListenerAdapter {
#Override
public void onTestFailure(ITestResult result){
Object currentClass = result.getInstance();
WebDriver webDriver = ((BaseTest) currentClass).getDriver();
if (webDriver != null){
File f = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
//etc.
}
}
}