การสร้างม็อกด้วย Mockito
ใช้ Mockito เพื่อสร้างออบเจ็กต์ม็อกสำหรับสิ่งที่ต้องพึ่งพา โดยแยกหน่วยที่กำลังทดสอบออกจากส่วนที่ทำงานร่วมกัน
การสร้างม็อกด้วย Mockito เป็นบทเรียน Testing Mastery: JUnit, Mockito & Integration Tests ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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
voiddo 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
@Mockannotation 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 ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Testing Mastery: JUnit, Mockito & Integration Tests ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Testing Mastery: JUnit, Mockito & Integration Tests มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างม็อกด้วย Mockito”
ใช้ Mockito เพื่อสร้างออบเจ็กต์ม็อกสำหรับสิ่งที่ต้องพึ่งพา โดยแยกหน่วยที่กำลังทดสอบออกจากส่วนที่ทำงานร่วมกัน คุณปฏิบัติ Testing Mastery: JUnit, Mockito & Integration Tests ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Testing Mastery: JUnit, Mockito & Integration Tests หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Testing Mastery: JUnit, Mockito & Integration Tests บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างม็อกด้วย Mockito” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Testing Mastery: JUnit, Mockito & Integration Tests นี้ได้ไหม
ได้ บทเรียน Testing Mastery: JUnit, Mockito & Integration Tests ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ม็อก สตับ และเฟก
- การสร้างม็อกด้วย Mockito
- การตรวจสอบการโต้ตอบกับม็อก
- การฉีดม็อกด้วย @Mock และ @InjectMocks