I am trying to improve how I write my unit test cases for my Python programs. I am noticing in some cases, it would be really helpful to have access to private members to ensure that a method is functioning properly. An example case would be when trying to test a method for proper behavior that has no expected return value other than None. I know the easy and wrong way of doing this would be to just make the private attributes into protected attributes instead and test them directly. However, I would like to find a way that doesn't expose the interface as much.
So how do I test private attributes within classes without exposing them in the interface, or, if applicable, a better way of testing such a scenario so that private attribute access would not necessarily be needed for proper unit testing?
In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with the double underscore “__”. Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.
Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.
Python doesn't have real private variables, so use the __ prefix (two underlines at the beginning make a variable) from PEP 8. Use instance _class-name__private-attribute try to access private variables outside the class in Python.
Nothing is private in Python. If you are using the double underscore prefix on member variables, the name is simply mangled. You can access it by qualifying the name in the form _Class__member
. This will access the __member
variable in the class Class
.
See also this question: Why are Python's 'private' methods not actually private?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With