0
0
JUnittesting~8 mins

doReturn and doThrow in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - doReturn and doThrow
Folder Structure
project-root/
├── src/
│   ├── main/
│   │   └── java/
│   │       └── com/example/app/
│   │           └── Service.java
│   └── test/
│       └── java/
│           └── com/example/app/
│               ├── ServiceTest.java
│               └── mocks/
│                   └── MockedDependency.java
├── build.gradle
└── settings.gradle
Test Framework Layers
  • Test Classes: Contain JUnit test methods using Mockito for mocking. Example: ServiceTest.java.
  • Mocking Layer: Uses Mockito to create mocks and stubs. Methods like doReturn() and doThrow() control mock behavior.
  • Application Code: Production classes under src/main/java tested by mocks.
  • Utilities: Helper classes for common test setup or reusable mocks.
  • Configuration: Build files and test runner settings.
Configuration Patterns
  • Mockito Setup: Use @ExtendWith(MockitoExtension.class) to enable Mockito in JUnit 5 tests.
  • Mock Initialization: Use @Mock annotations or Mockito.mock() in setup methods.
  • Environment: Tests run locally or in CI with standard JUnit runner.
  • Behavior Stubbing: Use doReturn(value).when(mock).method() to return values without calling real methods.
  • Exception Stubbing: Use doThrow(exception).when(mock).method() to simulate exceptions.
Test Reporting and CI/CD Integration
  • JUnit generates XML and HTML reports by default, showing passed and failed tests.
  • CI tools (Jenkins, GitHub Actions) run tests on each commit and publish reports.
  • Mockito stubbing failures cause test failures, clearly reported in test output.
  • Use build tools (Gradle/Maven) to configure test tasks and report formats.
Best Practices
  1. Use doReturn() for Stubbing Void or Spy Methods: When stubbing methods on spies or void methods, prefer doReturn() over when().thenReturn() to avoid calling real methods.
  2. Use doThrow() to Simulate Exceptions: Use doThrow() to test how your code handles exceptions from dependencies.
  3. Keep Tests Independent: Each test should set up its own mocks and stubs to avoid side effects.
  4. Clear Naming: Name test methods to clearly describe the behavior being tested with stubbing or exceptions.
  5. Minimal Mocking: Mock only what is necessary to isolate the unit under test.
Self Check

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

Key Result
Use Mockito's doReturn and doThrow in JUnit tests to control mock behavior for return values and exceptions.