Is it possible to use different @Before @After for

2019-06-16 07:14发布

问题:

I am new to Java & JUnit and came across different Fixtures. I searched a lot on net but I couldn't get the answer.

Is it possible to use different @Before @After for different test case in JUnit? For eg: I have the following TC then is it possible to use different @Before for test & different @Before for test1

 import static org.junit.Assert.assertEquals;

 import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Ignore;
 import org.junit.Test;

 public class testJUnit {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    System.out.println("Before Class");
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
    System.out.println("Tear Down After Class");
}

@Before
public void setUp() throws Exception {
    System.out.println("Setup");
}

@After
public void tearDown() throws Exception {
    System.out.println("Tear Down");
}

@Test
public void test() {
    int a = 1;
    assertEquals("Testing...", 1, a);
}

@Ignore
@Test
public void test1() {
    int a = 156;
    assertEquals("Testing...", 156, a);
}

}

Can anyone guide me?

回答1:

If you want different Before and After, put each test in its proper public class

Method that is marked with @Before will be executed before executing every test in the class.



回答2:

Just write a private method that you call in the test.