11

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?

Amrit
  • 2,295
  • 4
  • 25
  • 42
  • 3
    Maybe your tests shouldn't be in the same class if they don't share the same initialization/context... – LaurentG Oct 23 '13 at 09:01
  • @LaurentG OK. Thanks! BTW, do you know where does `main` is invoked for JUnit as I can't find in it code. Is it done under the junit package? – Amrit Oct 23 '13 at 09:07
  • JUnit tests don't have `main`. They are called directly from the development environment -- something like right-clicking a class or package and selecting "run tests", or somewhere in the menu; depends on the specific IDE. The code you provided is enough, it does not need more methods. What do you use: Eclipse, NetBeans, ...? – Viliam Búr Oct 23 '13 at 10:20
  • @ViliamBúr I am using Eclipse. Thanks again :) – Amrit Oct 23 '13 at 11:30

2 Answers2

12

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.

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
  • 1
    You can use After/Before methods from a superclass too. So if you want more classes per After/Before just put them into an (abstract) super class. As the name says the super Before will run before, the super After after the annotated methods of your subclass. – Franz Ebner Oct 23 '13 at 09:17
7

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

blank
  • 17,852
  • 20
  • 105
  • 159