0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · 课时

使用 Mockito 创建模拟对象

使用 Mockito 为依赖项创建模拟对象,将待测试单元与其协作者隔离。

使用 Mockito 创建模拟对象 是 CoddyKit 上的免费 Testing Mastery: JUnit, Mockito & Integration Tests 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Testing Mastery: JUnit, Mockito & Integration Tests 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Mockito Mocks

In the previous lesson, we learned about the concept of a mock object. Mocks are special test doubles that let us control the behavior of dependencies.

Now, we'll dive into Mockito, a popular Java mocking framework, to see how easy it is to create these powerful tools for your tests.

Why Create Mocks?

Creating mocks is crucial for effective unit testing:

  • Isolation: Mocks allow you to test a single unit of code in isolation, without worrying about its real dependencies.
  • Control: You can program mocks to behave exactly as needed for your test scenario, simulating various outcomes.
  • Speed: Mocks avoid slow operations like database calls or network requests, making your tests run much faster.

The `Mockito.mock()` Method

The simplest way to create a mock object in Mockito is by using the Mockito.mock() static method. You pass it the Class or Interface you want to mock.

It returns a new mock instance that looks and acts like the real object, but without its actual implementation logic.

Basic Mock Creation Example

Let's create a mock for a simple EmailService interface. Run the code to see how a mock object is created.

import org.mockito.Mockito;

interface EmailService {
  void sendEmail(String to, String subject, String body);
  String getServiceStatus();
}

public class Main {
  public static void main(String[] args) {
    EmailService mockEmailService = Mockito.mock(EmailService.class);
    System.out.println("Mock created: " + mockEmailService.getClass().getName());
  }
}

Understanding Default Mock Behavior

What happens if you call a method on a mock without telling it what to do?

  • Objects: Methods returning objects will return null.
  • Primitives: Methods returning primitive types (like int, boolean) will return their default values (0, false).
  • Collections: Methods returning collections will return empty collections.
  • Void: Methods returning void do nothing.

Default Behavior in Action

Let's call a method on our mockEmailService without any configuration. Observe the default return value.

import org.mockito.Mockito;

interface EmailService {
  void sendEmail(String to, String subject, String body);
  String getServiceStatus();
}

public class Main {
  public static void main(String[] args) {
    EmailService mockEmailService = Mockito.mock(EmailService.class);
    
    // Calling a method that returns an object
    String status = mockEmailService.getServiceStatus();
    System.out.println("Default status: " + status);
    
    // Calling a void method (does nothing by default)
    mockEmailService.sendEmail("test@example.com", "Hi", "Hello");
    System.out.println("Void method called (no output)");
  }
}

Creating Mocks with `@Mock`

While Mockito.mock() works, for tests, Mockito offers a more convenient way using the @Mock annotation.

You simply declare a field with @Mock, and Mockito takes care of initializing it into a mock object.

Initializing `@Mock` Annotations

For @Mock annotations to work, you need to tell Mockito to process them. In JUnit 5, this is typically done using the @ExtendWith(MockitoExtension.class) annotation on your test class.

Alternatively, you can manually initialize them using MockitoAnnotations.openMocks(this).

Example: Using `@Mock` Annotation

This example simulates a test class where @Mock is used. Run it to see the mock initialized via MockitoAnnotations.openMocks().

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

interface DataRepository {
  String fetchData();
}

// Simulate a test class structure
class MyServiceTest {
  @Mock
  DataRepository mockRepository;

  public MyServiceTest() {
    // Manually open mocks for demonstration in main
    MockitoAnnotations.openMocks(this);
  }
}

public class Main {
  public static void main(String[] args) {
    MyServiceTest testInstance = new MyServiceTest();
    System.out.println("Mocked repository: " + testInstance.mockRepository.getClass().getName());
    System.out.println("Default fetch data: " + testInstance.mockRepository.fetchData());
  }
}

Quick Check on Mocks

You want to create a mock object for an interface called PaymentGateway. Which of the following is a correct and common way to do this in Mockito?

Recap: Creating Mocks

You've learned the fundamental ways to create mock objects with Mockito:

  • Use Mockito.mock(ClassToMock.class) for direct creation.
  • Use the @Mock annotation on a field, typically initialized by @ExtendWith(MockitoExtension.class) in JUnit 5.
  • Mocks return default values (null, 0, false) for method calls if not configured otherwise.

Next, we'll learn how to verify that your mocks were called as expected!

常见问题解答

「使用 Mockito 创建模拟对象」课时是免费的吗?

是的 — 「使用 Mockito 创建模拟对象」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Testing Mastery: JUnit, Mockito & Integration Tests 课程的其余内容,请升级到 CoddyKit PRO。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。

「使用 Mockito 创建模拟对象」这节课中我会学到什么?

使用 Mockito 为依赖项创建模拟对象,将待测试单元与其协作者隔离。 你通过在浏览器中直接运行的动手代码来练习 Testing Mastery: JUnit, Mockito & Integration Tests,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Testing Mastery: JUnit, Mockito & Integration Tests 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Testing Mastery: JUnit, Mockito & Integration Tests 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 Mockito 创建模拟对象」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Testing Mastery: JUnit, Mockito & Integration Tests 课中编写并运行代码吗?

能。每节 Testing Mastery: JUnit, Mockito & Integration Tests 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 模拟对象、存根与伪造对象
  2. 使用 Mockito 创建模拟对象
  3. 验证模拟对象交互
  4. 使用 @Mock 与 @InjectMocks 注入模拟对象
← 返回 Testing Mastery: JUnit, Mockito & Integration Tests