简体   繁体   中英

How can I run (or change the order of) specific test-methods in a JUnit test class?

I am fairly new to Java. I have constructed a single JUnit test class and inside this file are a number of test methods. When I run this class (in NetBeans) it runs each test method in the class in order.

Question 1: How can I run only a specific sub-set of the test methods in this class? (Potential answer: Write @Ignore above @Test for the tests I wish to ignore. However, if I want to indicate which test methods I want to run rather than those I want to ignore, is there a more convenient way of doing this?)

Question 2: Is there an easy way to change the order in which the various test methods are run?

Thanks.

You should read about TestSuite 's. They allow to group & order your unit test methods. Here's an extract form this article

"JUnit test classes can be rolled up to run in a specific order by creating a Test Suite.

EDIT: Here's an example showing how simple it is:

 public static Test suite() { 
      TestSuite suite = new TestSuite("Sample Tests");

      suite.addTest(new SampleTest("testmethod3"));
      suite.addTest(new SampleTest("testmethod5"));

      return suite; 
 }

This answer tells you how to do it. Randomizing the order the tests run is a good idea!

Like the comment from dom farr states, each unit test should be able to run in isolation. There should be no residuals and no given requirements after or before a test run. All your unit tests should pass run in any order, or any subset.

It's not a terrible idea to have or generate a map of Test Case --> List of Test and then randomly execute all the tests.

There are a number of approaches to this, but it depends on your specific needs. For example, you could split up each of your test methods into separate test classes, and then arrange them in different test suites (which would allow for overlap of methods in the suites if desired). Or, a simpler solution would be to make your test methods normal class methods with one test method in your class that calls them in your specific order. Do you want them to be dynamcially called?

I've not been using Java that long either, but as far as I've seen there isn't a convenient method of marking methods to execute rather than ignore. Instead I think this could be achieved using the IDE. When I want to do that in Eclipse I can use the junit view to run individual tests by clicking on them. I imagine there is something similar in Netbeans.

I don't know of an easy way to reorder the test execution. Eclipse has a button to rerun tests with the failing tests first, but it sounds like you want something more versatile.

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