1

Is it possible to place the setup/teardown methods using JUnit framework in a single class (which would be my baseclass) so on test runs they methods are always called first/last? it would be in a similar way to which nunit tests can be structured

currently the only way I can get my tests to kick off is if I have the setup/teardown methods within the same class as my tests are (which is something I wan't to avoid, to keep my test classes tidy)

example I would hope to set up;

public class baseclass
{
    @Before
    public void setUp
    {}

    @After
    public void tearDown
    {}
}

public class tests
{
    @Test
    public void test1
    {
        // test content here
    }
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
jim7
  • 213
  • 1
  • 2
  • 6

2 Answers2

1

Run this test and see the sequence of events

class Test1 {
    @Before
    public void setUp1() {
        System.out.println("setUp1");
    }
}

public class Test2 extends Test1 {
    @Before
    public void setUp2() {
        System.out.println("setUp2");
    }

    @Test
    public void test() {
        System.out.println("test");
    }

}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Yes, as long as your test class extend your baseclass.
For instance:

  • Suite

    @RunWith(Suite.class)
    @SuiteClasses(Tests.class)
    public class AllTests {
    
    }
    
  • BaseClass

    public class BaseClass {
    
        @BeforeClass 
        public static void beforeAll() { 
        }
    
        @Before
        public void setUp() { 
        }
    
        @After
        public void tearDown {
        }
    
        @AfterClass 
        public static void afterAll() { 
        }
    }
    
  • Tests

    public class Test extends BaseClass {
    
        @Test
        public void test1() {
        }
    
        @Test
        public void test2() {
        }
    
    }
    
Albert
  • 1,156
  • 1
  • 15
  • 27
  • This is perfect, thanks Albert! New to Java so figuring out inheritance was confusing me :) – jim7 Mar 06 '15 at 10:49