Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use different @Before @After for each test case in JUnit?

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?

like image 733
Amrit Avatar asked Oct 23 '13 08:10

Amrit


2 Answers

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.

like image 130
Adel Boutros Avatar answered Nov 08 '22 08:11

Adel Boutros


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

like image 37
blank Avatar answered Nov 08 '22 06:11

blank