Question
How can I mock a non-static method of a different class while unit testing Java code?
Answer
Mocking non-static methods in Java unit testing can be challenging, especially when working with frameworks like Mockito. In this guide, we'll explore how to efficiently mock a non-static method from a different class using Mockito, enabling you to isolate the class under test and facilitate effective unit tests.
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;
class MyServiceTest {
@Mock
private ExternalService externalService;
@InjectMocks
private MyService myService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void testMyServiceMethod() {
// Arrange
when(externalService.nonStaticMethod(anyString())).thenReturn("Mocked Response");
// Act
String result = myService.myMethod();
// Assert
assertEquals("Expected Result", result);
}
}
Causes
- Non-static methods are bound to instances and are generally more complex to mock compared to static methods.
- When testing, you often need to isolate the unit of work without merging dependencies.
Solutions
- Use a mocking framework like Mockito which allows you to create mock objects and specify behavior for non-static methods.
- Annotate the test class with @RunWith(MockitoJUnitRunner.class) to enable Mockito annotations if you're using JUnit 4, or @ExtendWith(MockitoExtension.class) for JUnit 5.
- Create mock instances of the class containing the non-static method and define behavior using when() and thenReturn() methods.
Common Mistakes
Mistake: Forgetting to initialize mocks with MockitoAnnotations.openMocks(this) or using the correct runner.
Solution: Ensure you call MockitoAnnotations.openMocks() in the @BeforeEach setup method or use the appropriate test runner.
Mistake: Not verifying that the mocked method was called as expected.
Solution: Always include verification logic in your tests to confirm that the mocked methods were invoked with the right parameters.
Helpers
- Java unit testing
- mock non-static method
- Mockito tutorial
- unit testing best practices
- Java testing frameworks