Skip to content
Advertisement

TypeError: object is not callable when instantiating during unit test

I have a class that throws an exception when instantiated with wrong values and I would like to write a unit test raising an exception when given wrong parameters.

Instantiating an object outside of the self.assertRaises() doesn’t seem to cause any error and I fail to understand why it causes an error when I try to instantiate it within the assert

my class looks like this:

JavaScript

My test looks like this:

JavaScript

But I get:

JavaScript

Do you know how should I do if I want to test this ?

Advertisement

Answer

The signature of assertRaises is different than your usage. See the documentation Here

You should either provide it with a callable and the arguments it should call it with, or you should use the with statement and call it as usual.

Here is a snippet, showing the two approaches:

JavaScript

Based on your edited question: You actually don’t throw an exception, but catch it in your code, so the assertion fails, because you don’t do what you expect. Tests work!

Now, if you want to check if the exception was caught as expected, you should test if the print statement was printed:

JavaScript

What we do here is to redirect the standard output to a simple text stream, then call your method, capture the output (stripping it to remove any unknown whitespaces) and check if the outputted string is the same as we expect it to be. In my case, I just print "I am an exception". You should replace this with the output of your exception.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement