PowerMockito.whenNew isn't working - testing

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.

Related

ExtentReport is not generated in Maven repository

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

How do I add a screenshot to an Allure report?

I have a Selenide+Java project which uses allure reporting. I am using the TestExecutionListener to handle browser setup, but I am having some extreme difficulty figuring out how to add screenshots to the report on a test failure.
I'm using
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-junit5</artifactId>
<version>2.13.0</version>
<scope>test</scope>
</dependency>
And in my Listener code:
public class BrowserListener implements TestExecutionListener {
Browser browser;
#Override
public void executionStarted(TestIdentifier testIdentifier) {
if(testIdentifier.isTest()) {
browser = new Browser();
browser.openBrowser();
}
}
#Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
//code here to log failed execution - ideally would like to put screenshot on failure
browser.close();
}
}
How do I add a screenshot to an Allure report using Selenide/Junit 5?
I managed to get this working by adding the following:
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.WebDriverRunner;
import org.apache.commons.io.FileUtils;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import java.io.IOException;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.getSelenideDriver;
import static io.qameta.allure.Allure.addAttachment;
#Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
if (testExecutionResult.getStatus().equals(TestExecutionResult.Status.FAILED)) {
try {
File screenshotAs = ((TakesScreenshot) getSelenideDriver().getWebDriver()).getScreenshotAs(OutputType.FILE);
addAttachment("Screenshot", FileUtils.openInputStream(screenshotAs));
} catch (IOException | NoSuchSessionException e) {
// NO OP
} finally {
WebDriverRunner.getSelenideDriver().getWebDriver().quit();
}
}
}

java.lang.ClassCastException error when implementing extent reporting in TestNG XML file

