简体   繁体   English

NUnit设置属性是否有代码味道?

[英]Is NUnit Setup attribute a code smell?

I have written a set of NUnit classes, which have Setup and TearDown attributes. 我已经编写了一组NUnit类,它们具有Setup和TearDown属性。 Then I read this: http://jamesnewkirk.typepad.com/posts/2007/09/why-you-should-.html . 然后,我读了这篇文章: http : //jamesnewkirk.typepad.com/posts/2007/09/why-you-should-.html I can understand what the author is saying where you have to scroll up and scroll down when reading the Unit Tests. 我能理解作者在说什么,在阅读单元测试时必须向上和向下滚动。 However, I also see the benefit of Setup and TearDown. 但是,我也看到了Setup和TearDown的好处。 For example, in a recent test class I did this: 例如,在最近的测试课程中,我这样做:

private Product1 _product1;
private Product2 _product2;
private IList<Product> _products;

[SetUp]
public void Setup()
{
    _product1 = new Product();
    _product2 = new Product();
    _product = new List<Product>();
    _products.Add(_product1);
    _products.Add(_product2);
}

Here _product1 , _product2 and _products is used by every test. 每个测试都使用_product1_product2_products Therefore it seems to violate DRY to put them in every method. 因此,将它们放入每种方法似乎违反了DRY。 Should they be put in every test method? 是否应该将它们放在每种测试方法中?

This question is very subjective, but I don't believe it is a code smell. 这个问题是非常主观的,但是我不认为这是代码的味道。 The example in the linked blog post was very arbitrary and did not use the variables setup in every test. 链接的博客文章中的示例非常随意,没有在每个测试中都使用变量设置。 If you look at your code and you are not using the variables from the SetUp , then yes, it is probably a code smell. 如果您查看代码,但没有使用SetUp的变量,那么可以,这可能是代码的味道。

If your tests are grouped well however, then each test fixture will be testing a group of functionality that often needs the same setup. 但是,如果您的测试分组正确,则每个测试装置将测试一组通常需要相同设置的功能。 In this case, the DRY principle wins out in my books. 在这种情况下,DRY原则在我的书中胜出。 James argued in his post that he needed to look in three methods to see the state of the data, but I would counter that too much setup code in a test method obscures the purpose of the test. James在他的文章中辩称,他需要查看三种方法来查看数据状态,但是我认为测试方法中的太多设置代码会掩盖测试的目的。

Copying setup code like you have in your example also makes your tests harder to maintain. 像在示例中一样复制设置代码也使测试难以维护。 If your Product class changes in the future and requires additional construction, then you will need to change it in every test, not in one place. 如果您的Product类别将来会更改并且需要其他构造,那么您将需要在每个测试中而不是在一个地方进行更改。 Adding that much setup code to each test method would also make your test class very long and hard to scan. 在每个测试方法中添加那么多设置代码也将使您的测试类非常长且难以扫描。

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

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