依靠 NUnit 单元测试的顺序是不好的形式吗 [英] Is it bad form to count on the order of your NUnit unit tests

查看:34
本文介绍了依靠 NUnit 单元测试的顺序是不好的形式吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在疯狂地创建单元测试,并发现我经常不得不在一个测试中设置一些我刚刚在之前的测试中删除的内容.在一次测试(例如插入测试)中创建某些内容(例如数据库记录)然后将其用于以后的测试(例如删除测试)是否合理?还是每个测试都应该完全独立?

I have been creating Unit tests like crazy and find that I'm often having to set up something in one test that I just tore down in a previous test. Is it ever reasonable to create something (e.g. a database record) in one test (e.g. an Insertion test) and then use it for a later test (e.g. a Deletion test)? Or should each and every test always stand completely on its own?

您甚至可以确定 NUnit 中的测试顺序还是总是按字母顺序进行?

Can you even determine the order of tests in NUnit or are they always done alphabetically?

注意:我特别询问一个测试文件中的测试顺序.不是跨测试文件或更全局的任何方式.

Note: I am specifically asking about the order of tests within one test file. Not across test files or in any way more globally.

更新:感谢所有回答的人 - 很多 很好的答案,并且小组的感觉非常一致.我选择了 John Nolan 的答案,因为他提供了最完整的解释和大量链接.正如您可能已经猜到的那样,尽管我认为它可能像约翰所说的那样有点臭",但我还是非常想打破这条规则.还要感谢 Fortyrunner 添加unit-testing 标签.

Update: Thanks to everyone that answered - there were a lot of good answers and the sense of the group is pretty unanimous. I've chosen John Nolan's answer as he provided the most complete explanation and lots of links. As you may have guessed, I've been sorely tempted to break this rule despite thinking that it might be a bit "smelly" as John put it. Thanks also to Fortyrunner for adding the unit-testing tag.

推荐答案

依赖于您的测试顺序表明您正在跨测试保持状态.这是

Relying on the order of your tests indicates that you are persisting state across tests. This is smelly

更简洁的测试方式是您只依赖要检查其行为的单个功能.通常,您模拟使您的方法在测试中起作用所需的其他对象.

A cleaner way of testing is where you only depend on the single piece of functionality you want to check the behaviour of. Commonly you mock the other objects you need to get your method under test to function.

考虑进行单元测试的一个好方法是 安排、行动、断言模式.

A good way to think about approaching unit tests is the Arrange, Act, Assert pattern.

以下是 Karl Seguin 出色的免费电子书.我已经注释了排列、执行和断言.

Below is a snippet from Karl Seguin's excellent free eBook. I've annoted Arrange, Act and Assert.

[TestFixture] public class CarTest 
{ 
    [Test] public void SaveCarCallsUpdateWhenAlreadyExistingCar()   
    {
         //Arrange
         MockRepository mocks = new MockRepository();
         IDataAccess dataAccess = mocks.CreateMock<IDataAccess>();   
         ObjectFactory.InjectStub(typeof(IDataAccess), dataAccess); 
         //Act
         Car car = new Car(); 
         Expect.Call(dataAccess.Save(car)).Return(389); 
         mocks.ReplayAll(); 
         car.Save(); 
         mocks.VerifyAll(); 
         // Assert
         Assert.AreEqual(389, car.Id); 
         ObjectFactory.ResetDefaults();
    } 
}

这篇关于依靠 NUnit 单元测试的顺序是不好的形式吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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