gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:47:42 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com