0

I'm having trouble performing a simple unittest on a class I created. I'm getting this error:

AssertionError: <main.MathClass object at 0x7fc7e0340940> != 18

import unittest

class MathClass:
    def __init__(self):
        self.result = 0

    def add(self, num, *nums):
        self.result += num + sum(nums)
        return self

    def subtract(self, num, *nums):
        self.result -= (num + sum(nums))
        return self


class MathTest(unittest.TestCase):
    def testAdd(self):
        self.assertEqual(self.result.add(4,5,9), 18)

    def setUp(self):
        self.result = MathClass()


if __name__ == "__main__":
    unittest.main()

1 Answer 1

1

In your unit test you make a result object which is a MathClass object `:

def setUp(self):
    self.result = MathClass()

You later invoke the add method of the MathClass object. The problem is that your add method returns self, e.g. the Math object itself.

def add(self, num, *nums):
    self.result += num + sum(nums)
    return self

Internally, the MathClass.result may be changed but add still returns the Math object.

Therefore your assertEquals check compares the Math object and an int (18). Which are not equal :)

If you want to keep your variable names you may create a local variable that gets the MathClass object's result and compares it to 18:

def testAdd(self):
    self.result.add(4,5,9)
    value = self.result.result
    self.assertEqual(value, 18)

Or whatever other option you find more appropriate.

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

1 Comment

Thanks, this is a great option and the explanation helped tremendously. I ended up keeping my code in MathTest and used return self.result in the add method of my MathClass

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.