java 命令行test使用,使用命令行从JUnit类运行单个测试

I am trying to find an approach that will allow me to run a single test from a JUnit class using only command-line and java.

I can run the whole set of tests from the class using the following:

java -cp .... org.junit.runner.JUnitCore org.package.classname

What I really want to do is something like this:

java -cp .... org.junit.runner.JUnitCore org.package.classname.method

or:

java -cp .... org.junit.runner.JUnitCore org.package.classname#method

I noticed that there might be ways to do this using JUnit annotations, but I would prefer to not modify the source of my test classes by hand (attempting to automate this). I did also see that Maven might have a way to do this, but if possible I would like to avoid depending on Maven.

So I am wondering if there is any way to do this?

Key points I'm looking for:

Ability to run a single test from a JUnit test class

Command Line (using JUnit)

Avoid modifying the test source

Avoid using additional tools

解决方案

You can make a custom, barebones JUnit runner fairly easily. Here's one that will run a single test method in the form com.package.TestClass#methodName:

import org.junit.runner.JUnitCore;

import org.junit.runner.Request;

import org.junit.runner.Result;

public class SingleJUnitTestRunner {

public static void main(String... args) throws ClassNotFoundException {

String[] classAndMethod = args[0].split("#");

Request request = Request.method(Class.forName(classAndMethod[0]),

classAndMethod[1]);

Result result = new JUnitCore().run(request);

System.exit(result.wasSuccessful() ? 0 : 1);

}

}

You can invoke it like this:

> java -cp path/to/testclasses:path/to/junit-4.8.2.jar SingleJUnitTestRunner

com.mycompany.product.MyTest#testB

After a quick look in the JUnit source I came to the same conclusion as you that JUnit does not support this natively. This has never been a problem for me since IDEs all have custom JUnit integrations that allow you to run the test method under the cursor, among other actions. I have never run JUnit tests from the command line directly; I have always let either the IDE or build tool (Ant, Maven) take care of it. Especially since the default CLI entry point (JUnitCore) doesn't produce any result output other than a non-zero exit code on test failure(s).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值