I getting an error telling java.lang.ClassCastException: [My extent report class name] cannot be cast to org.testng.ITestNGListener when running the TestNG XML file as a Test suite.
I have automated a web page using page factory design technique using MAVEN and TestNG which consists of 6 page classes objects initialize in one package. I also written extent report listener class in another package. In addition to this I also has a base class in another package which is the super class of all 6 page object initialize classes. I have written test cases for 3 page classes and base class is the super class of these classes as well.
I have generated TestNG XML file by adding all 3 page test cases and adding extent report class as a listener for this XML file.
I will show the structure of my framework by including one class from each package below.
Page object initialize package - Login class
package com.crm.qa.pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.crm.qa.base.TestBase;
import com.crm.qa.util.TestUtil;
public class LoginPage extends TestBase {
#FindBy(name="username")
WebElement userName;
#FindBy(name="password")
WebElement password;
#FindBy(xpath="//input[#type='submit']")
WebElement loginBtn;
#FindBy(xpath="//button[contains(text(),'Sign Up')]")
WebElement signupBtn;
#FindBy(xpath="//img[#class = 'img-responsive']")
WebElement crmLogo;
//Initializing the page objects
public LoginPage() {
PageFactory.initElements(driver, this);
}
public String validateLoginPageTitle() {
return driver.getTitle();
}
public boolean validateCRMLogo() {
return crmLogo.isDisplayed();
}
public HomePage login (String un, String pwd) {
userName.sendKeys(un);
password.sendKeys(pwd);
loginBtn.submit();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
// Actions act = new Actions(driver);
// act.moveToElement(loginBtn).click().build().perform();
return new HomePage();
}
}
Base Package - Test Base class
package com.crm.qa.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import com.crm.qa.util.TestUtil;
import com.crm.qa.util.WebEventListener;
public class TestBase {
public static WebDriver driver;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventListener;
public TestBase() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream("C:\\Users\\i7\\git\\TestDesignFramework1\\Suresh.com.automationLearning\\src"
+ "\\main\\java\\com\\crm\\qa\\config\\config.properties");
prop.load(ip);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization () {
String browserName = prop.getProperty("browser");
if(browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "E:\\C\\Selenium\\Chrome Driver\\Extract\\chromedriver.exe");
driver = new ChromeDriver();
}
else if (browserName.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "E:\\C\\Selenium\\GeckoDriver\\Extract\\geckodriver.exe");
driver = new FirefoxDriver();
}
e_driver = new EventFiringWebDriver(driver);
eventListener = new WebEventListener();
e_driver.register(eventListener);
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get(prop.getProperty("url"));
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
}
}
Test cases package - Login page test class
package com.crm.qa.pages.testcases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.Assert;
import com.crm.qa.base.TestBase;
import com.crm.qa.pages.HomePage;
import com.crm.qa.pages.LoginPage;
public class LoginPageTest extends TestBase {
LoginPage loginPage;
HomePage homepage;
public LoginPageTest() {
super();
}
#BeforeMethod
public void setUp() {
initialization();
loginPage = new LoginPage();
}
#Test(priority = 1)
public void loginPageTitle() {
// extentTest = extent.createTest("loginPageTitle");
String title = loginPage.validateLoginPageTitle();
Assert.assertEquals(title, "#1 Free CRM software in the "
+ "cloud for sales and service");
}
#Test(priority = 2)
public void crmLogoImageTest() {
// extentTest = extent.createTest("crmLogoImageTest");
boolean flag = loginPage.validateCRMLogo();
Assert.assertTrue(flag);
}
#Test(priority = 3)
public void loginTest() {
// extentTest = extent.createTest("loginTest");
homepage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
System.out.println("Successfully login to the home page of freeCRM");
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
Test Util package - Extent report listener class
package com.crm.qa.ExtentReport;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
public class ExtentReportListener {
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest extentTest;
#BeforeSuite
public void setUp() {
htmlReporter = new ExtentHtmlReporter("C:\\Users\\i7\\git\\TestDesignFramework1\\Suresh.com.automationLearning\\Reporting\\ExtentReporting.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
}
#AfterMethod
public void getResult(ITestResult result) {
if (result.getStatus()==ITestResult.FAILURE) {
extentTest.fail(MarkupHelper.createLabel(result.getName()+" Test Case Failed", ExtentColor.RED));
extentTest.fail(result.getThrowable());
}
else if (result.getStatus()==ITestResult.SUCCESS) {
extentTest.pass(MarkupHelper.createLabel(result.getName()+" Test Case Passed", ExtentColor.GREEN));
extentTest.pass(result.getThrowable());
}
else {
extentTest.skip(MarkupHelper.createLabel(result.getName()+" Test Case Skipped", ExtentColor.ORANGE));
extentTest.skip(result.getThrowable());
}
}
#AfterSuite
public void tearDown() {
extent.flush();
}
}
TestNG XML file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Free CRM Test Application Regression Test Suite">
<listeners>
<listener class-name="com.crm.qa.ExtentReport.ExtentReportListener">
</listener>
</listeners>
<test thread-count="5" name="Free CRM app regression test cases">
<classes>
<class name="com.crm.qa.pages.testcases.LoginPageTest"/>
<class name="com.crm.qa.pages.testcases.HomePageTest"/>
<class name="com.crm.qa.pages.testcases.ContactsPageTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
TestNG is working as designed.
Whenever you add an entry such as the one below, into your testng suite xml file
<listeners>
<listener class-name="com.crm.qa.ExtentReport.ExtentReportListener"/>
</listeners>
TestNG expects that the class implements one of the sub-interfaces of org.testng.ITestNGListener
Your class doesn't do that, which is what is triggering the exception.
Please go through the relevant extent reports documentation to understand how to correctly work with extent reports.
The solution is to use "implements IReporter" inside testNG Report class.
In your case the testNG reporting class is "ExtentReportListener" so you have to type:
public class FinalReport implements IReporter
{}

JerseyClient2.x:SSLHandshakeException:java.security.cert.CertificateException:No name match.. even though client ignores all certs & trusts all hosts

public class Testing {
static WebTarget webTarget = null;
public static void main(String args[]) throws Exception {
webTarget = createClient();
WebTarget webTargetWithQueryParam = webTarget.queryParam("Version", "1").queryParam("Connection", "gOpAK52by09i305CMqJsnzzD4paQd1KG%2BVgdCBJw9h%0D%0AeuAxY2");
Invocation.Builder invocationBuilder = webTargetWithQueryParam.request(MediaType.APPLICATION_XML);
invocationBuilder.header("Host", "stagingtenant").header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.accept("text/xml");
Response response = invocationBuilder.post(Entity.xml(new File("..\sample.xml")));
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"=="+response.getStatusInfo());
}
String output = response.getStatusInfo().toString();
System.out.println(output);
}
public static Client initClient(ClientConfig config) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("SSL");
TrustManager certs =
new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){ return new X509Certificate[0];}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
};
ctx.init(null, new TrustManager[]{certs}, new SecureRandom());
return ClientBuilder.newBuilder()
.sslContext(ctx)
.withConfig((javax.ws.rs.core.Configuration) config)
.hostnameVerifier(new TrustAllHostNameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
}
public static class TrustAllHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static WebTarget createClient() throws KeyManagementException, NoSuchAlgorithmException{
ClientConfig clientConfig = new ClientConfig();
Client client = initClient(clientConfig);
client.register(new LoggingFilter());
HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder().credentialsForDigest("username", "password").build();
client.register(feature);
WebTarget webTarget = client.target("https://stagingtenant/apc/dig/ingestion/transcript");
return webTarget;
}
}
Response:
SEVERE: Error while committing the request output stream.
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching
stagingtenant found at
sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
fwiw, an example using "RestEasy" implementation of JAX-RS 2.x to build a special "trust all" client...
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import javax.ejb.Stateless;
import javax.net.ssl.SSLContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.TrustStrategy;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
#Stateless
#Path("/postservice")
public class PostService {
private static final Logger LOG = LogManager.getLogger("PostService");
public PostService() {
}
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public PostRespDTO get() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException, GeneralSecurityException {
//...object passed to the POST method...
PostDTO requestObject = new PostDTO();
requestObject.setEntryAList(new ArrayList<>(Arrays.asList("ITEM0000A", "ITEM0000B", "ITEM0000C")));
requestObject.setEntryBList(new ArrayList<>(Arrays.asList("AAA", "BBB", "CCC")));
//...build special "trust all" client to call POST method...
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(createTrustAllClient());
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
ResteasyWebTarget target = client.target("https://localhost:7002/postRespWS").path("postrespservice");
Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(requestObject, MediaType.APPLICATION_JSON));
//...object returned from the POST method...
PostRespDTO responseObject = response.readEntity(PostRespDTO.class);
response.close();
return responseObject;
}
//...get special "trust all" client...
private static CloseableHttpClient createTrustAllClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUSTALLCERTS).useProtocol("TLS").build();
HttpClientBuilder builder = HttpClientBuilder.create();
NoopHostnameVerifier noop = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, noop);
builder.setSSLSocketFactory(sslConnectionSocketFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
}
private static final TrustStrategy TRUSTALLCERTS = new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
}
related Maven dependencies
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>

