0
0
JUnittesting~8 mins

Mocking void methods in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Mocking void methods
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── Service.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── ServiceTest.java
│               └── mocks/
│                   └── MockHelpers.java
├── build.gradle
└── settings.gradle
    
Test Framework Layers
  • Test Classes: Contain JUnit test methods using Mockito to mock void methods.
  • Mocks and Stubs: Use Mockito to create mocks and stub void methods with doNothing(), doThrow().
  • Utilities: Helper classes for common mocking setups or reusable mock behaviors.
  • Application Code: Actual classes with void methods to be tested.
  • Configuration: JUnit and Mockito setup, test runners, and dependencies.
Configuration Patterns
  • Use @ExtendWith(MockitoExtension.class) to enable Mockito annotations.
  • Configure mocks with @Mock and inject with @InjectMocks.
  • Use doNothing().when(mock).voidMethod() to mock void methods that do not throw exceptions.
  • Use doThrow(new Exception()).when(mock).voidMethod() to simulate exceptions from void methods.
  • Keep test data and environment setup simple and isolated per test method.
Test Reporting and CI/CD Integration
  • Use JUnit reports generated by build tools (Gradle/Maven) for test results.
  • Integrate with CI tools like Jenkins, GitHub Actions to run tests on each commit.
  • Fail build if any test including void method mocks fail.
  • Use coverage tools (JaCoCo) to ensure void methods are exercised in tests.
Best Practices
  1. Use doNothing() to mock void methods that should not perform any action during tests.
  2. Use doThrow() to simulate exceptions from void methods and test error handling.
  3. Keep mocks focused and avoid over-mocking; only mock external dependencies.
  4. Use descriptive test method names to clarify what void method behavior is tested.
  5. Reset mocks between tests to avoid state leakage.
Self Check

Where in this folder structure would you add a new mock helper method to simulate throwing an exception from a void method?

Key Result
Use Mockito's doNothing() and doThrow() in JUnit tests to mock void methods effectively.