Как исправить 'Unable to Load browser: null' (NPE) при запуске автоматических тестов с использованием огурца и корнишона - PullRequest
0 голосов
/ 30 марта 2019

Я использую фреймворк селена в Java, который использует класс DriverFactor, класс Constant, класс ReadConfigFile и файл config.properities для хранения соответствующих данных, в которые я могу обращаться через DriverFactory.

Однако, когда я запускаю файл объектов, я почти сразу же получаю сообщение об ошибке: «Невозможно загрузить браузер: ноль».

Я полагаю, что это происходит, если файл конфигурации не установлен 't читается правильно, поэтому возвращает «ноль» и затем завершается неудачно.Я просто не могу решить проблему.

Я добавил e.printstacktrace ();чтобы попытаться получить лучшее представление о том, откуда возникла проблема, но я еще не решил проблему.

DriverFactory.java

package utils;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class DriverFactory {

    public static WebDriver driver;

    public WebDriver getDriver() {

        try {
            // Read Config
            ReadConfigFile file = new ReadConfigFile();
            String browser = file.getBrowser();

            switch (browser) {

            /*
             * switch statement lets you select the browser you want
             */

            case "firefox":
                // code
                if (null == driver) {
                    System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
                    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
                    capabilities.setCapability("marionette", true);
                    driver = new FirefoxDriver();
                }

                break;

            case "chrome":
                // code
                if (null == driver) {
                    System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
                    driver = new ChromeDriver();
                    driver.manage().window().maximize();
                }

                break;
            }

        } catch (Exception e) { 
            System.out.println("Unable to load browser: " + e.getMessage());
            e.printStackTrace();
        }// finally {
            //driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
        //}
        return driver;
    }
}

Константа.java

package utils;

public class Constant {

    /*
     * Config Property File 
     */

    public final static String CONFIG_PROPERTIES_DIRECTORY = "config.properties";

    public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\chromedriver.exe";

    public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\geckondriver.exe";

}

ReadConfigFile.java

package utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadConfigFile {
    protected InputStream input = null;
    protected Properties prop = null;

    public ReadConfigFile() {
        try {
            ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
            prop = new Properties();
            prop.load(input);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getBrowser() {
        if (prop.getProperty("browser") == null)
            return "";
        return prop.getProperty("browser");
    }

}

config.properities

browser=chrome

Console / StackTrace распечатать

Feature: Log into account
  Existing user should be able to log into account using correct credentials

  Scenario Outline: Login to account with credentials         # C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:4
    Given user navigates to "<url>"
    When user clicks on the login portal button
    And User enters username "<username>"
    And User enters password "<password>"
    And User clicks on the login button
    Then user should be presented with validation "<message>"

    Examples: 
Unable to load browser: null
java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at utils.ReadConfigFile.<init>(ReadConfigFile.java:15)
    at utils.DriverFactory.getDriver(DriverFactory.java:16)
    at stepDefinitions.MasterHooks.setup(MasterHooks.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
    at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
    at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
    at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
    at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
    at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
    at cucumber.runtime.Runtime.run(Runtime.java:122)
    at cucumber.api.cli.Main.run(Main.java:36)
    at cucumber.api.cli.Main.main(Main.java:18)
Unable to load browser: null
java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at utils.ReadConfigFile.<init>(ReadConfigFile.java:15)
    at utils.DriverFactory.getDriver(DriverFactory.java:16)
    at stepDefinitions.GenericWebSteps.user_navigates_to(GenericWebSteps.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
    at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
    at cucumber.runtime.Runtime.run(Runtime.java:122)
    at cucumber.api.cli.Main.run(Main.java:36)
    at cucumber.api.cli.Main.main(Main.java:18)

  Scenario Outline: Login to account with credentials                 # C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:14
    Given user navigates to "http://www.webdriveruniversity.com"      # GenericWebSteps.user_navigates_to(String)
      java.lang.NullPointerException
        at stepDefinitions.GenericWebSteps.user_navigates_to(GenericWebSteps.java:21)
        at ✽.Given user navigates to "http://www.webdriveruniversity.com"(C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:5)

    When user clicks on the login portal button                       # GenericWebSteps.user_clicks_on_the_login_portal_button()
    And User enters username "tomdale"                                # GenericWebSteps.user_enters_a_username(String)
    And User enters password "testuser1"                              # GenericWebSteps.user_enters_a_password(String)
    And User clicks on the login button                               # GenericWebSteps.user_clicks_on_the_login_button()
    Then user should be presented with validation "validation failed" # GenericWebSteps.user_should_be_presented_with_validation(String)

Failed scenarios:
C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:14 # Scenario Outline: Login to account with credentials

1 Scenarios (1 failed)
6 Steps (1 failed, 5 skipped)
0m0.076s

java.lang.NullPointerException
    at stepDefinitions.GenericWebSteps.user_navigates_to(GenericWebSteps.java:21)
    at ✽.Given user navigates to "http://www.webdriveruniversity.com"(C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:5)

Я ожидаюлибо экземпляр драйвера chrome, либо экземпляр драйвера gecko для загрузки и выполнения моего теста.

Фактические результаты, я получил сообщение «Невозможно загрузить браузер: пусто» ошибка

Ответы [ 2 ]

0 голосов
/ 01 апреля 2019

Для тех, кто борется с подобной проблемой, мне удалось решить ее в конце концов.

Итак, прежде всего, в файле ReadConfigFile.java, в инструкции try вы захотите установить инициализацию ReadConfig для ввода. Как показано ниже ..

    try {
        input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
        prop = new Properties();
        prop.load(input);

    } catch (IOException e) {
        e.printStackTrace();
    }

Кроме того, в вашем классе Constant.java установите для CONFIG_PROPERTIES_DIRECTORY путь к файлу, в котором хранится ваш файл config.properties, как показано ниже:

package utils;

public class Constant {

    /*
     * Config Property File 
     */

    public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";

    public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\chromedriver.exe";

    public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\geckondriver.exe";

}

Если вы затем запустите настройки для выбранного файла компонентов, он должен создать экземпляр выбранного веб-драйвера, и ваш тест должен работать в обычном режиме.

0 голосов
/ 30 марта 2019

В этих строках

public class ReadConfigFile {
    protected InputStream input = null;
    protected Properties prop = null;

    public ReadConfigFile() {
        try {
            ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
            prop = new Properties();
            prop.load(input);

вы инициализировали input как ноль, а затем в prop.load(input) вы загружаете input, который все еще равен нулю.Вот почему существует NPE.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...