我有一个困难时期设法确保被应用了,我写了使用代码契约的接口(很简单)的合同。为什么Interface合约不能在组件外部应用?
我对我们的项目之一,在“共享” DLL的代码。这样做的目的是,我们几个模块可以使用相同的基础架构,并实现自己的处理程序和命令类型:
[ContractClass(typeof(CommandHandlerContracts<>))]
public interface ICommandHandler<TCommand>
where TCommand : ICommand
{
void Handle(TCommand _command);
}
[ContractClassFor(typeof(ICommandHandler<>))]
public class CommandHandlerContracts<TCommand> : ICommandHandler<TCommand>
where TCommand : ICommand
{
public void Handle(TCommand _command)
{
Contract.Requires<ArgumentNullException>(_command != null);
}
}
如果我然后运行一个简单的测试,这样,它失败了,因为没有抛出异常:
public class TestCommand : ICommand
{
public string Field { get; set; }
}
public class TestHandler : ICommandHandler<TestCommand>
{
public void Handle(TestCommand _command) { }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
[ExpectedException(typeof (ArgumentNullException))]
public void TestMethod1()
{
new TestHandler().Handle(null);
}
}
只要我复制/粘贴从另一个dll的接口和契约类定义到测试类,一切都开始工作。似乎有一个问题,接口是在一个不同的dll实现的。
我目前使用的Visual Studio 2012和单元测试微软测试类(“Microsoft.VisualStudio.QualityTools.UnitTestFramework”)。应用程序和测试DLL都针对.net4.0框架。
代码合同设置为“标准合同要求”,完整的运行时检查和两个项目的合同参考大会的'DoNotBuild'(起初我不确定这是单元测试项目所需要的,但我添加了它也无济于事)。
我想这应该工作出了大门,我失去了一些东西在这里?