Junit 4 is not picking up my @Before & @After methods

336 views Asked by At

My @Before and @After methods are not picking up by Junit

public class TestSetup {

    @Before
    public void browserSetUp() {
     // code for before a test
    }


    @After
    public void tearDown() {
      // code after a test
    }
}

In Another class file I have defined

public class Steps{

@Step
public void step1() {
//Code for step 1

}

@Step
public void step2() {
// Code for Step 2

}

}

Finally I am calling those steps for my Test

public class Tests {

Steps step = new Steps();   

@Test
public void TC_0001 {
step.step1();
step.step2();

}


}

@Test method are getting executed but the @Before and @After methods are not executing before @Test method.Do I have to include the TestSetup class to somewhere ? Any help will be appreciated.

**Thought 1: As I am using Maven to build, my @Before @After methods resides in a class (TestSetup.java - Name is not ending with *Test.java and may be thats why Maven is not picking it up for execution?

2

There are 2 answers

1
Bruno On

@Before and @After are used in the same class that your test is running. You should put this methods on your test class:

public class Tests {

    Steps step = new Steps();   

    @Test
    public void TC_0001 {
        step.step1();
        step.step2();
    }

    @Before
    public void browserSetUp() {
        // code for before a test
    }


    @After
    public void tearDown() {
        // code after a test
    }

}
1
Gerald Mücke On

@Before and @After are only executed before a single test, if they are defined in the same class as the @Test. In your case, the TestSetup class contains no tests. So either you let Test inherit from TestSetup or you create a rule that is executed "around" your test.