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

Factorial กับ unittest

ในแบบฝึกหัดนี้ จะได้เริ่มใช้ unittest เพื่อสร้างการทดสอบเบื้องต้นสำหรับฟังก์ชัน factorial เนื่องจากไลบรารีนี้ใช้แนวทางเชิงวัตถุ (object-oriented) ฟังก์ชันต่าง ๆ จึงถูกนำไปใช้งานในรูปของ method ภายใน class unittest.TestCase โดยได้ import แพ็กเกจ unittest ไว้ให้แล้ว

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

Python เบื้องต้นสำหรับการทดสอบโค้ด

ดูคอร์ส

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

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

def func_factorial(number):
    if number < 0:
        raise ValueError('Factorial is not defined for negative values')
    factorial = 1
    while number > 1:
        factorial = factorial * number
        number = number - 1
    return factorial

class TestFactorial(unittest.TestCase):
    def test_positives(self):
        # Add the test for testing positives here
        ____
แก้ไขและรันโค้ด