0
0
JUnittesting~8 mins

@Spy for partial mocking in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - @Spy for partial mocking
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── Service.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── ServiceTest.java  <-- contains @Spy usage
│               └── utils/
│                   └── TestUtils.java
├── pom.xml  <-- Maven build and dependencies
└── README.md
    
Test Framework Layers
  • Test Classes: Contain test methods using JUnit and Mockito annotations like @Spy for partial mocking.
  • Service Layer: Application classes under test, e.g., Service.java.
  • Test Utilities: Helper classes for common test setup or data.
  • Mocking Layer: Uses Mockito to create spies (@Spy) and mocks (@Mock) for controlling behavior.
  • Configuration: Maven pom.xml manages dependencies and test execution.
Configuration Patterns
  • Dependencies: Use pom.xml to include JUnit 5 and Mockito dependencies.
  • Test Runner: Use JUnit 5 with MockitoExtension to enable @Spy annotation processing.
  • Environment: Tests run locally or in CI with standard JVM settings.
  • Credentials: Not typically needed for unit tests with @Spy, but external configs can be loaded if needed.
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <version>5.4.0</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.9.3</version>
  <scope>test</scope>
</dependency>
    
Test Reporting and CI/CD Integration
  • JUnit Reports: Standard XML and HTML reports generated by Maven Surefire plugin.
  • Mockito Logs: Mockito does not produce logs by default; use assertions to verify spy behavior.
  • CI/CD: Integrate tests in pipelines (GitHub Actions, Jenkins) to run on each commit and fail builds on test failures.
  • Coverage: Use JaCoCo plugin to measure code coverage including partially mocked methods.
Best Practices for @Spy Partial Mocking
  • Use @Spy to wrap real objects when you want to call real methods but override some behavior.
  • Always initialize @Spy objects with MockitoExtension or MockitoAnnotations.openMocks() to avoid null pointers.
  • Prefer @Spy on concrete classes, not interfaces, because spies wrap real instances.
  • Keep tests focused: use @Spy only when partial mocking is necessary to avoid overcomplicating tests.
  • Verify interactions on spies to ensure correct method calls and side effects.
Self Check

Where in this folder structure would you add a new spy object for a helper class used in ServiceTest.java?

Key Result
Use @Spy in JUnit tests to partially mock real objects, enabling selective method overriding while preserving original behavior.