0
0
JUnittesting~8 mins

Mocking static methods (Mockito 3.4+) in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Mocking static methods (Mockito 3.4+)
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── UtilityClass.java  (contains static methods)
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── UtilityClassTest.java  (tests mocking static methods)
│               └── OtherServiceTest.java
├── pom.xml  (Maven config with Mockito 3.4+ dependency)
└── README.md
Test Framework Layers
  • Test Classes: Contain JUnit test methods using Mockito to mock static methods.
  • Static Utility Classes: Classes with static methods to be mocked.
  • Mockito Extension Setup: Use @ExtendWith(MockitoExtension.class) and try (MockedStatic<ClassName> mocked = Mockito.mockStatic(ClassName.class)) to mock static methods.
  • Test Utilities: Helper methods for common test setup or data creation.
  • Configuration: Maven or Gradle dependencies specifying Mockito 3.4+ and JUnit 5.
Configuration Patterns
  • Dependencies: Add Mockito 3.4+ and JUnit 5 dependencies in pom.xml or build.gradle.
  • Mockito Inline: Use mockito-inline artifact to enable static mocking.
  • Test Runner: Use JUnit 5 with @ExtendWith(MockitoExtension.class) for integration.
  • Environment: No special environment config needed for static mocking, but keep test isolation.
  • IDE Setup: Ensure IDE supports JUnit 5 and Mockito 3.4+ for running tests smoothly.
Test Reporting and CI/CD Integration
  • JUnit Reports: Use JUnit 5 standard XML reports for test results.
  • CI Integration: Configure CI tools (Jenkins, GitHub Actions) to run tests and collect reports.
  • Mockito Logs: Enable logging if needed to debug static mocks.
  • Fail Fast: Configure CI to fail build on test failures to ensure static mocks behave correctly.
  • Code Coverage: Use tools like JaCoCo to measure coverage including static method calls.
Best Practices
  1. Limit Static Mocking: Use static mocking only when necessary, as it can make tests harder to read.
  2. Use Try-With-Resources: Always mock static methods inside a try-with-resources block to avoid side effects.
  3. Keep Tests Isolated: Reset static mocks after each test to prevent interference.
  4. Prefer Dependency Injection: When possible, avoid static methods by using instance methods and DI for easier testing.
  5. Clear Naming: Name test methods clearly to indicate when static methods are mocked.
Self Check

Where in this folder structure would you add a new test class to mock static methods of a new utility class named FileHelper?

Key Result
Use Mockito 3.4+ with try-with-resources to safely mock static methods in JUnit 5 tests.