Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

testing - How do I run JUnit tests from inside my java application?

Is it possible to run JUnit tests from inside my java application?

Are there test frameworks I can use (such as JUnit.jar?), or am I force to find the test files, invoke the methods and track the exceptions myself?

The reason why I am asking is my application requires a lot of work to start launch (lots of dependencies and configurations, etc) and using an external testing tool (like JUnit Ant task) would require a lot of work to set up.

It is easier to start the application and then inside the application run my tests.

Is there an easy test framework that runs tests and output results from inside a java application or am I forced to write my own framework?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can. I was doing it couple of times to run diagnostic/smoke tests in production systems. This is a snippet of key part of the code invoking JUnit:

JUnitCore junit = new JUnitCore();
Result result = junit.run(testClasses);

DON'T use JUnit.main inside your application, it invokes System.exit after tests are finished and thus it may stop JVM process.

You may want to capture JUnit's "regular" console output (the dots and simple report). This can be easily done by registering TextListener (this class provides this simple report).

Please also be aware of several complications using this kind of method:

  1. Testing of any "test framework", including so small one, although is quite simple may be confusing. For example if you want to test if your "test framework" return failure result when one of the tests fails you could (should?) create sample JUnit test that always fails and execute that test with the "test framework". In this case failing test case is actually test data and shouldn't be executed as "normal" JUnit. For an example of such tests you can refer to JUnit's internal test cases.

  2. If you want to prepare / display your custom report you should rather register your own RunListener, because Result returned by JUnit doesn't contain (directly) information about passed tests and test method (it is only "hardcoded" as a part of test Description).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...