[英]Why am I getting an Assertion Error in Python?
我正在用 Python 測試一個函數。 這是我寫的函數。
def hypotenuse(a, b):
math.sqrt(a**2 + b**2)
我使用了這個測試用例。
def test_hypotenuse_1(self):
self.assertEqual(funcs.hypotenuse, 3, 4)
這個斷言錯誤出現了。
======================================================================
FAIL: test_hypotenuse_1 (__main__.TestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
File "funcs_tests.py", line 27, in test_hypotenuse_1
self.assertEqual(funcs.hypotenuse, 3, 4)
AssertionError: <function hypotenuse at 0x7f397f2d79d8> != 3 : 4
我做錯了什么? 對不起,如果這是一個基本問題,我是第一次編碼。
您需要調用該函數,然后指定該調用的結果應該等於什么
def test_hypotenuse_1(self):
self.assertEqual(funcs.hypotenuse(3, 4), 5)
這斷言具有邊 3 和邊 4 的三角形的斜邊等於 5。
您的測試仍然會失敗,因為hypotenuse()
不返回結果。 它必須是:
def hypotenuse(a, b):
return math.sqrt(a**2 + b**2)
請注意,您通常不應該對這樣的數學函數使用相等測試。 它使用浮點運算,可能有舍入誤差。 您可以assertAlmostEqual()
使用assertAlmostEqual()
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.