Useful design patterns for unit testing/TDD?

后端 未结 9 786
一个人的身影
一个人的身影 2021-01-29 17:54

Reading this question has helped me solidify some of the problems I\'ve always had with unit-testing, TDD, et al.

Since coming across the TDD approach to development I k

9条回答
  •  梦谈多话
    2021-01-29 18:36

    Arrange, Act, Assert is a good example of a pattern that helps you structure your testing code around particular use cases.

    Here's some hypothetical C# code that demonstrates the pattern.

    [TestFixture]
    public class TestSomeUseCases() {
    
        // Service we want to test
        private TestableServiceImplementation service;
    
        // IoC-injected mock of service that's needed for TestableServiceImplementation
        private Mock dependencyMock;
    
        public void Arrange() {
            // Create a mock of auxiliary service
            dependencyMock = new Mock();
            dependencyMock.Setup(s => s.GetFirstNumber(It.IsAny)).Return(1);
    
            // Create a tested service and inject the mock instance
            service = new TestableServiceImplementation(dependencyMock.Object);
        }
    
        public void Act() {
            service.ProcessFirstNumber();
        }
    
        [SetUp]
        public void Setup() {
            Arrange();
            Act();
        }
    
        [Test]
        public void Assert_That_First_Number_Was_Processed() {
            dependencyMock.Verify(d => d.GetFirstNumber(It.IsAny()), Times.Exactly(1));
        }
    }
    

    If you have a lot of scenarios to test, you can extract a common abstract class with concrete Arrange & Act bits (or just Arrange) and implement the remaining abstract bits & test functions in the inherited classes that group test functions.

提交回复
热议问题