起订量和虚拟属性和方法
我使用 Moq 进行单元测试。 为了让 Moq 工作,属性和方法必须标记为虚拟。 有时我会传入数据并在构造函数中设置属性值。 是否有一条规则规定不应在构造函数中设置虚拟属性,因为这可能会导致意外行为(如果该类是从基类继承的),或者这样做安全吗?
I'm using Moq for unit testing. It order for Moq to work, properties and methodes have to be marked as virtual. Sometimes I pass in data and set property values in the constructors. Isn't there a rule that you should not set virtual properties in constrcutors since it might cause unexpected behaviour (if the class has been inherited from a base class) or is it safe to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这确实是一个问题,Visual Studio 代码分析显式检查为此。
一个简单的解决方法是将工作移至非虚拟内部成员,然后让虚拟方法调用该成员以及构造函数。 像这样的事情:
It is, indeed a problem, and Visual Studio Code Analysis explicitly checks for this.
A simple workaround for this is to move the work to a non-virtual internal member, and then have the virtual method call that, as well as the constructor. Something like this: