JUnit每次测试会重初始化类与变量,为何仍推荐用@Before初始化类变量?
@Before Methods Even Though JUnit Reinitializes the Class per Test? Great question—this is a common point of confusion, so let’s break down the key reasons why using @Before is still the best practice for test setup:
Eliminate redundant code
If you duplicate initialization logic in every test method, you’ll end up with messy, hard-to-maintain code. Putting setup in a single@Beforemethod means you write the logic once, and every test runs it automatically. If you need to adjust the initialization later (like changing a default value or adding a setup step), you only update one place instead of every test.Guarantee consistent test state
Manual initialization in each test is prone to human error: you might forget to set a critical variable, use the wrong default, or skip a setup step entirely.@Beforeensures every test starts with exactly the same known state, making your test results reliable and reproducible—no more flaky tests caused by inconsistent setup.Cleanly handle complex setup
Not all initialization is as simple as assigning a value. You might need to create mock objects, load test data, establish database connections, or perform multi-step configuration. Encapsulating this work in@Beforekeeps your test methods focused on the actual test logic (assertions, action triggers) instead of cluttering them with setup details.Improve code readability
Test methods should be easy to scan and understand at a glance. When you move setup to@Before, anyone reading your code can immediately separate "preparation work" from "test execution." This clear separation makes debugging and collaborating on tests much easier.Fix static variable contamination
A quick clarification: JUnit creates a new instance of your test class for each test, so instance variables are reinitialized by default. But static class variables are shared across all test instances. If you have static variables that need resetting between tests,@Beforelets you reset them to a known state every time, preventing cross-test interference that could break your results.
内容的提问来源于stack exchange,提问作者user3813133

