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
From the course: Complete Guide To Java Testing with JUnit 5 & 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
-
-
-
-
-
-
-
-
(Locked)
Set up Mockito1m 40s
-
(Locked)
Mocking basics3m 17s
-
(Locked)
How to mock an object in Java2m 32s
-
(Locked)
Stub a method with Mockito3m
-
(Locked)
Verify an interaction with Mockito3m 49s
-
(Locked)
Verify arguments with argument matchers3m 13s
-
(Locked)
Verify arguments with argument captors5m 7s
-
(Locked)
Challenge: Test a library management system1m 32s
-
(Locked)
Solution: Test a library management system7m 6s
-
(Locked)
-
-
-