Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

When unit testing with JUnit, there are two similar methods, setUp() and setUpBeforeClass(). What is the difference between these methods? Also, what is the difference between tearDown() and tearDownAfterClass()?

Here are the signatures:

@BeforeClass

public static void setUpBeforeClass() throws Exception {

}

@AfterClass

public static void tearDownAfterClass() throws Exception {

}

@Before

public void setUp() throws Exception {

}

@After

public void tearDown() throws Exception {

}

1 Answer

0 votes
by (46k points)

The @BeforeClass and @AfterClass annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static.

The @Before and @After methods will be run before and after every test case, so will probably be run multiple times during a test run.

So let's assume you had three tests in your class, the order of method calls would be:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)

    setUp()

    test1()

    tearDown()

  (Test class second instance constructed and the following methods called on it)

    setUp()

    test2()

    tearDown()

  (Test class third instance constructed and the following methods called on it)

    setUp()

    test3()

    tearDown()

tearDownAfterClass()

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...