Stubbing Return Values
Configure mock objects to return specific values or throw exceptions when their methods are invoked.
Intro to Stubbing Mocks
When you create a mock object, it doesn't have any real behavior. Its methods do nothing by default, often returning null, 0, or empty collections.
Stubbing is the process of teaching a mock object how to respond to specific method calls. It's like giving your mock a script to follow!
This allows you to control the exact conditions for your tests, isolating the code you're actually testing.
Making Mocks Return Values
The most common way to stub a mock is using when().thenReturn(). This tells Mockito: "When this specific method is called on the mock, return this predefined value."
when(mock.someMethod()).thenReturn(value);
The value can be any object or primitive type that matches the method's return type.
All lessons in this course
- Stubbing Return Values
- Mockito Argument Matchers
- Spying on Real Objects
- Throwing Exceptions and Consecutive Calls