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

ตัวเลขหลักสุดท้ายด้วย MethodSource

เช่นเดียวกับภาษาโปรแกรมยอดนิยมที่มีมาอย่างยาวนาน Java มีระบบนิเวศที่กว้างขวาง และมักมีหลายวิธีในการทำสิ่งเดียวกัน

ลองนำแบบฝึกหัด LastDigit จากบทเรียนก่อนหน้ามาเขียนใหม่โดยใช้ @MethodSource เพื่อฝึกไวยากรณ์ที่เพิ่งเรียนไป

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

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

ดูคอร์ส

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

  • ใช้ annotation ที่ถูกต้องสำหรับ parameterized test ที่รับอาร์กิวเมนต์จากเมธอด
  • ระบุให้ annotation ชี้ไปยังเมธอด arguments provider
  • ใช้ไวยากรณ์เดิมสามครั้งเพื่อสร้างคู่อาร์กิวเมนต์

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

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

public class LastDigitWithTests {
  public static void main(String[] args) {
    launchTestsAndPrint(LastDigitTest.class);
  }
}

class LastDigitTest {

    @ParameterizedTest
    // Add the annotation to use a method to provide arguments and point it to the arguments method
    @____("____")
    void testLastDigit(int number, int expected) {
        int actual = LastDigit.lastDigit(number);

        assertEquals(expected, actual);
    }

    private static List getArgs() {
        return List.of(
        	// Create three argument objects for the test using the same syntax
            ____.of(2025, 5),
            ____.of(-2025, 5),
            ____.of(2020, 0)
        );
    }
}
แก้ไขและรันโค้ด