起订量正在触发代码合同?
给出这段代码:
[ContractClass(typeof(DogContract))]
public interface IDog {
void Eat(object obj);
}
[ContractClassFor(typeof(IDog))]
internal abstract DogContract : IDog {
public void Eat(object obj) {
Contract.Requires<ArgumentNullException>(obj != null);
}
}
var dogMock = new Mock<IDog>();
dogMock.Object.Eat(null); // Throws ArgumentNullException
似乎重写器以某种方式将其行为放入模拟对象中,这是我真正没想到的。我不认为这是一个真正的问题,只是出乎意料。有人知道这是怎么发生的吗?
Given this code:
[ContractClass(typeof(DogContract))]
public interface IDog {
void Eat(object obj);
}
[ContractClassFor(typeof(IDog))]
internal abstract DogContract : IDog {
public void Eat(object obj) {
Contract.Requires<ArgumentNullException>(obj != null);
}
}
var dogMock = new Mock<IDog>();
dogMock.Object.Eat(null); // Throws ArgumentNullException
It seems like the rewriter is somehow putting its behavior into the mocked object, which I didn't really expect. I don't think its a real problem, just unexpected. Anyone know how this is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“调用站点需要检查”就可以了。然后,重写器会将前提条件放入调用者代码中,而不是实现中。因此,即使模拟对象中的代码无法重写(它是在运行时生成的),调用者中的代码也可以重写。
生成的代码如下所示,不带调用站点 Requires:
且带:
IDog 是一个静态类,包含 IDog 接口中的所有方法以及先决条件。 Eat 的样子如下:
这样,即使类中的代码无法重写,前置条件也会被调用。
"Call-site Requires checking" will do it. The rewriter will then put the preconditions into the caller code and not the implementations. So, even though the code in the mocked object can't have been rewritten (it's generated at runtime), the code in the caller can be.
Here's what the generated code looks like without call-site Requires:
And with:
IDog is a static class that contains all the methods from the IDog interface, along with the preconditions. Here is what Eat looks like:
So this way, the preconditions will be called even if the code in the class can't have been rewritten.