Search code examples
pythonunit-testingtestingtddaccess-modifiers

In Python, how do I write unit tests that can access private attributes without exposing them?


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?


Solution

  • I'm gonna go off in a different direction...

    Try to write unit tests that assert public behavior over private state. Lets say you call your void method A() that modifies internal state. Now if the method is called and the state does change, there will be some observable change in your little code-universe. Maybe B() now behaves differently. So my test would be... (trivializing the example)

    void MyTest()
    {
       Assert.That(B(), Is.False);
       A();
       Assert.That(B(), Is.True);
    }
    

    Avoid Inappropriate Intimacy between the test and the SUT.