简体   繁体   中英

How do I make a JUnit Test Suite that runs tests conditionally based on a list of Test Classes?

I need to make a JUnit test suite that runs tests based on an input file provided by the user. IE if the user says that 5 of 10 tests should be run those 5 tests will be run and nothing more. Is there a way to take a list of Classes containing test my cases and run those only? I tried to use a for loop for this like so

for (Class a: classes)
    JUnitCore.runClasses(a);

but i got this error

Exception in thread "main" java.lang.NoClassDefFoundError: org/junit/runner/JUnitCore
at TestRunner.main(TestRunner.java:56)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.JUnitCore
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more

There are two alternatives.

Use Categories runner

It allows you to "tag" tests and construct test suite by tags. You can look in documentation: https://github.com/junit-team/junit/wiki/Categories

Pros:

  • easier to setup
  • only tests marked with category will run

Cons:

  • fixed test suites, to change them you have to change test code

Use Rule

Write your on test rule and in this rule ignore (by throwing AssumptionViolatedException) all tests not in your list. Documentation is here:

https://github.com/junit-team/junit/wiki/Rules

Look at TestWatcher rule, it has information about test class name and method name in Description object passed into its methods.

Pros:

  • very flexible test suites

Cons:

  • harder to setup
  • all tests are run, but those not in list are ignored ie some @Before and @After methods may fire even when no tests are run
  • all your tests must use this rule, test not using rule will run as usual

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM