0

I am trying to test (using unittest.TestCase) that a ValueError exception is raised when an invalid value is passed to the deposit method but the test is failing when it being is raised. I've stepped through the test in the debugger and it does reach the raise ValueError line but the test still fails for some reason. I've even tried raising and asserting with other exceptions and the test still fails.

Here is a debug image

My method:

    def deposit(self, amount):
        if (not isinstance(amount, float)) and (not isinstance(amount, int)):
            raise ValueError

My test:

    def test_illegal_deposit_raises_exception(self):
        self.assertRaises(ValueError, self.account.deposit("Money"))

I then thought that perhaps it was failing becasue the exception had not yet been caught. So I added a method in my object's class to call the deposit method catch the ValueError Exception.

    def aMethod(self):
        try:
            self.deposit("Money")
        except ValueError:
            print("ValueError was caught")

However, now the test failed because I am getting a TypeError Exception instead. Here is an other debug image

TypeError: 'NoneType' object is not callable

Could someone explain why I am getting a TypeError Exception instead of the ValueError Exception which I've raised?

Samuel Browne
  • 73
  • 1
  • 9
  • The method returns the value None, not an error (since you caught it), reraise the error after the print (`raise ValueError`). That should at least remove the `TypeError`. – Thymen Dec 08 '20 at 13:03
  • You're right, if I re-raise the Value error after `print("ValueError was caught")` the correct `ValueError` is raised when I step through in the debugger. In that case, I should not use the `aMethod` method to test and use the `deposit` method to test right? That means I still have to figure out why the test is failing even though the correct exception is being raised. – Samuel Browne Dec 09 '20 at 03:18

1 Answers1

0

After looking at this answer by Daryl Spitzer I was able to get it working. Because the deposit method has arguments passed to it, I need to specify them in the assertion instead of in the method.

The correct way to test the Exception is raised:

self.assertRaises(ValueError, self.account.deposit, "Money")

The wrong way:

self.assertRaises(ValueError, self.account.deposit("Money"))
Samuel Browne
  • 73
  • 1
  • 9