Extent Reports tests always reporting Pass - selenium

I am having an issue where if I run a test that has 6 steps, 3 pass, 1 fail, 2 skipped. It will always report as Passed in my extent reports. I am using Klov. Is it possible that I have not correctly configured the report? and if so does anyone have suggestions to fix this issue.
public class MyRunner {
#BeforeClass
public static void initialize(){
d = new Date();
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setKlovServerUrl("http://localhost");
extentProperties.setKlovProjectName("Test Project");
extentProperties.setKlovReportName("Test Report: " + d);
extentProperties.setMongodbHost("localhost");
extentProperties.setMongodbPort(27017);
extentProperties.setMongodbDatabase("klov");
}
}
#AfterClass
public static void teardown(ITestResult result){
extent.flush();
}
}
And here is my test, it is just a simple test that opens googles login page, just to make sure the extent reports will do everything I need it to
public class Google {
WebDriver driver;
#Given("^that I am on the webpage Google$")
public void thatIAmOnTheWebpageGoogle() throws Throwable {
System.setProperty("webdriver.chrome.driver","\\\\hiscox.nonprod\\profiles\\Citrix\\XDRedirect\\CaseyG\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en&passive=true&continue=https%3A%2F%2Fwww.google.com%2F&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
driver.manage().window().maximize();
MyRunner.logger.log(Status.INFO, "Opened Google login page")
//throw new PendingException();
//extent.createTest("Step 1").pass("log");
}
#When("^I try to login$")
public void i_try_to_login() throws Throwable {
// find the username field and enters the username, then clicks next
WebElement username = driver.findElement(By.xpath("//input[#id='identifierId']"));
username.sendKeys("********");
driver.findElement(By.id("identifierNext")).click();
//finds the password field and enters the password
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
password.sendKeys("**********");
Assert.assertFalse(true);
driver.findElement(By.id("passwordNext")).click();
//throw new PendingException();
//extent.createTest("Step 2").pass("log");
}
#Then("^I will be successfully logged into Google$")
public void i_will_be_successfully_logged_into_Google() throws Throwable {
String account = "Google Account: greg casey \n" + "(klovtest#gmail.com)";
//WebElement loggedInUser = driver.findElement(By.xpath("//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]"))
//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]/a
//extent.createTest("Step 3").pass("log");
throw new PendingException();
}
}

You should use ITestListener Interface on your Listener class where extent report's test is created
OnTestStart and do other things alos as descriobed below (I have used Thread for parallel device testing so you can ignore, rest is useful)
public class Listeners extends Utilities implements ITestListener {
ExtentReports extent = ExtentReporterTool.getReport();enter code here
ExtentTest test;
ThreadLocal<ExtentTest> testObjects = new ThreadLocal<ExtentTest>();
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName());
testObjects.set(test);
}
#Override
public void onTestSuccess(ITestResult result) {
testObjects.get().log(Status.PASS, "Test Case passed");
}
#Override
public void onTestFailure(ITestResult result) {
testObjects.get().fail(result.getThrowable());
WebDriver driver;
try {
driver = (WebDriver) result.getTestClass().getRealClass().getSuperclass().getField("driver")
.get(result.getInstance()); testObjects.get().addScreenCaptureFromPath(takeScreenshot(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| NoSuchFieldException e) {
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult result) {
testObjects.get().log(Status.SKIP, "Test Case skipped");
}
#Override
public void onFinish(ITestContext context) {
extent.flush();
}
}

Related

TestNG is not sending the latest emailable-report.html

#Aftertest
#AfterSuite
#AfterClass Nothing is helpful in my case when we talk about sending the latest reports in the email.
#AfterSuite
public void statusupdate() throws Exception
{
SendMail.execute();
}
This is what I am doing and every time I am getting an older version of my emailable-report.html as I am struggling with JAVA as well so hopefully someone can help me understanding what is wrong here. My assumption is I am sending the email before the fresh report is generated but have no clue what to do next. Thanks for the patience and your replies.
Best you can do is to help yourself with Listeners for reports, instead of an #afterXxxx method.
So you can do something like:
import org.testng.annotations.Listeners;
#Listeners(TestListener.class)
public class MyTestClass {
#Test
public void myTest {
doTest();
}
}
Where your Listener has your SendMail action in the onFinish method:
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener {
#Override
public void onTestStart(ITestResult result) {
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onStart(ITestContext context) {
}
#Override
public void onFinish(ITestContext context) {
SendMail.execute();
}
}
I hope this does what you need, if not let me know.
Finally I am able to get the latest .html report by implementing extent reports and TestNG listeners in my framework. I am using 7.0 TestNG and its limitation is that it does not update the emailable-report.html so to overcome this problem you will have to implement extent reports where you will always get the latest .html fancy report which you can send through email in onFinish method of your listener class. But before jumping in you have to understand listeners and extent reports rest is given below. Also thanks #rodrigo for giving me a direction :)
public class TestClass{
WebDriver driver=null;
public ExtentHtmlReporter htmlReporter;
public ExtentReports extent;
public ExtentTest test;
public static String getScreenshot(WebDriver driver, String screenshotName) throws IOException {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date(0));
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
// after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/Screenshots/" + screenshotName + dateName + ".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
#BeforeTest()
#Parameters("browser")
public void setup(String browsername) {
if(browsername.equalsIgnoreCase("chrome"))
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
}
else if(browsername.equalsIgnoreCase("firefox"))
{
WebDriverManager.firefoxdriver().setup();
driver=new FirefoxDriver();
}
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"\\test-output\\myReport.html");
htmlReporter.config().setDocumentTitle("Automation Report"); // Tile of report
htmlReporter.config().setReportName("Functional Testing"); // Name of the report
htmlReporter.config().setTheme(Theme.DARK);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Passing General information
extent.setSystemInfo("Host name", "NerdBox");
extent.setSystemInfo("Environemnt", "QA");
extent.setSystemInfo("user", "AB");
}
#Test(priority=1,enabled=true)
public void SubmitQuestions() throws Exception {
driver.manage().window().maximize();
driver.get("https://com/questions");
driver.findElement(By.xpath("/html/body/div/div/div[3]/div/div/div[1]/div/div/div[2]/div")).click();
}
#AfterMethod(alwaysRun=true)
public void end(ITestResult result) throws IOException
{
test= extent.createTest("The Test is "+result.getName());
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL, "TEST CASE FAILED IS " + result.getName()); // to add name in extent report
test.log(Status.FAIL, "TEST CASE FAILED IS " + result.getThrowable()); // to add error/exception in extent report
String screenshotPath = NerdboxJobSubmit.getScreenshot(driver, result.getName());
test.addScreenCaptureFromPath(screenshotPath);// adding screen shot
} else if (result.getStatus() == ITestResult.SKIP) {
test.log(Status.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, "Test Case PASSED IS " + result.getName());
}
}
#AfterTest(alwaysRun=true)
public void flush() throws Exception
{
System.out.println("After test");
extent.flush();
driver.quit();
}

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

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

