FordPrefect
FordPrefect

Reputation: 406

Test python class with method calls in __init__

I have a class which calls a lot of its methods in __init__. Since a lot is going on in these methods, I want to test them. Testing classes and class methods requires to instantiate the class and then call its methods. But if I instantiate the class, the methods will already be called before I can test it.

I have some ideas for possible solutions, but I am unsure if they are possible or a good way to go:

  1. I could introduce a kwarg into the class like init=True and testing for it within __init__. So I could have default option to do all the magic stuff on object creation, and could deactivate it to instantiate the class and call functions separately.

  2. I could define the methods outside the class in other classes or functions, if that works, and test them separately. The test of the bigger class would become something like an integration test.

Upvotes: 0

Views: 1664

Answers (1)

Eugene Yalansky
Eugene Yalansky

Reputation: 124

It depends on what you would like to test

If you want to check if all the calls are happening correctly you could mock underlying functionality inside the __init__ method.

And then do assert on the mocks. (Pytest has a spy mocks which does not modify original behavior but could be tested as mocks for call count, arguments etc... I'm sure you could replicate that with unittest mock as well)

So you could mock everything that is necessary by the beginning and then create an instance.

If you want to check how it was assembled you could do this after initialization.

Generally modifying your source code just for the purpose of the test case is not a good idea.

Run your code through a debugger, check what you are looking for as a tester and automate it.

Upvotes: 1

Related Questions