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

后端 未结 8 1756
别跟我提以往
别跟我提以往 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: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();   
             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();
        } 
    }
    

提交回复
热议问题