Unable to load chrome/gecko driver after using Cucumber Driver Factory

This is my first question ever asked here, so I hope I ask it the right way:
I'm working on a multimodule maven project to test a software that is still in a development. I've been using Cucumber, Selenium, JUnit for some time and doing online courses to improve my skills. In one of the tutorials was explained how to use Driver Factory and configuration files so I applied it to my project, but after that was unable to run any of the drivers (gecko/chrome/ie). Here is a big part of the code, so I hope someone can help :)
I catch the exception from the DriverFactory.class:
"Unable to load browser: null"
config.properties file has only one line:
browser=chrome
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
//Read Config
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (driver == null) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
FirefoxOptions options = new FirefoxOptions();
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
break;
case "chrome":
if (driver == null) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
/*case "ie":
if (driver == null) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", Constant.IE_DRIVER_DIRECTORY);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
}
*/
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
} finally {
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
return driver;
}
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch(IOException e) {
e.printStackTrace();
}
}
public String getBrowser() {
if(prop.getProperty("browser") == null) {
return "";
}
return prop.getProperty("browser");
}
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\geckodriver.exe";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\chromedriver.exe";
public class CreateCaseSteps extends DriverFactory {
//Background Steps
#Given("^user accesses the login page$")
public void userAccessesTheLoginPage() throws Throwable {
getDriver().get("http://localhost:8080/");
}
#When("^user enters a valid username")
public void userEntersAValidUsername(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='username']")).sendKeys(data.get(0).get(0));
}
#When("^user enters a valid password")
public void userEntersAValidPassword(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='password']")).sendKeys(data.get(0).get(0));
}
#And("^user clicks on the login button$")
public void userClicksOnTheLoginButton() throws Throwable {
getDriver().findElement(By.xpath("//input[#value='Login']")).click();
}
#Then("^user should be taken successfully to the login page$")
public void userShouldBeTakenSuccessfullyToTheLoginPage() throws Throwable {
Thread.sleep(3000);
WebElement logoutMenu = getDriver().findElement(By.xpath("//i[#class='glyphicon glyphicon-user']"));
Assert.assertEquals(true, logoutMenu.isDisplayed());
}

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

