2017-08-25 251 views
-1

我對Python中的單元測試非常新穎。我正在爲一個非常小的方法編寫單元測試。代碼實現如下。但是,如果我運行測試腳本,我得到一個錯誤說:Python單元測試:類型錯誤:__init __()缺少

TypeError: __init__() missing 4 required positional arguments: 'x ,'y','z','w'

class get_result(): 
    def __init__(self,x,y,z,w): 
     self.x=x 
     self.y=y 
     self.z=z 
     self.w=w 


    def generate_result(self): 
     curr_x= 90 
     dist= curr_x-self.x 
     return dist 


import unittest 
from sample import get_result 
result = get_result() 

class Test(unittest.TestCase): 

    def test_generate_result(self): 
     self.assertEqual(somevalue, result.generate_result()) 
+4

是的,你的類需要四個參數,但是當你實例化它,你不傳遞任何。 – jonrsharpe

+0

如果你不想傳遞任何參數,你可以使用'def __init __(self,x = 0,y = 0,z = 0,w = 0):'定義默認值。 – PRMoureu

+0

你的類定義應該是CamelCase,否則它可能會讓某個讀取你的代碼的人感到困惑。 – Vinny

回答

1

result = get_result()應該result = get_result(xvalue,yvalue,zvalue,wvalue)

如果這些值==一些數字。或者如PRMoureu建議您可以在您的__init__()方法聲明中將它們設爲可選參數。

0

你的__init__方法要求 4個參數,當沒有提供時會引發錯誤。

如果你想支持可選的位置參數你可以定義初始化如下: __init__(self, *args, **kwargs),然後處理它們在函數內部。請注意,如果未提供對象,仍會創建該對象,並且如果未驗證值是否存在,則會在代碼的稍後階段遇到錯誤。您可以捕獲該異常並打印更可讀的錯誤:

>>> class GetResult(): 
    def __init__(self, *args, **kwargs): 
     if len(args) < 4: 
      raise Exception('one or more required parameters x, y, w, z is missing') 
.. rest code here 

>>> g = GetResult() 

Traceback (most recent call last): 
    File "<pyshell#87>", line 1, in <module> 
    g = GetResult() 
    File "<pyshell#86>", line 4, in __init__ 
    raise Exception('one or more required parameters x, y, w, z is missing') 
Exception: one or more required parameters x, y, w, z is missing