From the course: Complete Guide To Java Testing with JUnit 5 & Mockito
Unlock the full course today
Join today to access over 24,900 courses taught by industry experts.
How to mock an object in Java
From the course: Complete Guide To Java Testing with JUnit 5 & Mockito
How to mock an object in Java
- [Instructor] Mockito offers two primary ways to create mock objects, the traditional mock method and the concise mock annotation. Both approaches achieve the same goal, creating simulated objects for unit testing, but they differ in how they're implemented. In the last video, we used the mock method to create the user repository mock object. We can simplify this by creating a user repository mock field, and using the mock annotation. (instructor typing) To use this annotation with JUnit, we'll use the Mockito extension. (instructor typing) With this extension, our mock will automatically be set up behind the scenes. Mockito will instantiate our mock object and inject it into our test class. This injection allows us to use this mock within our test methods without any additional setup. Mockito will also manage the lifecycle of the mock objects, ensuring they're reset properly between test methods. This prevents cross contamination between tests. Let's run our method. And it passes…
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)
-
-
-