Difference between setUp() and setUpBeforeClass()
When unit testing with JUnit, there are two similar meth开发者_如何学运维ods, 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 {
}
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()
Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.
Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).
"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.
setUpBeforeClass is run before any method execution right after the constructor (run only once)
setUp is run before each method execution
tearDown is run after each method execution
tearDownAfterClass is run after all other method executions, is the last method to be executed. (run only once deconstructor)
From the Javadoc:
Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a
public static void
no-arg method with@BeforeClass
causes it to be run once before any of the test methods in the class. The@BeforeClass
methods of superclasses will be run before those the current class.
精彩评论