0
0
JUnittesting~8 mins

when().thenThrow() for exceptions in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - when().thenThrow() for exceptions
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── Service.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── ServiceTest.java
│               └── mocks/
│                   └── MockedDependency.java
├── pom.xml
└── README.md

This structure follows Maven conventions for Java projects using JUnit.

Test Framework Layers
  • Test Layer: Contains JUnit test classes like ServiceTest.java where when().thenThrow() is used to simulate exceptions from mocked dependencies.
  • Mock Layer: Uses Mockito to create mocks and define behavior such as throwing exceptions.
  • Service Layer: The actual application code under test, e.g., Service.java.
  • Utilities: Helper classes for common test utilities or custom matchers.
  • Configuration: Test configuration files and setup for JUnit and Mockito.
Configuration Patterns
  • Mockito Setup: Use @ExtendWith(MockitoExtension.class) to enable Mockito annotations.
  • Mock Initialization: Use @Mock for dependencies and @InjectMocks for the class under test.
  • Exception Simulation: Use when(mock.method()).thenThrow(new ExceptionType()) to simulate exceptions.
  • Environment: Use Maven profiles or system properties to manage test environments if needed.
  • JUnit Version: Use JUnit 5 (Jupiter) for modern features and better integration.
Test Reporting and CI/CD Integration
  • JUnit Reports: Automatically generated XML reports by Maven Surefire plugin.
  • CI/CD: Integrate with Jenkins, GitHub Actions, or GitLab CI to run tests on each commit.
  • Failure Details: Reports show stack traces when thenThrow() causes exceptions, helping diagnose test failures.
  • Code Coverage: Use tools like JaCoCo to measure coverage of exception handling paths.
Best Practices
  1. Use Specific Exceptions: Throw the exact exception type expected to improve test clarity.
  2. Keep Tests Focused: Test one behavior per test method, including exception handling.
  3. Clear Naming: Name tests to describe the exception scenario, e.g., shouldThrowWhenDependencyFails().
  4. Use Mockito Extension: Avoid manual mock initialization by using @ExtendWith(MockitoExtension.class).
  5. Assert Exception: Use assertThrows() in JUnit 5 to verify exceptions are thrown as expected.
Self Check

Where in this folder structure would you add a new mock class to simulate a dependency that throws an exception?

Key Result
Use Mockito's when().thenThrow() in JUnit tests to simulate exceptions from mocked dependencies for robust error handling verification.