2

Ситуация такая. Нужно запустить тест на java с помощью командной строки Windows. После компиляции получила файл .class, который не удается запустить. Прописываю:
java -cp C:\Users\Yuliia\IdeaProjects\test1123\classes\com\selenium\test\ SimpleTest

Выдает:

Error: Could not find or load main class SimpleTest.

Selenium Standalone server запущен, java установлена. Писала в IntelliJ IDEA IDE.

Код:

package com.selenium.test;


import com.selenium.test.webtestsbase.WebDriverFactory;
import com.selenium.test.utils.DOMParser;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import java.util.ArrayList;

import static org.junit.Assert.assertFalse;


public class SimpleTest extends TestCase {

    public static final DOMParser DOM_PARSER = new DOMParser();
//    @Rule
//    public ScreenShotOnFailRule screenShotOnFailRule = new ScreenShotOnFailRule();

    public static void main(String[] args) {
        junit.textui.TestRunner.run(SimpleTest.class);
    }

//    @Before
//    public void beforeTest() {
//        WebDriverFactory.startBrowser(false);
//    }

    @Test
    public void testPages() {
        DOMParser dom = DOM_PARSER;
        dom.Parse_sitemap();
        ArrayList pages = dom.getPages();

        WebDriverFactory.startBrowser(false);

        WebDriver driver = WebDriverFactory.getDriver();
        for (int i = 0; i < pages.size(); i++) {
            String url = pages.get(i).toString();
            driver.get(url);
            String bodyText = driver.findElement(By.tagName("body")).getText();
            assertFalse("Page was not found on server", driver.getTitle().contains("404"));
            assertFalse("Page was not found on site itself", driver.getPageSource().contains("This page was lost at sea"));
            assertFalse("Page was not found on site itself", bodyText.contains("NOT FOUND"));
        }

        WebDriverFactory.finishBrowser();

    }

Попробовала так: C:\Users\Yuliia\IdeaProjects\test1123\src\classes\com\selenium\test> java -cp SimpleTest.class

Выдало:

Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include:
    -d32          use a 32-bit data model if available
    -d64          use a 64-bit data model if available
    -client       to select the "client" VM
    -server       to select the "server" VM
                  The default VM is client.

    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A ; separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose:[class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -no-jre-restrict-search
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions with specified granularity
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions with specified granularity
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                  see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.

НОВОЕ

Запускаю:

C:\Users\Yuliia\IdeaProjects\test1123>java -cp "C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.4\lib\*";"C:\Users\Yuliia\Desktop\selenium-2.47.1\*";"C:\Users\Yuliia\Desktop\commons-io-2.4\*";C:\Users\Yuliia\IdeaProjects\test1123\classes org.junit.runner.JUnitCore com.selenium.test.junit.tests.SimpleTest

Получаю:

JUnit version 4.11
.E
Time: 1.082
There was 1 failure:
1) testPages(com.selenium.test.junit.tests.SimpleTest)
com.selenium.test.exceptions.TestsConfigurationException: Unable to read property file with name 'config.properties' - file not found
        at com.selenium.test.configuration.properties.PropertiesLoader.populate(PropertiesLoader.java:37)
        at com.selenium.test.configuration.TestsConfig.<init>(TestsConfig.java:25)
        at com.selenium.test.configuration.TestsConfig.getConfig(TestsConfig.java:19)
        at com.selenium.test.webtestsbase.WebDriverFactory.startBrowser(WebDriverFactory.java:46)
        at com.selenium.test.junit.tests.SimpleTest.testPages(SimpleTest.java:45)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at junit.framework.TestCase.runTest(TestCase.java:176)
        at junit.framework.TestCase.runBare(TestCase.java:141)
        at junit.framework.TestResult$1.protect(TestResult.java:122)
        at junit.framework.TestResult.runProtected(TestResult.java:142)
        at junit.framework.TestResult.run(TestResult.java:125)
        at junit.framework.TestCase.run(TestCase.java:129)
        at junit.framework.TestSuite.runTest(TestSuite.java:255)
        at junit.framework.TestSuite.run(TestSuite.java:250)
        at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
        at org.junit.runners.Suite.runChild(Suite.java:127)
        at org.junit.runners.Suite.runChild(Suite.java:26)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
        at org.junit.runner.JUnitCore.runMain(JUnitCore.java:96)
        at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:47)
        at org.junit.runner.JUnitCore.main(JUnitCore.java:40)

FAILURES!!!
Tests run: 1,  Failures: 1
12
  • Ну а по факту - у тебя нет public static void main(String ... args) метода в этом SimpleTest 17 авг 2015 в 15:59
  • @AndrewBystrov куда, что, как? это мой первый тест и первый опыт запуска через командную строку.
    – Юлия
    17 авг 2015 в 16:00
  • @Юлия Приведите минимальный пример кода для воспроизведения ошибки. Так будет понятнее, что у вас не так и можно будет аргументировать ответы. 17 авг 2015 в 16:01
  • @AndrewBystrov public static void main(String[] args) { junit.textui.TestRunner.run(SimpleTest.class); } Это есть.
    – Юлия
    17 авг 2015 в 16:02
  • @TimofeyBondarev добавила код
    – Юлия
    17 авг 2015 в 16:04

1 ответ 1

1

Для начала, рекомендуется использовать написание тестов в стиле JUnit 4, т.е. без наследования от TestCase, а используя аннотацию @Test.

Для описания того, как нужно запускать тест в вашем случае, разберу сначала пример с использованием синтаксиса JUnit 3.

Имеется проект со следующей структурой файлов:

my_project/
--junit.jar
--hamcrest-core.jar
--com/
----prog/
------MyTest.java

junit.jar и hamcrest-core.jar -- это файлы библиотеки JUnit.

Содержимое файла my_project/com/prog/MyTest.java:

package com.prog;

import static org.junit.Assert.*;
import junit.framework.TestCase;

public class MyTest extends TestCase {
    public void testSum() {
        assertEquals(3, 1 + 2);
    }
}

Скомпилировать его можно следующим образом:
my_project> javac -cp .;junit.jar my_project\com\prog\MyTest.java

Для Windows используется разделитель путей ; и желателен символ \ для каталогов.
Для Linux разделитель путей : и символ / для каталогов.

После этого появится файл my_project/com/prog/MyTest.class.

Для запуска тестов этого файла из командной строки нужно использовать следующую команду:
my_project> java -cp .;junit.jar;hamcrest-core.jar junit.textui.TestRunner com.prog.MyTest

После этого будет показано сообщение об успешном прохождении тестов.

.
Time: 0,001

OK (1 test)

Для JUnit версии 4 код тестов немного изменится. my_project/com/prog/MyTest.java:

package com.prog;

import static org.junit.Assert.*;
import org.junit.Test;

public class MyTest {
    @Test
    public void testSum() {
        assertEquals(3, 1 + 2);
    }
}

Изменится и запуск тестов:

my_project> java -cp .;junit.jar;hamcrest-core.jar org.junit.runner.JUnitCore com.prog.MyTest

Результат запуска:

JUnit version 4.12
.
Time: 0,004

OK (1 test)

Источник:

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.