lom*_*axx 6 c# unit-testing virtual-functions mocking
我一直在用RhinoMocks做一些嘲弄,它需要将模拟的方法变成虚拟的.这很好,除了我们有一个自定义框架,其中包含我想要模拟的方法,这些方法当前没有标记为虚拟.
我不能预见到使这些方法变得虚拟的任何问题,但我想知道使方法虚拟的一些潜在危险我应该注意什么?
小智 8
实际上,如果该方法不是被设计为被覆盖并且有人覆盖它,那么它可能是非常有问题的.特别是,永远不要从构造函数中调用虚方法.考虑:
class Base {
public Base() {
InitializeComponent();
}
protected virtual void InitializeComponent() {
...
}
}
class Derived : Base {
private Button button1;
public Derived() : base() {
button1 = new Button();
}
protected override void InitializeComponent() {
button1.Text = "I'm gonna throw a null reference exception"
}
}
Run Code Online (Sandbox Code Playgroud)
Derived类可能不知道虚方法调用将导致在其自己的构造函数的单行运行之前调用其InitializeComponent方法.
归档时间: |
|
查看次数: |
873 次 |
最近记录: |