Using Annotations
Learn about @Before, @After, @BeforeClass, @AfterClass in unit tests.
@Before
method
Methods annotated with the @Before
annotation are run before each test.
As we add more tests for a given set of related behaviors, it becomes clear that many of them have the same initialization needs. We’ll want to take advantage of the @Before
method to help ensure that our tests don’t become a maintenance nightmare of redundant code.
It’s important to understand the order in which JUnit executes
@Before
and@Test
methods.
The AssertTest
class below in which the @Before
method resides has two tests, hasPositiveBalance
and depositIncreasesBalance
.
Press + to interact
// ...public class AssertTest {//...private Account account;@Beforepublic void createAccount() {account = new Account("an account name");}@Testpublic void hasPositiveBalance() {//...}@Testpublic void depositIncreasesBalance() {//...}}
Below is the flow of execution when JUnit interacts with the test class:
In other words, the @Before
method executes ...
Access this course and 1400+ top-rated courses and projects.