I have added the extent report dependency from the maven repository in pom.xml but when I am trying to use "ExtentSparkReporter" in my code, the import is not happening.
Below is my pom.xml
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>4.0.9</version>
</dependency>
Below is my file:
public void config()
{
String path =System.getProperty("user.dir")+"\\reports\\index.html";
ExtentSparkReporter reporter = new ExtentSparkReporter(path);
//no methods have been initiated in config
}
public void initialDemo()
{
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver =new ChromeDriver();
driver.get("https://www.google.com");
System.out.println(driver.getTitle());
driver.close();
//test.fail("Result do not match");
}
}
It will be a great help if anyone helps me regarding this.
P:s - As I have checked some of the solution to downgrade the extendreports library , so I am using 4.0.9.
Thanks
you are missing some key components:
The ExtentSparkReporter needs to be attached to the ExtentReports object
You need to flush the ExtentReports object at the end of all tests
Here's a sample using 5.0.9 ( it works with 4.0.9 also)
Using these maven dependencies:
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.9</version>
</dependency>
</dependencies>
I'm using testng to manipulate the order the code is executed.
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
public class TestDemo {
public ExtentReports extent = new ExtentReports();
public ExtentSparkReporter reporter;
public ExtentTest test;
public WebDriver driver;
#BeforeSuite
public void beforeSuite() { // it will be executed only once, before all the tests, so we won't have duplicate reports or override the file for each test
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe"); //set the chrome path for all tests only once
String path = System.getProperty("user.dir")+"\\reports\\index.html";
reporter = new ExtentSparkReporter(path);
}
#BeforeMethod
public void beforeMethod(){
driver = new ChromeDriver(); // create the chrome instance before each tests
}
#Test
public void aFastTest() {
test = extent.createTest("aFastTest");
driver.get("https://www.google.com");
System.out.println(driver.getTitle());
driver.close();
test.fail("Failed");
}
#Test
public void anotherTestPassed() {
test = extent.createTest("anotherTestPassed");
driver.get("https://www.google.com");
System.out.println(driver.getTitle());
driver.close();
test.pass("hey my test passed");
}
#AfterSuite
public void afterSuite(){ //executed after all the tests have ran
extent.attachReporter(reporter);
extent.flush();
}
}
Related
I am using selenium 3.141.59 to automate gmail application as an example in Edge in IE Mode.
If I use Selenium 4.0.0 or greater , PageFactory.initElements doesn't support .
I have to execute script for below environment :
Windows 11 (64 bit)
Edge 105.0.1343.50 ( Open in IE mode. Its requirement of an application)
DriverManager.java
package managers;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
public class DriverManager {
public WebDriver driver;
DesiredCapabilities capabilities;
#SuppressWarnings("unchecked")
#Parameters({ "browserName" })
#BeforeClass(alwaysRun = true)
public void initialize(String browser) throws IOException, InterruptedException {
if (browser.equalsIgnoreCase("edge")) {
System.setProperty("webdriver.edge.driver",
"D:\\My_Workspace\\EdgeInIEModeTest\\drivers\\msedgedriver.exe");
capabilities = new DesiredCapabilities();
// Creating an object of EdgeDriver
driver = new EdgeDriver();
driver.manage().window().maximize();
// Deleting all the cookies
driver.manage().deleteAllCookies();
// Specifiying pageLoadTimeout and Implicit wait
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if (browser.equalsIgnoreCase("edgeForWindows11")) {
// Selenium 4 + version
// System.out.println("edgeForWindows11 IN");
// System.setProperty("webdriver.ie.driver",
//
// "D:\My_Workspace\EdgeInIEModeTest\drivers\IEDriverServer32bit.exe\IEDriverServer32bit.exe");
//
// InternetExplorerOptions ieOptions = new InternetExplorerOptions();
// ieOptions.attachToEdgeChrome();
// ieOptions.withEdgeExecutablePath("C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe");
//
// driver = new InternetExplorerDriver(ieOptions);
// Selenium 3.141.59
System.setProperty("webdriver.ie.driver",
"D:\\My_Workspace\\EdgeInIEModeTest\\drivers\\IEDriverServer32bit.exe");
InternetExplorerOptions edgeIe11Options = new InternetExplorerOptions();
Map<String, Object> ops = (Map<String, Object>) edgeIe11Options.getCapability("se:ieOptions");
ops.put("ie.edgechromium", true);
ops.put("ie.edgepath", "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"); // Edge Browser
// directory
// path
edgeIe11Options.introduceFlakinessByIgnoringSecurityDomains();
edgeIe11Options.ignoreZoomSettings();
edgeIe11Options.enablePersistentHovering();
edgeIe11Options.takeFullPageScreenshot();
edgeIe11Options.disableNativeEvents();
edgeIe11Options.requireWindowFocus();
edgeIe11Options.destructivelyEnsureCleanSession();
edgeIe11Options.setCapability("ignoreProtectedModeSettings", true);
edgeIe11Options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new InternetExplorerDriver(edgeIe11Options);
}
}
public static String getIPAddress() {
InetAddress IP = null;
try {
IP = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return IP.getHostAddress();
}
public void launchGmailApplication() throws InterruptedException, IOException {
System.out.println("In launchApplication method for EdgeInIEMode Windows 11");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.google.com");
Thread.sleep(3000);
try {
driver.switchTo().alert().accept();
} catch (Exception a) {
}
}
#AfterClass(alwaysRun = true)
public void TeardownTest() {
System.out.println(driver.getCurrentUrl());
if (null != driver) {
driver.close();
driver.quit();
}
}
}
BasePage.Java
package pages;
import org.openqa.selenium.WebDriver;
public abstract class BasePage {
public WebDriver driver;
public BasePage(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver = driver;
}
}
LogInPage.Java
import java.io.IOException;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import managers.DriverManager;
import pages.LogInPage;
public class LogInTest extends DriverManager {
public LogInPage loginPage;
#BeforeClass(alwaysRun = true)
public void launchApplication() throws InterruptedException, IOException {
loginPage = PageFactory.initElements(driver, LogInPage.class);
launchGmailApplication();
}
#Test
public void invokeDriver() {
System.out.println("Hello");
loginPage.clickOnGmailMenuOption();
loginPage.clickOnSignInButton();
loginPage.logInToGmailApplication();
}
}
LogInTest.Java
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import managers.DriverManager;
import pages.LogInPage;
public class LogInTest extends DriverManager {
public LogInPage loginPage;
#BeforeMethod(alwaysRun = true)
public void launchApplication() {
loginPage = PageFactory.initElements(driver, LogInPage.class);
loginPage.logInToGmailApplication();
}
#Test
public void invokeDriver() {
System.out.println("Hello");
loginPage.clickOnGmailMenuOption();
loginPage.clickOnSignInButton();
loginPage.logInToGmailApplication();
}
}
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cemtrex.com</groupId>
<artifactId>EdgeInIEModeTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>if-suite-exists</id>
<activation>
<property>
<name>!env.SUITES</name>
</property>
</activation>
<properties>
<suites>GlobalSuite</suites>
</properties>
</profile>
<!-- browsers -->
<profile>
<id>firefox</id>
<properties>
<capabilities>/firefox.capabilities</capabilities>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>chrome</id>
<properties>
<capabilities>/chrome.capabilities</capabilities>
</properties>
</profile>
<profile>
<id>ie</id>
<properties>
<capabilities>/ie.capabilities</capabilities>
</properties>
</profile>
</profiles>
<properties>
<suites>${env.SUITES}</suites>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<resources>
<resource>
<directory>src/main/java/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/java/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<!--<inherited>true</inherited> -->
<configuration>
<!--<testFailureIgnore>false</testFailureIgnore> -->
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/suites/${suites}.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
After Execute :
I m trying to use web application with Embedded tomcat 8 without web.xml.
But I am not able to access the application by hitting the url http://localhost:8085/Servlet_Basic/index.jsp from browser.
Neither I am able to access the servlet by hitting the url http://localhost:8085/Servlet_Basic/hello from browser.
Here is my source code :
pom.xml dependencies
<properties>
<tomcat.version>8.5.23</tomcat.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>14</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<version>8.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
HelloServlet.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloServlet() {
super();
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";
out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>My First Servlet</H1>\n" + "</BODY></HTML>");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
App.java
public class App {
public static void main(String[] args) throws LifecycleException {
int port = 8085;
Tomcat tomcat = new Tomcat();
tomcat.setPort(port);
StandardServer server = (StandardServer) tomcat.getServer();
AprLifecycleListener listener = new AprLifecycleListener();
server.addLifecycleListener(listener);
String docBase = "D:\\Servlet_Basic\\src\\main\\webapp";
Context context = tomcat.addWebapp("/Servlet_Basic", docBase);
context.setAddWebinfClassesResources(true);
tomcat.start();
System.out.println("Tomcat server started at port " + port);
tomcat.getServer().await();
}
}
src/main/webapp contents :
index.jsp
<html>
<body>
<h2>Hello World</h2>
</body>
</html>
How can I access the application and invoke servlet annotated with #WebServlet
annotation in embedded tomcat without using web.xml ?
Basically I want to use web application with embedded tomcat without web.xml and without explicitly configuring servlets using tomcat.addServlet() method.
Instead I would like to configure servlet using #WebServlet annotation
I updated Pom File
<artifactId>selenium-java</artifactId>
<version>3.13.0</version>
and
<artifactId>testng</artifactId>
<version>6.14.3</version>
Now i am trying to run simple test case look like
#BeforeMethod
public void before() {
driver=new ChromeDriver();
}
#Test
public void mytest() {
driver.get("https://www.google.com");
System.out.println(driver.getCurrentUrl());
}
#AfterMethod
public void aftermethod() {
driver.close();
}
Its give me the error
org.openqa.selenium.WebDriverException: unknown error: unhandled inspector error: {"code":-32000,"message":"Cannot navigate to invalid URL"}
(Session info: chrome=67.0.3396.99)
If we downgrade the version then its work.Can anyone help me to fixed?
Please check you add the chromdriver.exe into the PATH environment.
Or you can specify webdriver.chrome.driver in code as below:
System.setProperty("webdriver.chrome.driver", <chromeDriverPath>);
driver=new ChromeDriver();
Though my tests ran successfully, I am not able to generate extent-report, below codes and pom.xml I used
Any help is appreciated. Hope I am clear on my question. Please help to solve this issue:
import java.io.File; import java.util.Date;
import com.relevantcodes.extentreports.DisplayOrder;
import com.relevantcodes.extentreports.ExtentReports;
public class ExtentManager {
private static ExtentReports extent;
public static ExtentReports getInstance() {
if (extent == null) {
Date d=new Date();
String fileName=d.toString().replace(":", "_").replace(" ", "_")+".html";
extent = new ExtentReports("C:\\Users\\dilu316\\Documents"+fileName, true, DisplayOrder.NEWEST_FIRST);
extent.loadConfig(new File(System.getProperty("user.dir")+"//ReportsConfig.xml"));
// optional
extent.addSystemInfo("Selenium Version", "2.53.0").addSystemInfo(
"Environment", "QA");
}
return extent;
}
}
Tests:
public class DummyTestB extends BaseTest{
ExtentReports rep = ExtentManager.getInstance();
ExtentTest test;
#Test
public void testB()
{
test = rep.startTest("DummyTestB");
test.log(LogStatus.INFO, "Starting the test test B");
openBrowser("Mozilla");
test.log(LogStatus.INFO, "Open the Browser");
navigate("appurl");
type("email_id","hara.mohapatra#gmail.com");
click("button_xpath");
verifyTitle();
reportFailure("title does not match");
test.log(LogStatus.PASS, "Test B Passed");
}
#AfterMethod
public void quit()
{
rep.endTest(test);
rep.flush();
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.selenium.core.ddf</groupId>
<artifactId>DataDriven_Core_Framework</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>DataDriven Core Framework</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.relevantcodes/extentreports -->
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.2</version>
</dependency>
</dependencies>
</project>
Thanks in Advance.
public class BaseClass
{
public static WebDriver driver;
public static ExtentReports report;
public static ExtentTest test;
#BeforeSuite
public void InitIate() throws Exception
{
report = new ExtentReports("YOURPATH", true);
report.loadConfig("YOURPATH);
}
}
public class TestSet1 extends BaseClass
{
#Test (priority=1)
public static void TestCase1()
{
test = report.startTest("TC desc");
// Blah Blah --your steps
report.endTest(test);
report.flush();
}
}
Update. Check working example in the end.
I've got a class:
package test;
public class ClassXYZ {
private final String message;
public ClassXYZ() {
this.message = "";
}
public ClassXYZ(String message) {
this.message = message;
}
#Override
public String toString() {
return "ClassXYZ{" + message + "}";
}
}
and a test:
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
public class MockClassXYZ {
#Test
public void test() throws Exception {
PowerMockito.whenNew(ClassXYZ.class).withNoArguments().thenReturn(new ClassXYZ("XYZ"));
System.out.println(new ClassXYZ());
}
}
but it still creates a real class and prints:
ClassXYZ{}
What am I doing wrong?
P.S. Maven deps:
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
</dependencies>
Working example:
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassXYZ.class)
public class MockClassXYZ {
#Test
public void test() throws Exception {
ClassXYZ mockXYZ = mock(ClassXYZ.class);
when(mockXYZ.toString()).thenReturn("XYZ");
PowerMockito.whenNew(ClassXYZ.class).withNoArguments().thenReturn(mockXYZ);
ClassXYZ obj = new ClassXYZ();
System.out.println(obj);
}
}
You are missing a #PrepareForTest(ClassXYZ.class) on your test class, see the documentation here or here. From the first link:
Mock construction of new objects
Quick summary
Use the #RunWith(PowerMockRunner.class) annotation at the class-level
of the test case.
Use the #PrepareForTest(ClassThatCreatesTheNewInstance.class) annotation at
the class-level of the test case.
[...]
Also note that there's no point of mocking the constructor if you ask the mocking framework to return a real instance of the mocked class.