เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การจัดการ Exception: การประมวลผลข้อความ

การใช้และจัดการ exception เป็นส่วนสำคัญของการเขียนโค้ด การทดสอบ exception จึงเป็นสิ่งที่ขาดไม่ได้เช่นกัน

ในแบบฝึกหัดนี้ จะได้ฝึกใช้ syntax สำหรับการ assert ประเภท class instance ของ JUnit โดยจะมีเมธอดที่แปลง String เป็นตัวพิมพ์ใหญ่ให้ แต่จะ throw RuntimeException แบบกำหนดเองหาก String เป็น null งานของคุณคือเขียน unit test สำหรับเมธอดนี้

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การทดสอบใน Java เบื้องต้น

ดูคอร์ส

คำแนะนำการฝึกหัด

  • Assert ว่าข้อความถูกแปลงเป็นตัวพิมพ์ใหญ่แล้วในกรณีที่สำเร็จ
  • ใช้ assertion ที่เหมาะสมเพื่อตรวจสอบว่า exception ที่ถูก throw นั้นเป็น instance ของ คลาส RuntimeException
  • ระบุคลาสที่คาดหวังของ exception
  • ใช้ assertion ที่ถูกต้องเพื่อตรวจสอบข้อความของ exception

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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());
    }
}
แก้ไขและรันโค้ด