0
0
JUnittesting~8 mins

@BeforeEach method in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - @BeforeEach method
Folder Structure
src/
└── test/
    └── java/
        └── com/
            └── example/
                ├── pages/
                │   └── LoginPage.java
                ├── tests/
                │   └── LoginTest.java
                ├── utils/
                │   └── TestUtils.java
                └── config/
                    └── TestConfig.java
Test Framework Layers
  • Config Layer: Holds configuration classes like TestConfig.java for environment and browser setup.
  • Page Object Layer: Contains page classes like LoginPage.java that model UI elements and actions.
  • Test Layer: Contains test classes like LoginTest.java where test methods and lifecycle methods like @BeforeEach are defined.
  • Utility Layer: Helper classes such as TestUtils.java for reusable methods.

The @BeforeEach method runs before every test method in the test class to set up common preconditions.

Configuration Patterns
  • Environment Setup: Use TestConfig.java to load environment variables or properties files for URLs, credentials, and browser types.
  • Browser Setup: Initialize WebDriver in a setup method annotated with @BeforeEach to ensure a fresh browser instance for each test.
  • Credentials: Store securely in environment variables or encrypted files, accessed via config classes.
  • Example:
      
      @BeforeEach
      void setUp() {
          driver = new ChromeDriver();
          driver.get(config.getBaseUrl());
      }
Test Reporting and CI/CD Integration
  • Use JUnit's built-in reporting or integrate with tools like Surefire or Allure for detailed test reports.
  • Configure CI/CD pipelines (e.g., Jenkins, GitHub Actions) to run tests automatically on code push.
  • Ensure @BeforeEach methods properly initialize test state so tests run reliably in CI environments.
  • Reports show which tests passed or failed, including setup failures from @BeforeEach if any.
Best Practices for @BeforeEach Method
  1. Keep @BeforeEach methods focused on setup needed for every test to avoid duplication.
  2. Do not put assertions or test logic inside @BeforeEach; it should only prepare the test environment.
  3. Use @BeforeEach to create fresh objects or reset states to keep tests independent and repeatable.
  4. Handle exceptions in @BeforeEach carefully to avoid hiding setup failures.
  5. Complement @BeforeEach with @AfterEach to clean up resources like closing browsers.
Self Check

Where in this folder structure would you add a new @BeforeEach method to initialize the WebDriver before each test?

Key Result
Use @BeforeEach in test classes to set up fresh test state before every test method.