.net - 为什么接口(interface)契约(Contract)不适用于装配外部?

标签 .net unit-testing generics visual-studio-2012 code-contracts

我很难确保应用我为使用代码契约的接口(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);
    }
}

只要我将接口(interface)和契约(Contract)类定义从另一个 dll 复制/粘贴到测试类中,一切就会开始工作。接口(interface)与实现接口(interface)位于不同的 dll 中这一事实似乎存在问题。

我目前正在使用 Visual Studio 2012 和 Microsoft 测试类(“Microsoft.VisualStudio.QualityTools.UnitTestFramework”)进行单元测试。应用程序和测试 dll 都针对 .net4.0 框架。

两个项目的契约(Contract)引用程序集的代码契约(Contract)设置为“标准契约(Contract)要求”、完整的运行时检查和“DoNotBuild”(起初我不确定单元测试项目是否需要这个,但我添加了它也无济于事)。

我认为这应该可以解决问题,我是否遗漏了什么?

最佳答案

我对代码契约(Contract)实际上如何生成契约(Contract)条款有错误的想法。事实证明,它需要为所有引用的程序集构建契约(Contract)引用程序集,以确保运行时检查(在我的项目中它被设置为“DoNotBuild”)。

将“通用”项目设置为“构建”后,测试项目能够创建自己的合约并开始抛出异常。

可以找到关于这个问题的更多讨论 here

关于.net - 为什么接口(interface)契约(Contract)不适用于装配外部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15909401/

相关文章:

java - 使用泛型时如何解决这个未经检查的转换错误?

.net - 具有多个零值问题的标志枚举(TextFormatFlags)

.net - 为什么 F# Set 不实现 ISet<T>?

visual-studio-2010 - 如何在VS单元测试中包含样本数据文件?

c# - AutoFixture 和流畅的 Moq 语法

java - 返回时泛型如何工作?

c# - 使用相等运算符比较两个 floored double 是否安全?

c# - 带有 INotifyPropertyChanged 实现的奇怪 NullReferenceException

c# - 最小起订量设置在被告知时不返回值

android - Kotlin - 检查泛型参数是否可选?