Как программно запустить JUnit TestJAVA

Программисты JAVA общаются здесь
Ответить
Гость
 Как программно запустить JUnit Test

Сообщение Гость »

У меня есть следующий код, и я пытаюсь автоматизировать выполнение конкретных тестовых случаев в двух проектах. Однако похоже, что после выполнения большинство результатов теста оказываются ошибочными. Я подозреваю, что это может быть связано с отсутствием зависимостей. Может ли кто-нибудь помочь мне проверить и изменить его?

Код: Выделить всё

public class TestRunner {
public static void main(String[] args) throws Exception {
TestExecutionSummary summary1= runSingleTest("E:\\Tutorial\\proj1\\target\\test-classes","test.CFGTestTest");
TestExecutionSummary summary2= runSingleTest("E:\\Tutorial\\proj2\\target\\test-classes","test.ConfigTest");
CompareTestResult(summary1,summary2);
}

public  static void CompareTestResult(TestExecutionSummary summary1,TestExecutionSummary summary2){
System.out.println("\n-----------------Compare Test Result-----------------");
if(summary1.getTestsSucceededCount()==summary2.getTestsSucceededCount()){
System.out.println("Test1 and Test2 are the same");
System.out.println("Passed: "+summary1.getTestsSucceededCount()+" Failed: "+summary1.getTestsFailedCount());
}else{
System.out.println("Test1 and Test2 are different");
System.out.println("Test1: "+"Passed: "+summary1.getTestsSucceededCount()+" Failed: "+summary1.getTestsFailedCount());
System.out.println("Test2: "+"Passed: "+summary2.getTestsSucceededCount()+" Failed: "+summary2.getTestsFailedCount());
}
System.out.println("-----------------------------------------------------\n");
}

/**
* Execute a single test.
* @param classPath The classpath
* @param className The class name
* @throws Exception Exceptions
*/
private static TestExecutionSummary runSingleTest(String classPath,String className) throws Exception {
Class testClass = getTestClassFromPath(classPath, className);
assert testClass != null;
return runTest(testClass);
}

/**
* Get the test class from the classpath and class name.
* @param classPath The classpath
* @param className The class name eg: com.example.Test
* @return The test class
* @throws Exception Exceptions
*/
private static Class getTestClassFromPath(String classPath,String className) throws Exception {
// Check if the path exists
File file = new File(classPath);
if (!file.exists()) {
System.out.println("Path does not exist");
return null;
}
URL url = file.toURI().toURL();
try (URLClassLoader classLoader = new URLClassLoader(new URL[]{url})) {
return classLoader.loadClass(className);
}catch (ClassNotFoundException e){
System.out.println("Class loading failed"+e.getMessage());
throw e;
}catch (Exception e){
System.out.println("Exception"+e.getMessage());
throw e;
}
}

/**
* Run the test.
* @param testClass The test class
*/
private static TestExecutionSummary runTest(Class testClass) {
System.out.println("Running tests for class " + testClass.getName());
Launcher launcher = LauncherFactory.create(); // Create a Launcher
// Create a SummaryGeneratingListener
SummaryGeneratingListener listener = new SummaryGeneratingListener();

// Create a LauncherDiscoveryRequest that includes the test class
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(selectClass(testClass))
.build();

// Register the listener with the Launcher
launcher.registerTestExecutionListeners(listener);
launcher.execute(request); // Execute the tests

// Get the execute summary
return listener.getSummary();
}
}
Вот результат. Хотя я получил те же результаты тестов, об ошибках зависимостей не сообщалось. Согласно ожидаемому результату, все пять функциональных тестов должны быть пройдены.

Код: Выделить всё

Running tests for class test.CFGTestTest
Running tests for class test.CFGTestTest

-----------------Compare Test Result-----------------
Test1 and Test2 are the same
Passed: 0 Failed: 5
-----------------------------------------------------
И я уже добавил ряд зависимостей POM, связанных с тестированием.

Подробнее здесь: https://stackoverflow.com/questions/782 ... junit-test
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»