Using Robotium for my Android automation I find myself creating the same steps for each test case.
I always need to "Login" and "Logout", I've been trying to create a FunctionsTestClass so I can simply call rLogin(); and rLogout();
Here is an example:
Adding my complete files.
'package com.myproject.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Logout extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.myproject.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Logout() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public static void logginin() throws Exception {
try {
//enter username
solo.sleep(17000);
throw e;
} catch (Exception e) {
solo.fail(
"com.myproject.mobile.test.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}'
Adding my second file
package com.mypackage.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import com.mypackage.mobile.test.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Test extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.mypackage.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Test() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public void testRecorded() throws Exception {
try {
Logout.logginin();
} catch (AssertionFailedError e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
} catch (Exception e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}
Updated the bottom two code to reflect my project.
Don't create testcase with name testLoggingin() . Instead of that creat a class having function login(). So that, whenever its needed you can import it and can call the function to login. And you can check conditions using assert.
Related
Error: java: cannot access java.util.concurrent.CompletableFuture class file for java.util.concurrent.CompletableFuture not found
Connected the library using Maven. Here is the TelegramBotsApi code to start the bot:
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
public class Main {
public static void main (String [] args) {
try {
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
botsApi.registerBot(new telegaBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
And here is the code of the bot itself:
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;
public class telegaBot extends TelegramLongPollingBot {
#Override
public String getBotUsername() {
return "bot_name";
}
#Override
public String getBotToken() {
return "token";
}
#Override
public void onUpdateReceived(Update update) {
}
}
Here are Java, Maven and IDEA versions
enter image description here
enter image description here
enter image description here
I first created a POM model framework for a test practice with LOG4J, listners for Screenshots.
Later tried to add Cucumber BDD framework also into the same framework. I'm able to run the tests as expected, but facing two issues:
POM Framework initial tests are able to take Screenshots, but BDD test fails with Null pointer exception, unable to get the driver object from the Methods.
Logs not getting printed for BDD tests while works fine with POM tests.
Code
TestRunner.java
package cucumberRunner;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
//import io.cucumber.junit.CucumberOptions;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
//#RunWith(Cucumber.class)
#CucumberOptions(
features="src/test/java/features",
glue="stepDefinitions")
public class TestRunner extends AbstractTestNGCucumberTests {
}
MyStepDefinitions.java
package stepDefinitions;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import e2E4.UserLogins;
import pageObjects.LandingPage;
import pageObjects.LoggedOnPage;
import resources.BaseClass;
public class MyStepDefinitions extends BaseClass {
public WebDriver driver;
Logger log=LogManager.getLogger(UserLogins.class.getName());
#Given("^Initialize browser with Chrome$")
public void initialize_browser_with_Chrome() throws Throwable {
driver = driverIni();
}
#Given("^Navigate to \"([^\"]*)\" website$")
public void navigate_to_saucelabs_website(String arg1) throws Throwable {
driver.get(arg1);
}
#When("^User enters \"([^\"]*)\" and \"([^\"]*)\" and Logs in$")
public void user_enters_and_and_Logs_in(String arg1, String arg2) throws Throwable {
LandingPage lp=new LandingPage(driver);
lp.sendUsername().sendKeys(arg1);
lp.sendPassword().sendKeys(arg2);
lp.sendLoginBtn().click();
log.info("Logging in");
}
#Then("^Verify if user successfully logged in$")
public void verify_if_user_successfully_logged_in() throws Throwable {
LoggedOnPage lop=new LoggedOnPage(driver);
Assert.assertTrue(lop.filterbtn().isDisplayed());
log.info("Logged in successfully");
}
}
BaseClass.java
package resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class BaseClass {
public WebDriver driver;
public Properties prop;
String dataPath=System.getProperty("user.dir");
public WebDriver driverIni() throws IOException {
FileInputStream fis=new FileInputStream(dataPath+"\\src\\main\\java\\resources\\data.properties");
prop=new Properties();
prop.load(fis);
String browserRequired=prop.getProperty("browser");
if(browserRequired.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", dataPath+"\\chromedriver.exe");
driver=new ChromeDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
return driver;
}
public String screenshot(String methodName, WebDriver driver) throws IOException {
TakesScreenshot ts=(TakesScreenshot) driver;
File source=ts.getScreenshotAs(OutputType.FILE);
String dest=dataPath+"\\reports\\"+methodName+".png";
FileUtils.copyFile(source, new File(dest));
return dest;
}
}
Listners.java
package e2E4;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import resources.BaseClass;
import resources.ExtendRep;
public class Listners extends BaseClass implements ITestListener {
WebDriver driver=null;
ExtendRep er=new ExtendRep();
ExtentReports extent=er.getReports();
ExtentTest test;
ThreadLocal<ExtentTest> et=new ThreadLocal<ExtentTest>();
public void onTestStart(ITestResult result) {
test=extent.createTest(result.getMethod().getMethodName());
et.set(test);
}
public void onTestSuccess(ITestResult result) {
String methodName=result.getMethod().getMethodName();
et.get().log(Status.PASS, "Test Passed Successfully");
try {
driver=(WebDriver)result.getTestClass().getRealClass().getDeclaredField("driver").get(result.getInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
et.get().addScreenCaptureFromPath(screenshot(methodName,driver),result.getMethod().getMethodName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onTestFailure(ITestResult result) {
String methodName=result.getMethod().getMethodName();
et.get().fail(result.getThrowable());
try {
driver=(WebDriver)result.getTestClass().getRealClass().getDeclaredField("driver").get(result.getInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
et.get().addScreenCaptureFromPath(screenshot(methodName,driver),result.getMethod().getMethodName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onTestSkipped(ITestResult result) {
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onTestFailedWithTimeout(ITestResult result) {
}
public void onStart(ITestContext context) {
}
public void onFinish(ITestContext context) {
extent.flush();
}
}
P.S : ExtentReports were working fine tho throu the Listners. Not able to figure it out :(
I'm working at the moment on a Mod for Minecraft with a dedicated Gui system written in C++ and Qt5. I let my GUI and Minecraft communicate through a named pipe, but I have there a small problem. I can read and write with a simple Java and C++(Qt) program into the pipe. But when I create a new instance of my Pipeendpoint class in post init of Minecraft Forge it can't read anything from the Pipe. In a standalone system, it can read stuff.
Not working Forge Implementation:
package de.CoderDE.CodersAnimationEditor;
import java.io.FileNotFoundException;
import de.CoderDE.CodersAnimationEditor.Pipe.PipeEndpoint;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
#SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy {
static PipeEndpoint pendpoint;
#Override
public void preInit(FMLPreInitializationEvent e) {
super.preInit(e);
}
#Override
public void init(FMLInitializationEvent e) {
super.init(e);
}
#Override
public void postInit(FMLPostInitializationEvent e) {
super.postInit(e);
try {
pendpoint = new PipeEndpoint();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
Working standalone implementation:
import java.io.FileNotFoundException;
import de.CoderDE.CodersAnimationEditor.Pipe.PipeEndpoint;
public class Main {
static PipeEndpoint pipe;
public static void main(String[] args) {
try {
pipe = new PipeEndpoint();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And the important PipeEndpoint class:
package de.CoderDE.CodersAnimationEditor.Pipe;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class PipeEndpoint {
private Thread reciever;
private RandomAccessFile pipe;
public PipeEndpoint() throws FileNotFoundException {
pipe = new RandomAccessFile("\\\\.\\pipe\\CodersAnimationEditor", "rw");
reciever = new Thread(new PipeEndpointReciever());
reciever.start();
}
private class PipeEndpointReciever implements Runnable {
#Override
public void run() {
try {
while (true) {
System.out.print((char)pipe.read());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And with "can't read anything" I mean that it never returns from pipe.read().
Oh, and the Java application starts after the C++(Qt) LocalServer started listening and waits for a new connection.
I have a plugin within i want to access to the class list of my model package from my maven project. Until now i just did this to load the classes into the plugin :
try {
runtimeClasspathElements = project.getRuntimeClasspathElements();
} catch (DependencyResolutionRequiredException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
for (int i = 0; i < runtimeClasspathElements.size(); i++) {
String element = (String) runtimeClasspathElements.get(i);
try {
runtimeUrls[i] = new File(element).toURI().toURL();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newLoader = new URLClassLoader(runtimeUrls,
Thread.currentThread().getContextClassLoader());
try { class=newLoader.loadClass("com.pkl.bc.personnaldata.model.Personne");
if(class!=null)
System.out.println(class.getCanonicalName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Until here i can see the full name of my class.
System.out.println(class.getDeclaredFields());
System.out.println(class.isAnnotationPresent(EditColumn.class));
for (Field f : class.getDeclaredFields()) {
EditColumn v = f.getAnnotation(EditColumn.class);
if (v != null) {
System.out.println(v.tableName());
System.out.println(v.oldName());
}
}
but i don't get anything, here is the output :
[Ljava.lang.reflect.Field;#398f573b
false
I also tried to use refelctions
Reflections reflections = new Reflections("com.pkl.bc.personnaldata.model.Personne");
Set<Field> annotated = reflections.getFieldsAnnotatedWith(EditColumn.class);
System.out.println(annotated);
this give me an empty list.
here is my annotation :
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD})
public #interface EditColumn {
String oldName() default "";
String newName() default "";
String tableName() default "";
}
the annotated field :
#EditColumn(newName = "main_adress", oldName = "adress", tableName = "Personne")
private String main_adress;
I fixed my answer,that your problem is loading different class instance in different ClassLoader when Thread.getContextClassLoader() returns null,because URLClassLoader(urls,parent) when parent is null.you can see the tests that both ways java return a Proxy instance for Annotation Name instance.occurs this problem often someone calls Thread.currentThread().setContextClassLoader(null) in somewhere.so you can solve the problem by checking the contextLoader whether is null.for example:
ClassLoader context=Thread.currentThread().getContextClassLoader();
if(context==null){
context=getClass().getClassLoader();
}
URLClassLoader loader=new URLClassLoader(urls,context);
Test
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static java.lang.String.format;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* Created by holi on 3/24/17.
*/
public class AnnotationsTest {
private interface StubClass {
Class<?> stubClass() throws ClassNotFoundException;
default <T extends Annotation> T annotation(Class<T> type) throws Exception {
return stubClass().getAnnotation(type);
}
default Annotation[] annotations() throws Exception {
return stubClass().getAnnotations();
}
}
private static final StubClass JAR_WITHIN_ANNOTATION_CLASS = jar("stubs-within-annotation-class.jar");
private static final StubClass JAR_WITHOUT_ANNOTATION_CLASS = jar("stubs-without-annotation-class.jar");
public static StubClass jar(String jar) {
URL jarFile = Objects.requireNonNull(ClassLoader.getSystemResource(jar), format("Jar file not found:%s", jar));
return () -> {
ClassLoader context = Thread.currentThread().getContextClassLoader();
return new URLClassLoader(new URL[]{jarFile}, context).loadClass("Stub");
};
}
private ClassLoader original;
#BeforeEach
void setUp() throws Throwable {
original = Thread.currentThread().getContextClassLoader();
}
#AfterEach
void tearDown() throws Throwable {
Thread.currentThread().setContextClassLoader(original);
}
#Test
void getAnnotationFromJarClassesWillReturnsContextLoaderAnnotationSharedInstanceIfContextLoaderAssociatedWithRuntimeClassLoader() throws Throwable {
Set<Object> annotationsCreated = new HashSet<>();
Set<Object> stubClassCreated = new HashSet<>();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
Stream.of(JAR_WITHIN_ANNOTATION_CLASS, JAR_WITHOUT_ANNOTATION_CLASS).forEach(asserts(stub -> {
Name it = stub.annotation(Name.class);
assertThat(it, is(instanceOf(Name.class)));
assertThat(it.value(), equalTo("stub"));
annotationsCreated.add(it);
stubClassCreated.add(stub.stubClass());
}));
assertThat(annotationsCreated, hasSize(1));
assertThat(stubClassCreated, hasSize(2));
}
#Test
void getAnnotationFromJarClassesWillReturnsNullIfNoContextLoaderAssociated() throws Throwable {
Thread.currentThread().setContextClassLoader(null);
Stream.of(JAR_WITHIN_ANNOTATION_CLASS, JAR_WITHOUT_ANNOTATION_CLASS).forEach(asserts(it -> {
//create different class instance in each class loader
assertThat(it.stubClass().getName(), equalTo("Stub"));
assertThat(it.annotation(Name.class), is(nullValue()));
}));
assertThat(JAR_WITHOUT_ANNOTATION_CLASS.annotations(), is(emptyArray()));
assertThat(JAR_WITHIN_ANNOTATION_CLASS.annotations(), arrayWithSize(1));
Annotation it = JAR_WITHIN_ANNOTATION_CLASS.annotations()[0];
assertThat(it.annotationType(), is(not(instanceOf(Name.class))));
assertThat(it.annotationType().getName(), equalTo(Name.class.getName()));
assertThat(it.annotationType().getDeclaredMethod("value").invoke(it), equalTo("stub"));
}
private interface Assert<T> {
void assertThat(T value) throws Exception;
}
private <T> Consumer<T> asserts(Assert<T> executor) {
return (value) -> {
try {
executor.assertThat(value);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
RuntimeException wrappedException = new RuntimeException(e);
wrappedException.setStackTrace(e.getStackTrace());
throw wrappedException;
}
};
}
}
#Name Annotation
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by holi on 3/24/17.
*/
#Retention(RetentionPolicy.RUNTIME)
public #interface Name {
String value();
}
Stub class
#Name("stub")
public class Stub{
}
You are already retrieving the class with its annotations , but you just need to add a loop to itirate all the annotations for each field you have.
try this example , it will print the annotation name and its values when it is available for a field of the loaded class.
for (Field f : loadedClass.getDeclaredFields()) {
System.out.println(f.getName());
for (Annotation a : f.getAnnotations()) {
System.out.println("## SHOWING ANNOTATION FOR FIELD:" + f.getName());
System.out.println(a.toString());
}
}
You can parse the toString to retrieve the values on that annotation.
Waiting for you feedback.
I know I can upload file to browser with many ways such as: AutoIt, Robot Class, and other ways(I tried them all and they worked most of time).
I got introduced to Winium and I would like to make the same test case with it, that is, upload a file to a browser using it, but I did not know what to do to switch between web driver to winium driver. Please help because I searched a lot for this trick but could not find any result
package testUtilities;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.winium.WiniumDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class WiniumWeb
{
WebDriver driver;
#BeforeClass
public void setUp() throws IOException
{
driver = new FirefoxDriver();
driver.navigate().to("http://the-internet.herokuapp.com/upload");
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\Resources\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists())
{
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try
{
driver = new WiniumDriver(new URL("http://localhost:9999"), null);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException
{
String file = System.getProperty("user.dir") + "\\Resources\\TestData.csv";
WebElement window = driver.findElement(By.className("File Upload"));
window.findElement(By.className("#32770")).sendKeys(file);
Thread.sleep(2000);
}
}
if you are still finding solution.I am sharing my script which worked for me.
public class FileUpload extends BaseClass {
static WiniumDriver d;
#BeforeClass
public void setUp() throws IOException {
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
LaunchLocalBrowser("chrome","http://the-internet.herokuapp.com/upload");//use your own code to launch browser
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\lib\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try {
d = new WiniumDriver(new URL("http://localhost:9999"),options);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException {
String file = System.getProperty("user.dir") + "\\lib\\Testdata.txt";
d.findElementByName("File name:").sendKeys(file);
d.findElementByXPath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']").click();
driver.findElement(By.id("file-submit")).click();
}
}
File upload using WiniumDriverService by referring to port- 9999. Creating winium instance using free port having issues. Below code is intended for sample implementation of Browser factory to facilitate web and desktop instances.
public class FactoryManager {
public static ClientFactory getIndividualProduct(EnumProductLists product) {
ClientFactory factory = null;
if (null != product) {
switch (product) {
case CHROME:
factory = new ProductChromeClient();
break;
case DESKTOP:
factory = new ProductWiniumClient();
break;
default:
break;
}
}
return factory;
}
}
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
public class ProductWiniumClient extends ClientFactory {
private WiniumDriverService service;
#Override
protected void startService() {
if (null == service) {
service = new WiniumDriverService.Builder()
.usingDriverExecutable(
new File(System.getProperty("user.dir") + "/WiniumFolder/Winium.Desktop.Driver.exe"))
.usingPort(9999).withVerbose(true).buildDesktopService();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void createService() {
startService();
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
deskClient = new WiniumDriver(service, options);
}
#Override
protected void stopService() {
if (null != service && service.isRunning()) {
service.stop();
}
}
}
public class TestCase1 {
WebDriver webClient;
WiniumDriver deskClient;
ClientFactory lists;
#BeforeTest
public void beforeTest() {
lists = FactoryManager.getIndividualProduct(EnumProductLists.CHROME);
webClient = (WebDriver) this.lists.getClient(WebDriver.class.getTypeName());
lists = FactoryManager.getIndividualProduct(EnumProductLists.DESKTOP);
deskClient = (WiniumDriver) this.lists.getClient("");
}
#Test
public void f() {
if (null != webClient) {
try {
webClient.manage().window().maximize();
webClient.get("https://uploadfiles.io/");
webClient.findElement(By.id("upload-window")).click();
String file = System.getProperty("user.dir") + "\\files\\upload.txt";
deskClient.findElement(By.name("File name:")).sendKeys(file);
deskClient.findElement(By.xpath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']")).click();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Client Instance is Null!");
}
}
#AfterTest
public void afterTest() {
}
}