0
0
JUnittesting~8 mins

assertThrows for exceptions in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - assertThrows for exceptions
Folder Structure
src/
└── test/
    └── java/
        └── com/
            └── example/
                ├── pages/
                │   └── LoginPage.java
                ├── tests/
                │   └── LoginTests.java
                ├── utils/
                │   └── TestUtils.java
                └── config/
                    └── TestConfig.java
Test Framework Layers
  • Test Classes: Contain test methods using assertThrows to verify exceptions.
  • Page Objects: Encapsulate UI elements and actions (e.g., LoginPage).
  • Utilities: Helper methods for common tasks like data setup or exception message validation.
  • Configuration: Manage environment settings, credentials, and test parameters.
  • Driver Layer: Manages WebDriver setup and teardown for browser automation.
Configuration Patterns
  • Environment Properties: Use TestConfig.java or application.properties to define URLs, credentials, and environment-specific settings.
  • Browser Setup: Configure browser type and options in setup methods or config files.
  • Exception Handling: Centralize expected exception types and messages for reuse in tests.
  • JUnit Annotations: Use @BeforeEach and @AfterEach for setup and cleanup.
Test Reporting and CI/CD Integration
  • Use JUnit's built-in reporting for test pass/fail results including exception assertions.
  • Integrate with CI tools like Jenkins or GitHub Actions to run tests automatically on code changes.
  • Generate HTML or XML reports using plugins like Surefire or Allure for detailed test results.
  • Fail tests clearly when assertThrows does not catch the expected exception.
Best Practices
  1. Use assertThrows to clearly specify the expected exception type and test only the code that should throw it.
  2. Keep exception messages simple and consistent to make assertions reliable.
  3. Write one assertion per test method to keep tests focused and easy to understand.
  4. Use descriptive test method names that explain what exception is expected and why.
  5. Centralize exception-related constants or helper methods in utility classes for reuse.
Self Check

Where in this folder structure would you add a new test method that verifies a NullPointerException is thrown when a required input is missing?

Key Result
Use assertThrows in test classes to verify expected exceptions clearly and reliably.