1

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())
5
  • 4
    Yes, your class requires four arguments but you don't pass any when you instantiate it. Commented Aug 25, 2017 at 17:16
  • you can use def __init__(self,x=0,y=0,z=0,w=0): to define default values if you don't want to pass any arguments. Commented Aug 25, 2017 at 17:18
  • Your class definition should be CamelCase, otherwise it may be confusing with a function to someone who reads your code. Commented Aug 25, 2017 at 17:24
  • Thanks! Understood! Commented Aug 25, 2017 at 17:26
  • Possible duplicate of Python - __init__() missing 1 required positional argument: Commented Aug 25, 2017 at 22:49

2 Answers 2

2

result = get_result() should be result = get_result(xvalue,yvalue,zvalue,wvalue)

Where those values == some number. Or as PRMoureu suggests you can make them optional arguments in your declaration of your __init__() method.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.