Я столкнулся с некоторой проблемой при запуске моей структуры cucumber через командную строку. Что я сделал, я создал один универсальный пакет c utils, и там я реализую класс Driver и использовал переключатель для запуска каждого драйвера. Теперь мой мотив - я не буду предоставлять браузер в файле свойств или где-либо еще в моем проекте. Мой браузер запустится, когда я передаю имя браузера (например: firefox, chrome, ie) из командной строки. Я использовал для предоставления ниже команды для запуска конкретного браузера. Синтаксис : mvn clean test -DBrowser = Chrome. Но проблема в том, что эта команда работает отлично, когда я выбираю браузер chrome из командной строки. При выборе Firefox я получаю ошибку. ошибка выглядит как ошибка версии. Поэтому я реализовал код класса Driver таким образом, чтобы не передавать браузер из командной строки. и запустите код из затмения, когда он запускает драйвер Firefox. и затем я запускаю тот же код из командной строки, в то время как я получаю ошибку при запуске Firefox. Может кто-нибудь предложить мне, как решить этот тип сценария? Любые потенциальные клиенты будут благодарны :) Заранее спасибо :)
Ниже код для кода класса водителя:
public static WebDriver driver;
public static Properties prop = new Properties();
public static Logger logger = Logger.getLogger(Driver.class.getName());
public static WebDriver launchBrowser() {
try {
PropertyConfigurator.configure("./resourceLib/configuration/log4j.properties");
logger.info("INFO Msg:=====================>Loading Properties file");
prop.load(new FileInputStream("./resourceLib/configuration/configFile.properties"));
}catch(Exception e) {
logger.error("ERROR Msg:=====================>Error while loading properties file"+e);
e.printStackTrace();
}
//browser identification should be user specific.
String browserName=System.getProperty("Browser");
System.out.println("Printing browser:=======>"+browserName);
if(browserName==null) {
browserName=System.getenv("Browser");
System.out.println(browserName);
if(browserName==null) {
browserName="Firefox";
}
}
switch (browserName) {
case "Chrome" :
try {
System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");
logger.info("INFO Msg:=====================> Launching Chrome browser");
if(browserName.equals("Chrome")) {
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}else {
logger.error("ERROR Msg:=====================> Error while executing chrome driver");
}
}catch (Exception e) {
logger.error("ERROR Msg:=====================> Error while launching Chrome browser"+e);
e.printStackTrace();
}
break;
case "Firefox" :
try {
logger.info("INFO Msg:=====================> Launching Firefox browser");
if(browserName.equals("Firefox")) {
WebDriverManager.firefoxdriver().setup();
driver=new FirefoxDriver();
System.out.println("Hello this line should execute====>"+driver);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}else {
logger.error("ERROR Msg:=====================> Error while executing firefox driver");
}
}catch (Exception e) {
logger.error("ERROR Msg:=====================> Error while launching Firefox browser"+e);
e.printStackTrace();
}
break;
case "IE":
try {
logger.info("INFO Msg:=====================> Launching IE browser");
if(browserName.equals("IE")) {
WebDriverManager.iedriver().setup();
driver=new InternetExplorerDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}else {
logger.error("ERROR Msg:=====================> Error while executing IE driver");
}
}catch (Exception e) {
logger.error("ERROR Msg:=====================> Error while launching IE browser"+e);
e.printStackTrace();
}
logger.error("ERROR Msg:=====================> Please choose the correct browser");
break;
default:
try {
logger.info("INFO Msg:=====================> Launching IE browser");
WebDriverManager.firefoxdriver().setup();
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}catch (Exception e) {
logger.error("ERROR Msg:=====================> Error while launching Firefox browser"+e);
e.printStackTrace();
}
break;
}
return driver;
}
}
Ниже код для кода класса определения шага:
@Before()
public void setUp(Scenario scenario) {
this.scenario=scenario;
Report.setReport();
try {
logger.info("INFO Msg:===============>Launch the Browser");
Driver.launchBrowser();
logger.info("Executing Scenario :"+scenario.getName());
}catch (Exception e) {
logger.error("ERROR Msg:=============>Error While launcing browser ");
}
}
//tear down method where browser should close
@After
public void tearDown(Scenario scenario) {
String timeStamp=new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
scenario.write("Finished Scenario");
if(scenario.isFailed()) {
scenario.embed(((TakesScreenshot)Driver.driver).getScreenshotAs(OutputType.BYTES), "./report/screenshots/"+timeStamp+".png");
}
logger.info("Test Enviourment closed");
Driver.driver.quit();
Report.endReport();
}
@Given("^I want Login to the application$")
public void i_want_Login_to_the_application() throws Throwable {
Report.createReport("Login to ActiTime Application and Validate Enter Time-Track heading should be available", "Login to ActiTime Application");
loginfo=Report.createTesteport("Given", "I want Login to the application");
try {
loginfo.info("INFO Msg:===============>Launch AtiTime application");
Driver.driver.get(prop.getProperty("actiTime_URL"));
loginfo.info("AtiTime application launch properly");
} catch (Exception e) {
Report.tesepHandelStep("FAIL", loginfo, e);
loginfo.error("ERROR Msg:=============>Error While launcing ActiTime application"+e);
}
}
Ниже приведен код для класса бегуна:
@RunWith(Cucumber.class)
@CucumberOptions(features="./resourceLib/Features", glue= {"StepDefination"},
format= { "pretty","html:report/cucumberReports", "json:target/cucumberReports/cucumber.json"
,"junit:target/cucumberReports/cucumber.xml"},
tags= {"@SmokeTest"}, monochrome=true,plugin = ("json:target/cucumber-
reports/CucumberTestReport.json"))
public class TestRunner {}
Ошибка при получении:
05-01-2020 19:59:09 Driver. java INFO [main] GenericUtils.Driver 80 - Сообщение INFO: ====================> Запуск браузера Firefox 01 мая 2020 г. 19:59:09 java .util.prefs.WindowsPreferences ПРЕДУПРЕЖДЕНИЕ: Не удалось открыть / создать prefs root узел Software \ JavaSoft \ Prefs в root 0x80000002. Windows RegCreateKeyEx (...) вернул код ошибки 5. [DEBUG] Предпочтение firefox = 74 (действует до 2020-05-02 00:25:12) [DEBUG] Предпочтение firefox74 = 0.26.0 (действует до 2020-05 -02 00:25:12) [INFO] Использование geckodriver 0.26.0 (поскольку на вашем компьютере установлен Mozilla Firefox 74) [DEBUG] Драйвер geckodriver 0.26.0 найден в кеше [INFO] Экспорт webdriver.gecko.driver как C: \ Users \ Admin.m2 \ repository \ webdriver \ geckodriver \ win64 \ 0.26.0 \ geckodriver.exe 05-01-2020 19:59:32 Driver. java ОШИБКА [главная] GenericUtils.Driver 91 - ОШИБКА Msg: =====================> Ошибка при запуске Firefox browserorg.openqa.selenium.WebDrive rException: java. net .ConnectException: Не удалось подключиться к localhost / 0: 0: 0: 0: 0: 0: 0: 1: 45951 Информация о сборке: версия: '3.141.59', версия: 'e82be7d358', время: '2018-11-14T08: 17 : 03 'Системная информация: хост:' ADMIN-P C ', ip:' 192.168.0.100 ', os.name:' Windows 7 ', os.arch:' amd64 ', os.version:' 6.1 ', java .version:' 1.8.0_172 'Информация о драйвере: driver.version: Драйвер org.openqa.selenium.W ebDriverException: java. net .ConnectException: Не удалось подключиться к localhost / 0: 0: 0: 0: 0: 0: 0: 1: 45951 Информация о сборке: версия: '3.141.59', версия: 'e82be7d358 ', время:' 2018-11-14T08: 17: 03 'Информация о системе: хост:' ADMIN-P C ', IP-адрес:' 192.168.0.100 ', имя os.name:' Windows 7 ', os. arch: 'amd64', os.version: '6.1', java .version: '1.8.0_172' Информация о драйвере: driver.version: Драйвер в org.openqa.selenium.remote.service.DriverCommandExecutor.execute (DriverCommandExecutor. java: 92) в org.openqa.selenium.remote.RemoteWebDriver.execute (RemoteWebDriver. java: 552) в org.openqa.selenium.remote.RemoteWebDriver.startSession (RemoteWebDriver. java: 21) .openqa.selenium.remote.RemoteWebDriver. (RemoteWebDriver. java: 131) в org.openqa.selenium. firefox .FirefoxDriver. (FirefoxDriver. java: 147) в org.openqa.selenium. firefox .FirefoxDriver. (FirefoxDriver. java: 125) в GenericUtils.Driver.launchBrowser (Driver. java: 83) в StepDefination.Login_ActiTime_And_Validate_EnterTimeTrackStep.setUp (Login_ActiTime) Validate_EnterTimeTrackStep. java: 75) в sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl. invoke (DelegatingMethodAccessorImpl. java: 43) в java .lang.reflect.Method.invoke (Method. java: 498) в cucumber.runtime.Utils $ 1.call (Utils. java: 40) в cucumber.runtime.Timeout.timeout (Timeout. java: 16) в cucumber.runtime.Utils.invoke (Utils. java: 34) в cucumber.runtime. java .JavaHookDefinition.execute (JavaHookDefinition. java: 60) в cucumber.runtime.Runtime.runHookIfTagsMatch (время выполнения. java: 224) в cucumber.runtime.Runtime.runHooks (время выполнения. java: 212) в cucumber.runtime.Runtime.runBeforeHooks (время выполнения. java: 202) на cucumber.runtime.model.CucumberScenario.run (CucumberScenario. java: 40) на cucumber.runtime.junit.ExecutionUnitRunner.run (ExecutionUnitRunner. java: 102) на cucumber.runtime.jun .jun. FeatureRunner.runChild (FeatureRunner. java: 63) в cucumber.runtime.junit.FeatureRunner.runChild (FeatureRunner. java: 18) в org.junit.runners.ParentRunner $ 4.run (ParentRunner. java: 331 ) в org.junit.runners.ParentRunner $ 1.schedule (ParentRunner. java: 79) в org.junit.runners.ParentRunne r.runChildren (ParentRunner. java: 329) в org.junit.runners.ParentRunner.access $ 100 (ParentRunner. java: 66) в org.junit.runners.ParentRunner $ 2.оценке (ParentRunner. java: 293) в org.junit.runners.ParentRunner $ 3.evaluate (ParentRunner. java: 306) в org.junit.runners.ParentRunner.run (ParentRunner. java: 413) в cucumber.runtime.junit.FeatureRunner. запустить (FeatureRunner. java: 70) в cucumber.api.junit.Cucumber.runChild (Cucumber. java: 95) в cucumber.api.junit.Cucumber.runChild (Cucumber. java: 38) в организации .junit.runners.ParentRunner $ 4.run (ParentRunner. java: 331) в org.junit.runners.ParentRunner $ 1.schedule (ParentRunner. java: 79) в org.junit.runners.ParentRunner.runChildren (ParentRunner. . java: 329) в org.junit.runners.ParentRunner.access $ 100 (ParentRunner. java: 66) в org.junit.runners.ParentRunner $ 2.оценке (ParentRunner. java: 293) в орг. junit.runners.ParentRunner $ 3.evaluate (ParentRunner. java: 306) в org.junit.runners.ParentRunner.run (ParentRunner. java: 413) в cucumber.api.junit.C ucumber.run (огурец. java: 100) в орг. apache .maven.surefire.junit4.JUnit4Provider.execute (JUnit4Provider. java: 365) в орг. apache .maven.surefire.junit4. JUnit4Provider.executeWithRerun (JUnit4Provider. java: 273) в орг. apache .maven.surefire.junit4.JUnit4Provider.executeTestSet (JUnit4Provider. java: 238) в организации. JUnit4Provider.invoke (JUnit4Provider. java: 159) в орг. apache .maven.surefire.booter.ForkedBooter.runSuitesInProcess (ForkedBooter. java: 377) в орг. apache .mabooter. ForkedBooter.execute (ForkedBooter. java: 138) в орг. apache .maven.surefire.booter.ForkedBooter.run (ForkedBooter. java: 465) в орг. apache .maven.surefire.booter. ForkedBooter.main (ForkedBooter. java: 451) Причина: java. net .ConnectException: Не удалось подключиться к localhost / 0: 0: 0: 0: 0: 0: 0: 1: 45951 в okhttp3 .internal.connection.RealConnection.connectSocket (RealConnection. java: 247) по адресу okhttp3.internal.connection.RealConnection.connect (RealConnection. java: 165) по адресу okhttp3.i nternal.connection.StreamAllocation.findConnection (StreamAllocation. java: 257) по адресу okhttp3.internal.connection.StreamAllocation.findHealthyConnection (StreamAllocation. java: 135) по адресу okhttp3.internal.connection.StreamAllocation. *: 114) в okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor. java: 42) в okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain. java: 147) в okhttp3.internalinorter.htpt. .proceed (RealInterceptorChain. java: 121) по адресу okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor. java: 93) в okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain. java: 147) в okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain. java: 121) в промежуточном мосту перехватчика. . java: 93) в okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain. java: 147) в okhttp3.internal.http.RetryAndFollowUpInterceptor. http.RealInterceptorChain.proceed (RealInterceptorChain. java: 147) в. .RealCall.execute (RealCall. java: 77) в org.openqa.selenium.remote.internal.OkHttpClient.execute (OkHttpClient. java: 103) в org.openqa.selenium.remote.ProtocolHandshake (протокол создания . java: 105) в org.openqa.selenium.remote.ProtocolHandshake.createSession (ProtocolHandshake. * 1 130 *: 74) в org.openqa.selenium.remote.HttpCommandExecutor.execute (HttpCommandExecutor. java: 136) в org.openqa.selenium.remote.service.DriverCommandExecutor.execute (DriverCommandExecutor. * 1132). * 1132 .. еще 48