Reputation: 45
I am very new to Unit Testing in Python. I was writing a unit test for a very small method. The code implementation is a follows. But if I run the test script, I get an error saying :
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())
Upvotes: 1
Views: 1774
Reputation: 11280
Your __init__
method requires 4 arguments, and when not provided raise an error.
If you want to to support optional position argument you can define init as follows:
__init__(self, *args, **kwargs)
and then handle them inside the function. Pay attention that if not provided, the object still gets created and if you don't validate the values exist you'll encounter the error at a later stage in your code. You can catch this exception and print more readable error:
>>> 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
Upvotes: 0