Selenium WebDriver, How to run/connect next class

I'm new to Selenium Webdriver, I have a few question :
First, I have 2 class, 'Login.java' and 'SelectCity.java
Class 1 : Login.java
invalidLogin
validLogin
Class 2 : SelectCity.java
For now, in Login.java I wrote
#After
public void tearDown() throws Exception {
driver.close();
}
which mean the browser will closed after finish run right?
Here is my question :
How to make after I run validLogin, it will continue to run the next class (SelectCity.java)?
Is it possible to do that?
How to make last browser (which test valid login) didn't get close?
My current Login.java class :
public class Login extends SelectCityAfterLogin{
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://mysite/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLoginInvalidPass() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("user1");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginInvalidUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("somepassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Invalid User or Password", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoUsername() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("");
driver.findElement(By.id("txtPassword")).sendKeys("somePassword");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginNoPassword() throws Exception {
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("username");
driver.findElement(By.id("txtPassword")).sendKeys("");
driver.findElement(By.id("lbLogin")).click();
try {
assertEquals("Please fill username and password.", driver.findElement(By.id("lblError")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
driver.get(baseUrl + "/mysite/login.aspx");
driver.findElement(By.id("txtUsername")).sendKeys("myUsername");
driver.findElement(By.id("txtPassword")).sendKeys("password");
driver.findElement(By.id("lbLogin")).click();
Thread.sleep(3000);
}
}
Thx
Yes you can run selectcity after login
You should Extend your First class to Second class
In your Login.java extend it to selectcity java like below
Public class login extends Selectcity {
After your validlogin
create a new instance for selectcity (If you are using #test, create the below in that)
selectcity test = new selectcity()
Once after your valid login do the following
test.(will fetch you the methods available in selectcity.java)
By this way you can call once class to another.
Let me know if this helps
UPDATE :
if selectcityAfterlogin in public class Login extends **SelectCityAfterLogin** is your second class name, then you are creating an incorrect object i guess
In your public login class please check whether your are extending the proper second class name
In #test method
#Test
public void testLoginValid() throws Exception{
//SelectRoleAfterLogin selectRole = SelectRoleAfterLogin();
it should be
SelectCityAfterLogin selectrole = new SelectCityAfterLogin()
selectrole.(will fetch you the methods of second city)
Please let me know if this helps.
One better solution would be to create multiple methods than multiple #test. You can call these to single #test suite.
I am assuming, you have 2 classes 'Login.java' and 'SelectCity.java'
as follows:
Class 1 : Login.java
public void invalidLogin (WebDriver driver){
//some operations
}
public void validLogin (WebDriver driver){
//some operations
}
Class 2 : SelectCity.java
public void selectCity (Webdriver Driver){
//some operations
}
Class 3: LoginAndSelectCity.java
public static void main(String args []){
WebDriver driver = new FirefoxDriver();
Login.validLogin(driver);
SelectCity.selectCity(driver);
}
If all classes should be in same package then only it works else you need to import packages or create new child to do inheritance of the classes.