单元测试中的多个断言 [英] Multiple Asserts in a Unit Test

查看:403
本文介绍了单元测试中的多个断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚读完Roy Osherove的单元测试的艺术",我正在尝试遵循他在书中提出的最佳实践.这些最佳实践之一是在测试方法中不要使用多个断言.我很清楚这个规则的原因,但这让我感到奇怪...

I've just finished reading Roy Osherove's "The Art of Unit Testing" and I am trying to adhere to the best practices he lays out in the book. One of those best practices is to not use multiple asserts in a test method. The reason for this rule is fairly clear to me, but it makes me wonder...

如果我有类似的方法:

public Foo MakeFoo(int x, int y, int z)
{
     Foo f = new Foo();
     f.X = x;
     f.Y = y;
     f.Z = z;

     return f;
}

我真的必须编写单独的单元测试来断言Foo的每个单独属性都使用提供的值进行了初始化吗?在测试方法中使用多个断言真的不常见吗?

Must I really write individual unit tests to assert each separate property of Foo is initialized with the supplied value? Is it really all that uncommon to use multiple asserts in a test method?

仅供参考:我正在使用MSTest.

FYI: I am using MSTest.

感谢所有答复.我想我会总结多个断言.在我的情况下,正在测试的行为是MakeFoo生成了正确的Foo.因此断言每个属性都在获得期望值就足够了.但是,如果在设置其中一个属性时存在条件,那么我将分别测试每个结果.

Thanks for all the responses. I think I'll wind up going with the multiple asserts. In my situation the behavior being tested is that MakeFoo makes a proper Foo. So asserting that each property is getting the expected value should suffice. However, if there was a condition around setting one of the properties then I'd test each of the individual outcomes separately.

尽管如此,我还是不喜欢....我喜欢对每个测试声明一个断言的原因是,您知道测试失败的确切原因.如果您解决了问题,则测试将通过.对于多个断言,您没有相同的保证.如果您修复了失败的断言所暗示的问题,则没有什么可以阻止测试中稍后再次断言另一个断言的.如果断言是断断续续的,那么您将从一开始就知道这两个失败.

I still don't like it though.... The reason I like the idea of having one assert per test is that you know the exact reason a test failed. If you fix the problem then the test will pass. With multiple asserts you don't have the same guarantee. If you fix the problem alluded to by the failing assertion, there is nothing to stop another assertion later on in the test from failing next. If the asserts were split up, then you'd have known about both failures from the start.

最后,我之所以不使用.Equals()的原因是,在我的情况下,Foo是一个LINQ-To-SQL实体,它引入了一些不值得在这里讨论的复杂性.

And finally, the reason I'm not just using .Equals() is because in my situation Foo is a LINQ-To-SQL entity which introduces some complications that aren't worth getting into here.

再次感谢.

推荐答案

每个单元测试仅测试一个概念更为重要.

It is far more important to test just one concept per unit test.

测试一个概念可能需要多个断言,因此不必过分担心断言的数量.当然,如果您遇到大量断言,则可能需要退后一步,考虑一下您真正在测试什么.

It may take more than one assertion to test a concept, so don't worry overly about the number of assertions. Of course if you end up with a large number of assertions, you may want to take a step back and think about what you are really testing.

这篇关于单元测试中的多个断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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