Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run a junit test for a single method only

Can you run a test for a single method only, not a whole class? Ideally from the command line.

e.g. for a class:

public class TestClass extends Unittest {
  @Test
  public void test1_shouldbeRun() {

  }

  @Test
  public void test2_shouldNotBeRun() {

  } 
}

I only want to run the method "test1_shouldBeRun".

like image 519
forste Avatar asked Mar 11 '12 10:03

forste


2 Answers

I do not think if that is natively supported by JUnit. However, you have some alternatives:

  1. Put the required tests in different classes so you can run them separately
  2. Maybe using the @Ignore annotation helps you.
  3. If you're using some IDE, it may support this approach. For instance in Eclipse, unfold the test class in the Package Explorer, select the method you want to run, and click Run As -> JUnit test.
  4. Here's a quite extensive tutorial on how to create a custom TestSuit and an Ant task that can make this for you.
  5. UPDATE In this thread the guys say that "The old junit.textui.TestRunner utility provides a way to run a single method on the command-line, via the runSingleMethod(), but it doesn't support JUnit4 annotated test classes."
like image 104
rlegendi Avatar answered Sep 19 '22 17:09

rlegendi


It is possible when you use the surefire plugin [1]:

mvn -Dtest=TestClass#test1_shouldbeRun test

[1] http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html

like image 37
fabb Avatar answered Sep 17 '22 17:09

fabb