การทดสอบข้อยกเว้นและการหมดเวลา
ตรวจสอบข้อยกเว้นที่คาดหมายและกำหนดเวลาหมดเวลาเพื่อป้องกันลูปไม่รู้จบหรือกรณีทดสอบที่ทำงานนานเกินไป
การทดสอบข้อยกเว้นและการหมดเวลา เป็นบทเรียน 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 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Test for Expected Errors
Sometimes, your code is designed to throw an error under specific, invalid conditions. For example, dividing by zero. Exception testing ensures that your code handles these situations correctly.
- It validates both the success and failure paths.
- It confirms your error messages are accurate.
Catching Exceptions with JUnit
JUnit 5 provides the assertThrows method to verify that a specific exception is thrown. This is the recommended and cleanest way to test for expected exceptions.
- It takes the expected exception type (e.g.,
IllegalArgumentException.class). - It takes a lambda expression (a small piece of code) that should trigger the exception.
`assertThrows` in Action
Let's see assertThrows in a simple test. Our Calculator method divide should throw an IllegalArgumentException if the divisor is zero.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Calculator {
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
}
public class ExceptionTest {
@Test
void testDivideByZeroThrowsException() {
Calculator calc = new Calculator();
assertThrows(IllegalArgumentException.class, () -> {
calc.divide(10, 0);
});
}
}Checking Exception Details
It's often not enough to just know *that* an exception was thrown. You might also want to verify its details, like the exception message or other properties.
The assertThrows method returns the actual exception object, allowing you to perform further assertions on it.
Asserting Exception Message
Here, we capture the exception object returned by assertThrows and then use assertEquals to verify its message. This makes your exception tests very precise.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Calculator {
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
}
public class ExceptionMessageTest {
@Test
void testDivideByZeroMessage() {
Calculator calc = new Calculator();
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> calc.divide(10, 0),
"Expected divide() to throw, but it didn't"
);
assertEquals("Divisor cannot be zero", thrown.getMessage());
}
}Preventing Endless Tests with Timeouts
Sometimes, a piece of code can get stuck in an infinite loop or take an unexpectedly long time to complete. This can cause your test suite to hang indefinitely.
Timeouts are a crucial feature that automatically fail a test if it exceeds a specified duration, ensuring your test suite runs efficiently.
Setting Timeouts with `@Timeout`
JUnit 5 uses the @Timeout annotation to set a maximum duration for test methods or entire test classes. You specify the maximum value and a unit of time.
- Common units include
TimeUnit.SECONDS,TimeUnit.MILLISECONDS,TimeUnit.MINUTES. - If the test runs longer than the specified time, it will fail.
Method-Level Timeout Example
Here's how to apply a timeout to a single test method. If the longRunningTask() takes more than 1 second, this test will automatically fail.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
public class TimeoutMethodTest {
// A method that might take too long
private void longRunningTask() throws InterruptedException {
Thread.sleep(1500); // Simulates a task taking 1.5 seconds
}
@Test
@Timeout(value = 1, unit = TimeUnit.SECONDS)
void testTaskShouldCompleteWithinOneSecond() throws InterruptedException {
longRunningTask(); // This will cause the test to fail due to timeout
assertTrue(true, "Task completed (but it will timeout)");
}
}Class-Level Timeouts
You can also apply the @Timeout annotation at the class level. When placed on a test class, all test methods within that class will inherit the specified timeout.
If a test method also has its own @Timeout annotation, the method-level timeout will override the class-level one for that specific method.
Test Your Knowledge
Which JUnit 5 feature is best suited to ensure a test method completes execution within a predefined time limit, failing if it exceeds that limit?
Recap: Exceptions & Timeouts
In this lesson, you learned to write robust tests for expected errors and to prevent runaway tests:
- You used
assertThrowsto verify that specific exceptions are thrown by your code. - You learned how to verify specific details of an exception, such as its message.
- You applied the
@Timeoutannotation to set time limits for your test methods and classes, ensuring efficient test execution.
คำถามที่พบบ่อย
บทเรียน “การทดสอบข้อยกเว้นและการหมดเวลา” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การทดสอบข้อยกเว้นและการหมดเวลา” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ 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 ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- วงจรชีวิตและลำดับการทดสอบ
- การทดสอบแบบมีพารามิเตอร์และแบบไดนามิก
- การทดสอบข้อยกเว้นและการหมดเวลา
- การทดสอบแบบมีเงื่อนไขและสมมติฐาน