TestNG + Selenium woes. noClassDef error, TestNG based selenium test

I've followed a lot of the guides and forum posts online but haven't had any luck getting this to work inside TestNG. It's a selenium grid based test, programmed in eclipse.
Had trouble, so used the libraries listed in the suggestion of this forum post: http://clearspace.openqa.org/message/66867
I am trying to run the suite in the testNG test plugin for eclipse (org.testng.eclipse). Also tried running the jar from command line through selenium grid to no avail.
Since I'm not a java developer, to be honest I'm not entirely sure what to look for. I've some familiarity with Java thanks to the Processing environment, but I've kind of been thrown into java/eclipse for this task and am at a bit of a loss. Anyway, any help is appreciated and thank you in advance.
Here's my code:
suite.java:
package seleniumRC;
//import com.thoughtworks.selenium.*;
//import junit.framework.*;
//import java.util.regex.Pattern;
//import static org.testng.AssertJUnit.assertTrue;
//import org.testng.annotations.AfterMethod;
//import org.testng.annotations.BeforeMethod;
//import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class suite extends Testcase1 {
#Test(groups = {"example", "firefox", "default"}, description = "test1")
public void user1() throws Throwable {
testCase1();
}
#Test(groups = {"example", "firefox", "default"}, description = "test2")
public void user2() throws Throwable {
testCase1();
}
}
The actual test case
package seleniumRC;
//import com.thoughtworks.selenium.*;
//import org.testng.annotations.*;
//import static org.testng.Assert.*;
//import com.thoughtworks.selenium.grid.demo.*;
//import junit.framework.*;
//import com.ibm.icu.*;
//import java.util.regex.Pattern;
//import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
public class Testcase1 extends SeleneseTestNgHelper {
private static int $itter = 10;
public static void main(String args[]) {
//junit.textui.TestRunner.run(Suite());
}
//public static Test Suite() {
// return new TestSuite(Testcase1.class);
//}
// public void setUp() throws Exception {
// setUp("http://localhost:8080/test", "*firefox");
//}
#BeforeMethod(groups = {"default", "example"}, alwaysRun = true)
#Parameters({"seleniumHost", "seleniumPort", "browser", "webSite"})
protected void startSession(String seleniumHost, int seleniumPort, String browser, String webSite) throws Exception {
startSession(seleniumHost, seleniumPort, browser, webSite);
selenium.setTimeout("120000");
}
#AfterMethod(groups = {"default", "example"}, alwaysRun = true)
protected void closeSession() throws Exception {
closeSession();
}
public void testCase1() throws Exception {
selenium.open("/login.action#login");
selenium.type("userName", "foo");
selenium.type("password", "bar");
selenium.click("login");
selenium.waitForPageToLoad("30000");
selenium.click("link=test");
Thread.sleep(4000);
selenium.click("//tr[4]/td[1]/a");
if(selenium.isElementPresent("//input[#id='nextButton']") != false){
selenium.click("//div[2]/input");
}
Thread.sleep(2000);
for(int i=0; i < $itter; i++) {
if(selenium.isElementPresent("//label") != false){
selenium.click("//label");
selenium.click("submitButton");
Thread.sleep(1500);
}
else{ Thread.sleep(1500);}
}
selenium.click("//body/div[2]/div[1]/div/a");
Thread.sleep(1500);
selenium.click("//a[contains(text(),'Finish Now')]");
Thread.sleep(2000);
selenium.click("link=View Results");
Thread.sleep(30000);
selenium.click("showAllImgCaption");
Thread.sleep(12000);
selenium.click("generateTimeButton");
Thread.sleep(2000);
selenium.click("link=Logout");
selenium.waitForPageToLoad("15000");
}
}
and the SeleneseTestNGHelper class
package seleniumRC;
import java.lang.reflect.Method;
//import java.net.BindException;
import com.thoughtworks.selenium.*;
//import org.openqa.selenium.SeleniumTestEnvironment;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
//import org.openqa.selenium.environment.GlobalTestEnvironment;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
public class SeleneseTestNgHelper extends SeleneseTestCase
{
private static Selenium staticSelenium;
#BeforeTest
#Override
#Parameters({"selenium.url", "selenium.browser"})
public void setUp(#Optional String url, #Optional String browserString) throws Exception {
if (browserString == null) browserString = runtimeBrowserString();
WebDriver driver = null;
if (browserString.contains("firefox") || browserString.contains("chrome")) {
System.setProperty("webdriver.firefox.development", "true");
driver = new FirefoxDriver();
} else if (browserString.contains("ie") || browserString.contains("hta")) {
driver = new InternetExplorerDriver();
} else {
fail("Cannot determine which browser to load: " + browserString);
}
if (url == null)
url = "http://localhost:4444/selenium-server";
selenium = new WebDriverBackedSelenium(driver, url);
staticSelenium = selenium;
}
#BeforeClass
#Parameters({"selenium.restartSession"})
public void getSelenium(#Optional("false") boolean restartSession) {
selenium = staticSelenium;
if (restartSession) {
selenium.stop();
selenium.start();
}
}
#BeforeMethod
public void setTestContext(Method method) {
selenium.setContext(method.getDeclaringClass().getSimpleName() + "." + method.getName());
}
#AfterMethod
#Override
public void checkForVerificationErrors() {
super.checkForVerificationErrors();
}
#AfterMethod(alwaysRun=true)
public void selectDefaultWindow() {
if (selenium != null) selenium.selectWindow("null");
}
#AfterTest(alwaysRun=true)
#Override
public void tearDown() throws Exception {
// super.tearDown();
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(Object actual, Object expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(String actual, String expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(String actual, String[] expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static void assertEquals(String[] actual, String[] expected) {
SeleneseTestBase.assertEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static boolean seleniumEquals(Object actual, Object expected) {
return SeleneseTestBase.seleniumEquals(expected, actual);
}
//#Override static method of super class (which assumes JUnit conventions)
public static boolean seleniumEquals(String actual, String expected) {
return SeleneseTestBase.seleniumEquals(expected, actual);
}
#Override
public void verifyEquals(Object actual, Object expected) {
super.verifyEquals(expected, actual);
}
#Override
public void verifyEquals(String[] actual, String[] expected) {
super.verifyEquals(expected, actual);
}
}
So I solved this by dropping the seleniumTestNGHelper class and reworking the classpaths by way of the ant file. It required completely working my suite/original testcases, but worked well within Grid.