From the course: Complete Guide To Java Testing with JUnit 5 & Mockito

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Stub a method with Mockito

Stub a method with Mockito

- [Instructor] When writing unit tests, it's essential to test the functionality of a class in isolation. However, many classes depend on other classes, which can make testing challenging. Stubbing allows you to replace these dependencies with mock objects that return to controlled responses, allowing you to focus solely on the behavior of the class under test. In other words, with stubbing, we can provide a predefined response to a method call on a mock object. Let's take a look at an example. In the findUserById test, we stubbed the findById method to return a fake user. The when method in Mockito is a key component in stubbing. It allows us to specify the behavior of a mock object when a particular method is called with certain arguments. By using when, we can control the output of methods on a mock object to suit the needs of a test case. In this example, our test required at least one user in the repository. So we mocked a user with the findById method, returning a predefined…

Contents