0
0
JUnittesting~8 mins

@AfterEach method in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - @AfterEach method
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── App.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── tests/
│               │   └── ExampleTest.java
│               ├── utils/
│               │   └── TestUtils.java
│               └── config/
│                   └── TestConfig.java
└── pom.xml
    
Test Framework Layers
  • Test Classes: Contain test methods annotated with @Test, and lifecycle methods like @BeforeEach and @AfterEach to setup and cleanup before and after each test.
  • Page Objects / Helpers: Encapsulate UI or API interactions to keep tests clean and readable.
  • Utilities: Helper methods for common tasks like data generation or assertions.
  • Configuration: Manage environment settings, test parameters, and credentials.
  • Test Runner: JUnit platform that executes tests and lifecycle methods in order.
Configuration Patterns

Use src/test/resources or Java config classes to store environment variables and credentials.

Example: Use @BeforeEach to setup test data or open connections, and @AfterEach to clean up resources like closing connections or resetting states.

Use Maven profiles or system properties to switch environments (dev, test, prod).

Test Reporting and CI/CD Integration
  • JUnit generates XML reports by default, which CI tools like Jenkins or GitHub Actions can consume.
  • Use plugins like Surefire or Gradle Test Logger for enhanced reports.
  • Integrate lifecycle methods like @AfterEach to capture screenshots or logs on test failure.
  • CI pipelines run tests automatically on code push, reporting pass/fail status.
Best Practices for @AfterEach Method
  • Always clean up resources (files, connections, mocks) in @AfterEach to avoid side effects between tests.
  • Keep @AfterEach methods fast and reliable to not slow down test runs.
  • Use @AfterEach instead of @AfterAll when cleanup must happen after every test, not just once.
  • Handle exceptions inside @AfterEach to ensure cleanup runs even if test fails.
  • Do not put assertions inside @AfterEach; keep it for cleanup only.
Self Check

Where in this framework structure would you add a method annotated with @AfterEach to close a database connection after each test?

Key Result
Use @AfterEach methods in test classes to clean up resources after every test method runs.