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

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