在遺留程式使用extract and override

單元測試

稍微記錄一下平常使用Extract and Override的技巧

這一支程式是一個帳單進行付款的行為,但要先進行客戶的資料基本檢驗,但是相依了Customer,要如何測試這一段程式碼, 因為原始程式碼相依耦合性依賴相當高,這會讓測試不好測試,最好的方式就是重構成Interface,但現實專案當中確實很難, 除非要有那個美國時間,讓你搞到好的設計。
在專案頻繁的功能再追加,可以考慮用Extract and Override技巧。


    public class Bill
    {
        Customer customer = new Customer();
        public bool Pay()
        {
            return customer.Validation();   
        }

    }
    public class Customer
    {
           
        public int Id { get; set; }

        public string Name { get; set; }

        public int Amt { get; set; }

        public bool Validation()
        {
            if (string.IsNullOrEmpty(Name)) 
            {
                return false;
            }
            if (Amt <= 0)
            {
                return false;
            }

            return true;
        }
    }

第二步提取方法並複寫,先加入Validation,並改Pay調用Validation()


    public class Bill
    {
        Customer customer = new Customer();
        public bool Pay()
        {
            return Validation();   
        }
        public virtual bool Validation()
        {
            return customer.Validation();
        }
    }
    public class Customer
    {
           
        public int Id { get; set; }

        public string Name { get; set; }

        public int Amt { get; set; }

        public bool Validation()
        {
            if (string.IsNullOrEmpty(Name)) 
            {
                return false;
            }
            if (Amt <= 0)
            {
                return false;
            }

            return true;
        }
    }

第三步加入單元測試,開始加入付款成功與付款失敗的案例。


    public class PayTests
    {
     
        [Test]
        public void Pay_Success_ReturnTrue()
        {
            var subBill = new StubBill();
            subBill.status = true;
            Assert.IsTrue(subBill.Pay());
        }
        [Test]
        public void Pay_Fail_ReturnFalse()
        {
            var subBill = new StubBill();
            subBill.status = false;
            Assert.IsFalse(subBill.Pay());
        }
        public class StubBill : Bill
        {
            public bool status = true;
            protected override bool Validation()
            {
                return status;
            }
        }
    }

比較好的方式,透過Interface,使用注入的方式和模擬框架的部分,來進行測試。

老E隨手寫