예외 테스트 및 시간 제한
예상한 예외가 발생하는지 검증하고 무한 루프나 장시간 실행되는 테스트 사례를 방지하도록 시간 제한을 구현합니다.
예외 테스트 및 시간 제한은(는) CoddyKit의 무료 Testing Mastery: JUnit, Mockito & Integration Tests 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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.
자주 묻는 질문
“예외 테스트 및 시간 제한” 강의는 무료인가요?
네 — “예외 테스트 및 시간 제한” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Testing Mastery: JUnit, Mockito & Integration Tests 강의 전체를 잠금 해제할 수 있습니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.
“예외 테스트 및 시간 제한”에서 뭘 배우나요?
예상한 예외가 발생하는지 검증하고 무한 루프나 장시간 실행되는 테스트 사례를 방지하도록 시간 제한을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Testing Mastery: JUnit, Mockito & Integration Tests을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Testing Mastery: JUnit, Mockito & Integration Tests을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Testing Mastery: JUnit, Mockito & Integration Tests은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“예외 테스트 및 시간 제한” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Testing Mastery: JUnit, Mockito & Integration Tests 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 테스트 수명 주기 및 순서
- 매개변수화 테스트와 동적 테스트
- 예외 테스트 및 시간 제한
- 조건부 테스트와 가정