问题描述
使用类不变式时,代码协定似乎将代码注入到各处.像这样的东西
When using class invariants, Code contracts seems to inject code everywhere. Stuff like this
[ContractClassFor(typeof(IX))]
interface IXContract
{
[ClassInvariant]
void Invariant() { ... }
}
[ContractClass(typeof(IXContract))]
interface IX { event EventHandler b; }
var a = new Mock<IX>();
a.Raise(x => x.b += null);
失败,并显示错误消息
Could not locate event for attach or detach method Void $InvariantMethod$().
有人知道解决方案吗?
推荐答案
该单元测试在运行时通过"而不会产生异常:
This unit test "passes" when run without generating exceptions:
[ContractClassFor(typeof(IX))]
class IXContract
{
[ContractInvariantMethod]
void Invariant() { }
}
[ContractClass(typeof(IXContract))]
public interface IX { event EventHandler b; }
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class UnitTest1
{
public void MyTest()
{
var a = new Mock<IX>();
a.Raise(x => x.b += null);
}
}
我不完全确定发生了什么以及如何编译(或转录)以上内容,但是我认为您无法使用"ContractClassFor"属性来修饰界面,并且您当然不能使用接口中的实现"{...}".您还需要将接口IX公开以对其进行模拟(或者在属性中使用InternalsVisibleTo()内部城堡代理进行内部模拟).
I'm not entirely sure what's going on and how you're compiling (or transcribing) the above, but I don't think you can have "ContractClassFor" attribute decorating an interface, and you certainly can't have the implementation "{ ... }" in an interface. You also need to make your interface IX public to mock it (or else internal with InternalsVisibleTo() castle proxy in your properties).
希望这会有所帮助,但是,如果您没有按照自己的意愿去做,请随时使用新代码更新您的帖子.
Hopefully this helps, but feel free to update your post with new code if this doesn't lead you toward what you're looking to do.
这篇关于最小起订量和代码合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!