0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · บทเรียน

การตรวจสอบการโต้ตอบกับม็อก

เรียนรู้การตรวจสอบว่าออบเจ็กต์ม็อกถูกเรียกด้วยอาร์กิวเมนต์ที่คาดหมายและจำนวนครั้งที่กำหนด

การตรวจสอบการโต้ตอบกับม็อก เป็นบทเรียน Testing Mastery: JUnit, Mockito & Integration Tests ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Testing Mastery: JUnit, Mockito & Integration Tests และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Testing Mastery: JUnit, Mockito & Integration Tests มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to Mockito Verification

Welcome to verifying mock interactions! After learning to create mocks, the next crucial step is to confirm how they were used.

Verification in Mockito means checking if specific methods on your mock objects were called during a test.

Why Verify Interactions?

When testing a class, you often want to ensure it correctly interacts with its dependencies.

  • Collaboration Check: Did the object under test call the right methods on its collaborators?
  • Behavior Confirmation: Did it pass the correct arguments to those methods?
  • Interaction Count: Was a method called once, multiple times, or not at all?

Verification answers these questions, ensuring your code behaves as expected.

The Basic `verify()` Method

The simplest way to verify an interaction is using Mockito.verify(). It checks if a method was called exactly once.

You write verify(mockObject).methodCall(); after the code under test has run. If the method wasn't called, or was called more than once, Mockito will throw an error.

Code: Basic `verify()` in Action

Try this runnable example. We'll simulate a test by creating a mock and calling a method on it. Then, we verify the interaction.

In a real JUnit test, a failed verification would make the test fail.

import static org.mockito.Mockito.*;

interface MyService {
    void doSomething();
}

class MyProcessor {
    private MyService service;
    public MyProcessor(MyService service) {
        this.service = service;
    }
    public void execute() {
        service.doSomething();
    }
}

public class Main {
    public static void main(String[] args) {
        MyService mockService = mock(MyService.class);
        MyProcessor processor = new MyProcessor(mockService);

        System.out.println("Calling execute...");
        processor.execute(); // This calls mockService.doSomething()

        try {
            // Verify doSomething() was called exactly once
            verify(mockService).doSomething();
            System.out.println("\nVerification successful: doSomething() called once.");
        } catch (Throwable e) {
            System.out.println("\nVerification failed: " + e.getMessage());
        }
        System.out.println("Program finished.");
    }
}

Verifying Specific Arguments with `eq()`

Often, you need to check not just if a method was called, but with what arguments.

Use eq(value) to match an exact argument value. For example, verify(mock).someMethod(eq("hello"), eq(123)); ensures the method was called with "hello" and 123.

You can also use generic matchers like anyString() or anyInt() if you don't care about a specific argument's value.

Code: `verify()` with `eq()`

Here, we verify that a message was sent with specific content and priority. Notice how eq() helps us be precise.

import static org.mockito.Mockito.*;

interface DataSender {
    void send(String message, int priority);
}

class MessageProcessor {
    private DataSender sender;
    public MessageProcessor(DataSender sender) {
        this.sender = sender;
    }
    public void processAndSend(String data) {
        sender.send(data.toUpperCase(), 1);
    }
}

public class Main {
    public static void main(String[] args) {
        DataSender mockSender = mock(DataSender.class);
        MessageProcessor processor = new MessageProcessor(mockSender);

        System.out.println("Processing 'hello' message...");
        processor.processAndSend("hello");

        try {
            // Verify send() was called with "HELLO" and 1
            verify(mockSender).send(eq("HELLO"), eq(1));
            System.out.println("\nVerification successful: Correct arguments received.");
        } catch (Throwable e) {
            System.out.println("\nVerification failed: " + e.getMessage());
        }

        // The following commented block shows a failing verification
        // try {
        //     verify(mockSender).send(eq("hello"), eq(1)); // "hello" (lowercase) is wrong
        //     System.out.println("This should not be printed.");
        // } catch (Throwable e) {
        //     System.out.println("Expected failure for wrong arguments: " + e.getMessage());
        // }
        System.out.println("Program finished.");
    }
}

Verifying Call Counts: `times()` & `never()`

Sometimes, you need to verify how many times a method was called:

  • verify(mock, times(N)).method();: Called exactly N times.
  • verify(mock, never()).method();: Never called (same as times(0)).

These are powerful for ensuring loops, conditions, or error handling work correctly.

Code: `times()` and `never()`

This example processes multiple events and logs an error. We'll verify the exact number of times each type of log was made.

import static org.mockito.Mockito.*;

interface EventLogger {
    void log(String event);
}

class EventProcessor {
    private EventLogger logger;
    public EventProcessor(EventLogger logger) {
        this.logger = logger;
    }
    public void processEvents(int count) {
        for (int i = 0; i < count; i++) {
            logger.log("Event " + (i + 1));
        }
    }
    public void logError(String error) {
        logger.log("ERROR: " + error);
    }
}

public class Main {
    public static void main(String[] args) {
        EventLogger mockLogger = mock(EventLogger.class);
        EventProcessor processor = new EventProcessor(mockLogger);

        System.out.println("Processing 3 events and logging an error...");
        processor.processEvents(3);
        processor.logError("Failed to connect");

        try {
            // Verify log() was called 3 times with arguments starting with "Event "
            verify(mockLogger, times(3)).log(startsWith("Event "));
            System.out.println("\nVerification successful: 'Event' logged 3 times.");

            // Verify log() was called once with the exact error message
            verify(mockLogger, times(1)).log(eq("ERROR: Failed to connect"));
            System.out.println("Verification successful: Error logged once.");

            // Verify log() was never called with arguments starting with "WARNING"
            verify(mockLogger, never()).log(startsWith("WARNING"));
            System.out.println("Verification successful: 'WARNING' never logged.");

        } catch (Throwable e) {
            System.out.println("\nVerification failed: " + e.getMessage());
        }
        System.out.println("Program finished.");
    }
}

Flexible Call Counts: `atLeast()`, `atMost()`

Sometimes an exact count isn't necessary, but a range is important:

  • verify(mock, atLeast(N)).method();: Called N or more times.
  • verify(mock, atMost(N)).method();: Called N or fewer times.

There are also convenient shortcuts: atLeastOnce() and atMostOnce() for clarity.

Verify Interactions Check

Which of the following are valid ways to verify method calls using Mockito?

Recap: Mastering Verification

You've learned how to verify mock interactions in Mockito!

  • verify(mock).method(); checks for a single call.
  • Use eq() for exact argument matching or generic matchers like anyString().
  • Control call counts with times(N), never(), atLeast(N), and atMost(N).

Mastering verification is key to writing robust, reliable unit tests that confirm precise object collaboration.

คำถามที่พบบ่อย

บทเรียน “การตรวจสอบการโต้ตอบกับม็อก” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การตรวจสอบการโต้ตอบกับม็อก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Testing Mastery: JUnit, Mockito & Integration Tests ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Testing Mastery: JUnit, Mockito & Integration Tests มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจสอบการโต้ตอบกับม็อก”

เรียนรู้การตรวจสอบว่าออบเจ็กต์ม็อกถูกเรียกด้วยอาร์กิวเมนต์ที่คาดหมายและจำนวนครั้งที่กำหนด คุณปฏิบัติ Testing Mastery: JUnit, Mockito & Integration Tests ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Testing Mastery: JUnit, Mockito & Integration Tests หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Testing Mastery: JUnit, Mockito & Integration Tests บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การตรวจสอบการโต้ตอบกับม็อก” ใช้เวลานานแค่ไหน

บทเรียน 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