Is it bad form to count on the order of your NUnit unit tests

后端 未结 8 1767
别跟我提以往
别跟我提以往 2021-02-13 06:16

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 cr

相关标签:
8条回答
  • 2021-02-13 06:58

    Look into test fixture setups that allow you to specify functions that will be executed before any of the tests in the fixture. This allows you to do common setup once and it will always run, whether you run one test, or all tests in the suite.

    0 讨论(0)
  • 2021-02-13 06:59

    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.

    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();
        } 
    }
    
    0 讨论(0)
提交回复
热议问题