.NET 4.0 code合同 - 他们将如何影响到单元测试? [英] .NET 4.0 code contracts - How will they affect unit testing?

查看:142
本文介绍了.NET 4.0 code合同 - 他们将如何影响到单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如本文章介绍了他们。

有什么好处?

静态分析看来很酷,但在同一时间,将prevent传递null作为单元测试参数的能力。 (如果你按照在作为制品的例子)

Static analysis seems cool but at the same time it would prevent the ability to pass null as a parameter in unit test. (if you followed the example in the article that is)

在单元测试的主题 - 给定的东西怎么现​​在肯定是没有点code合同,如果你已经练习自动化测试?

While on the topic of unit testing - given how things are now surely there is no point for code contracts if you already practice automated testing?

更新

已经打了code合同,我有点失望。例如,基于code在接受答案:

Having played with Code Contracts I'm a little disappointed. For example, based on the code in the accepted answer:

public double CalculateTotal(Order order)
{
    Contract.Requires(order != null);
    Contract.Ensures(Contract.Result<double>() >= 0);
    return 2.0;
}

有关单元测试,您还是要编写测试,以确保空无法通过,结果大于或等于零,如果合同的业务逻辑。换句话说,如果我是删除了第一份合同,没有考试将打破,除非我曾专门有一个测试此功能。这是基于不使用静态分析内置到更好的Visual Studio(最终等...)版本然而。

For unit testing, you still have to write tests to ensure that null cannot be passed, and the result is greater than or equal to zero if the contracts are business logic. In other words, if I was to remove the first contract, no tests would break, unless I had specifically had a test for this feature. This is based on not using the static analysis built into the better (ultimate etc...) editions of Visual Studio however.

从本质上讲,他们都归结为书写传统if语句的另一种方式。我的经验实际使用<一个href="http://stackoverflow.com/questions/2639960/how-come-you-cannot-catch-$c$c-contract-exceptions">TDD,与code合同说明了为什么,我该怎么去了。

Essentially they all boil down to an alternate way of writing traditional if statements. My experience actually using TDD, with Code Contracts shows why, and how I went about it.

推荐答案

我不认为单元测试和合同相互干扰多,如果有什么合同,应当有助于单元测试,因为它消除了需要添加繁琐的重复测试参数无效。合同规定的最低,你可以从功能期待,而单元测试尝试验证的实际行为为一组特定的输入。考虑这个人为的例子:

I don't think unit testing and contracts interfere with each other that much, and if anything contracts should help unit testing since it removes the need to add tedious repetitive tests for invalid arguments. Contracts specify the minimum you can expect from the function, whereas unit tests attempt to validate the actual behaviour for a particular set of inputs. Consider this contrived example:


public class Order
{
    public IEnumerable Items { get; }
}

public class OrderCalculator
{
    public double CalculateTotal(Order order)
    {
    	Contract.Requires(order != null);
    	Contract.Ensures(Contract.Result<double>() >= 0);

    	return 2.0;
    }
}

显然,code满足合同,但你仍然需要单元测试,以验证它实际上表现为你所期望的。

Clearly the code satisfies the contract, but you'd still need unit testing to validate it actually behaves as you'd expect.

这篇关于.NET 4.0 code合同 - 他们将如何影响到单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