Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

junit

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.

like image 354
kmccoy Avatar asked Jan 10 '11 17:01

kmccoy


2 Answers

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; 
 }
like image 191
Lukasz Avatar answered Oct 12 '22 18:10

Lukasz


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.

like image 35
Instantsoup Avatar answered Oct 12 '22 18:10

Instantsoup