例外處理:訊息處理
就像在程式中使用並處理例外是不可或缺的一部分,測試這些例外對於測試你的專案同樣重要。
在本練習中,你會練習 JUnit 的類別實例斷言語法。你會拿到一個將字串轉成大寫的方法,但當字串為 null 時會拋出自訂的 RuntimeException。你的任務是為它撰寫單元測試。
本練習屬於課程
Java 測試入門
練習說明
- 在成功情境的測試中,斷言訊息已被轉成大寫。
- 使用正確的斷言類型,驗證所拋出的例外是
RuntimeException類別的實例。 - 輸入例外的預期類別。
- 使用正確的斷言來驗證例外訊息。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Main {
public static void main(String[] args) {
launchTestsAndPrint(MessageProcessorTest.class);
}
}
class MessageProcessorTest {
@Test
void processMessage_returnsUppercase() {
String message = "error!";
String expected = "ERROR!";
String actual = MessageProcessor.processMessage(message);
// Assert the message is converted to uppercase
____(expected, actual);
}
@Test
void processMessage_throwsException_whenMessageIsNull() {
String message = null;
Exception expectedException = null;
try {
MessageProcessor.processMessage(message);
} catch (Exception e) {
expectedException = e;
}
// Assert the correct type of exception
____(RuntimeException.class, expectedException);
// Assert the correct exception message
____("Message cannot be null.", expectedException.getMessage());
}
}