【问题标题】:How can I export JUnit test cases into an executable .jar?如何将 JUnit 测试用例导出到可执行的 .jar 中?
【发布时间】:2018-08-17 11:44:10
【问题描述】:

我正在使用 Selenium 和 JUnit 来自动化一些测试。我希望能够将其导出到可运行的 jar 文件中。我不能,我假设这是因为没有 main 方法,JVM 不知道要运行什么......

我看到了这篇帖子how to export (JUnit) test suite as executable jar,它建议添加一个 main 并从那里运行 JUnit。 (我会评论那篇文章,但它没有让我????)

public static void main(String[] args) {
    JUnitCore.main("folder.package.testClass");
}

我用这个 main 方法创建了一个新的 java 类,但从未执行过测试类(来自 eclipse)。此外,如果我尝试导出项目,我会收到错误并且它不会导出。

为了将所有 JUnit 类导出到 1 个 Jar 文件并从那里运行,我能做到这一点的最佳方法是什么?我可能会构建一个小菜单,用户可以在其中选择他们想要运行的测试类(我假设在某些地方需要一个 main 方法......)。

【问题讨论】:

  • 可能是导出错误的原因。首先,确保您正在创建有效的可执行 jar(带有一些打印行等)
  • 它也不能从 Eclipse 运行.. 但是导出不起作用,我知道它坏了
  • 让我们关注执行问题。我相信您确定存在问题
  • 是的,我累了上面的代码,我也尝试了这里提供的代码logicbig.com/tutorials/unit-testing/junit/junit-core.html Java 类运行,但它从不访问 JUnit 类,它从不运行它。
  • 链接中提供的示例要求您指向测试套件类而不是包。是“folder.package.testClass”吗?是测试套件类的路径吗?

标签: java testing junit


【解决方案1】:

您可以通过以下方式执行测试(仅检查当前场景):

  1. 创建新的 Eclipse Java 项目
  2. 将 junit 和 hamcrest jar 添加到您的构建路径(我使用的是 junit-4.12hamcrest-core-1.3)。它应该看起来:

  1. test 文件夹下创建您的测试:

    package com.example.junit5;
    
    import static org.junit.Assert.assertTrue;
    
    import org.junit.Test;
    
    public class FirstTest {
    
        @Test
        public void testTrue() {
            System.out.println("Executing testTrue()");
            assertTrue(true);     
         }
    }
    
  2. src 文件夹下创建你的 main(executor) 类:

    package com.example.junit5;
    
    import org.junit.runner.JUnitCore;
    
    public class Executor {
    
        public static void main(String[] args) {
            JUnitCore.main("com.example.junit5.FirstTest");
        }
    
    }
    
  3. Java 应用程序 的身份执行您的测试。 结果应该是:

我的环境配置是:

java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

希望这会有所帮助

【讨论】:

    【解决方案2】:

    以下代码最终为我工作。

    package myPackageName;
    
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    
    public class testRunner {
        public static void main(String[] args) {
            Result result = JUnitCore.runClasses(AllTests.class);
            for (Failure failure : result.getFailures()) {
                System.out.println(failure.toString());
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-06
      • 2012-03-01
      • 1970-01-01
      • 2018-04-23
      • 2019-01-29
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      相关资源
      最近更新 更多