JUnit: @Before only for some test methods?

孤街浪徒 提交于 2019-12-18 12:45:13

问题


I have some common set up code that I've factored out to a method marked with @Before. However, it is not necessary for all this code to run for every single test. Is there a way to mark it so the @Before method only runs before certain tests?


回答1:


Just move out the tests that don't need the setup code into a separate test class. If you have some other code common to the tests that would be helpful to keep, move that out into a helper class.




回答2:


Or use TestNG. It gives you finer grained control over tests.




回答3:


It is possible to achieve also via Assume from JUnit. And then you can check the method name for which you want to process @Before.

public class MyTest {
     @Rule
     public TestName testName = new TestName();

     @Before
     public void setUp() {
       assumeTrue(testName.getMethodName().equals("myMethodName"));
       // setup follows
     }
}

Check the topic for more insights about @Rule.




回答4:


@Nested + @ForEach

Totally agree with the point of moving the related code to an inner class. So here what I have done.

  1. Create an inner class inside your test class
  2. Annotate the inner class with @Nested
  3. Move all the test methods you want to use in the inner class
  4. Write the init code inside the inner class and annotate it with @ForEach

Here is the code:

class Testing {

    @Test
    public void testextmethod1() {

      System.out.println("test ext method 1");

    }

    @Nested
    class TestNest{

       @BeforeEach
       public void init() {
          System.out.println("Init");
       }

       @Test
       public void testmethod1() {
          System.out.println("This is method 1");
       }

       @Test
       public void testmethod2() {
          System.out.println("This is method 2");
       }

       @Test
       public void testmethod3() {
          System.out.println("This is method 3");
       }

     }

     @Test
     public void testextmethod2() {

         System.out.println("test ext method 2");

     }

}

Here is the output

test ext method 1
test ext method 2
Init
This is method 1
Init
This is method 2
Init
This is method 3

Note: I am not sure if this is supported in Junit4. I am doing this in JUnit5




回答5:


Not sure about @Before, but I recently came up with a strategy for @After block to run selectively. The implementation was straight forward. I have some flags set to default values as part of the test class. They are reset to default values in @Before class. In the class I need to do things specific to a flag, I set those flags & in @After I check for flag values to do the respective jobs.



来源:https://stackoverflow.com/questions/1548462/junit-before-only-for-some-test-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!