简体   繁体   English

断言(合同)和单元测试

[英]Assertions (contracts) and unit testing

Say I have a method 说我有办法

public void PrintStuff(string stuff, Color color, PageDimensions dimensions)
{
     Assert.IsNotNull("color");
     Assert.IsNotNull(dimensions);
     Assert.IsTrue(dimensions.width < 20.0);
}

and I have another method AnotherMethod() which is calling PrintStuff() . 我还有另一个方法AnotherMethod() ,它正在调用PrintStuff() Let's assume PrintStuff() is defined in some interfaces that AnotherMethod() is using. 假设PrintStuff()是在AnotherMethod()使用的某些接口中定义的。 The question is: when writing a unit test for AnotherMethod() how can I automate testing that AnotherMethod() does not pass any values into PrintStuff() that violate its assertions? 问题是:编写用于AnotherMethod()的单元测试时,如何自动测试AnotherMethod()不会将任何值传递给违反其断言的PrintStuff()

Something like: 就像是:

printer.Expect(x => x.PrintStuff(null, null, null)).CheckAssertions();

The solution should support a change in assertions automatically. 解决方案应自动支持断言的更改。

If PrintStuff is in an interface but your assertions are in a concrete class, who's to say the same assertions apply to all implementations? 如果PrintStuff在接口中,但是您的断言在具体的类中,那么谁又说相同的断言适用于所有实现? It sounds like what you really want is to give contracts to the interface rather than the concrete class. 听起来您真正想要的是为接口提供合同,而不是具体的类。 Obviously you can't do that in "normal" C# code... 显然,您无法在“正常”的C#代码中执行此操作...

Now, I'd suggest using Code Contracts which support contract inheritance, including interfaces. 现在,我建议使用支持合同继承(包括接口)的代码合同 If you're using Visual Studio Premium or Ultimate editions, you can have compile-time static checking that you don't violate the assertions. 如果您使用的是Visual Studio Premium或Ultimate版本,则可以进行编译时静态检查,以确保不违反声明。 Otherwise, you're back to mocking I believe. 否则,我相信您会回到嘲笑。 Now if you use mocking, I don't think the contracts will automatically be picked up, because they're usually applied using binary rewriting... but I'd expect the tooling in this area to improve reasonably soon. 现在,如果您使用模拟,我认为合同不会自动被提取,因为它们通常是使用二进制重写来应用的……但是我希望该领域的工具能够在相当短的时间内得到改进。 Of course, mocking usually involves specifying the inputs you expect anyway, so you should be able to make sure they're valid when you write your tests anyway. 当然,模拟通常涉及指定您期望的输入,因此无论如何编写测试时,您应该能够确保它们有效。

You may also want to look at Pex which explores your code and tries to break it for you. 您可能还想看看Pex ,它会探索您的代码并尝试为您打破代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM