0
0
JUnittesting~8 mins

assertThrows usage in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - assertThrows usage
Folder Structure
src/
└── test/
    └── java/
        └── com/
            └── example/
                ├── tests/
                │   └── CalculatorTest.java
                ├── utils/
                │   └── TestHelpers.java
                └── exceptions/
                    └── CustomException.java
Test Framework Layers
  • Test Classes: Contain test methods using assertThrows to verify exceptions, e.g., CalculatorTest.java.
  • Exception Classes: Custom exceptions to be tested, e.g., CustomException.java.
  • Utility Classes: Helper methods for tests, e.g., input validation or setup.
  • Configuration: Test settings like environment or test data.
Configuration Patterns
  • Use src/test/resources for test data and environment properties.
  • Configure JUnit platform via pom.xml or build.gradle for running tests.
  • Use system properties or environment variables to switch test environments.
  • Keep exception messages or expected error codes configurable if needed.
Test Reporting and CI/CD Integration
  • JUnit generates XML reports by default, compatible with CI tools like Jenkins, GitHub Actions.
  • Use plugins like Surefire or Gradle Test Logger for enhanced console output.
  • Integrate with CI pipelines to run tests on each commit and fail builds on assertion failures.
  • Reports clearly show which assertThrows tests passed or failed, including exception details.
Best Practices for assertThrows Usage
  • Use assertThrows to verify that the exact expected exception is thrown.
  • Check exception message or properties if needed by capturing the thrown exception.
  • Keep tests focused: one assertion per test method for clarity.
  • Use descriptive test method names to indicate the exception scenario.
  • Avoid catching exceptions manually in tests; rely on assertThrows for cleaner code.
Self Check

Where in this folder structure would you add a new test class to verify that a NullPointerException is thrown when a null input is passed?

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