[英]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. 我正在努力改进我为Python程序编写单元测试用例的方法。 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. 一个示例案例是在尝试测试方法以确定没有预期返回值而非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? 那么如何测试类中的私有属性而不在接口中公开它们,或者,如果适用的话,更好的方法是测试这样的场景,以便正确的单元测试不一定需要私有属性访问?
Nothing is private in Python. 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
. 您可以通过在_Class__member
表单中限定名称来访问它。 This will access the __member
variable in the class Class
. 这将访问类Class
的__member
变量。
See also this question: Why are Python's 'private' methods not actually private? 另请参阅此问题: 为什么Python的“私有”方法实际上不是私有的?
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. 让我们假设您调用修改内部状态的void方法A()。 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. 也许B()现在表现不同。 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. 避免测试和SUT之间的不适当的亲密关系 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.