0
0
JUnittesting~8 mins

when().thenReturn() stubbing in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - when().thenReturn() stubbing
Folder Structure
src/
└── test/
    └── java/
        └── com/
            └── example/
                ├── pages/
                │   └── LoginPage.java
                ├── tests/
                │   └── LoginServiceTest.java
                ├── utils/
                │   └── TestUtils.java
                └── mocks/
                    └── UserRepositoryMock.java
    

This structure separates page objects, tests, utilities, and mocks for clear organization.

Test Framework Layers
  • Mocks Layer: Contains mock objects created with Mockito to simulate dependencies.
  • Page Objects Layer: Represents UI pages or service classes under test.
  • Test Layer: Contains JUnit test classes that use mocks and verify behavior.
  • Utilities Layer: Helper methods for common test tasks.
  • Configuration Layer: Manages test settings like environment variables and test data.
Configuration Patterns

Use @BeforeEach in JUnit to initialize mocks and set up stubbing with when().thenReturn().

Manage environment-specific data using src/test/resources properties files loaded in tests.

Example snippet for stubbing a method:

import static org.mockito.Mockito.*;

@BeforeEach
void setup() {
    userRepository = mock(UserRepository.class);
    when(userRepository.findUserById(1)).thenReturn(new User(1, "Alice"));
}
    
Test Reporting and CI/CD Integration

JUnit test results are reported in XML and HTML formats by build tools like Maven or Gradle.

Integrate with CI/CD pipelines (e.g., Jenkins, GitHub Actions) to run tests automatically on code changes.

Mockito stubbing failures cause test failures, clearly reported in test reports.

Best Practices
  • Use when().thenReturn() to stub only external dependencies, not the class under test.
  • Keep stubbing simple and focused on expected inputs and outputs.
  • Reset mocks between tests to avoid state leakage.
  • Use descriptive method names in tests to clarify what behavior is stubbed and verified.
  • Prefer explicit stubbing over default returns to catch unexpected calls.
Self Check

Question: In the folder structure shown, where would you add a new mock class for a service called PaymentService to stub its methods using when().thenReturn()?

Key Result
Organize tests with clear layers separating mocks, page objects, tests, utilities, and configuration, using when().thenReturn() to stub dependencies in JUnit tests.