單元測試-虛設常式

單元測試

 

外部依賴(external dependency)是指系統中的一個物件,它與被測試程式碼互動,但你
卻無法掌握。

(EX:常見外部依賴:執行緒、記憶體、時間),上述提到ExpectedBehavior的其中一種(系統狀態改變)。

虛設常式(stub)是系統中產生一個可控的替代物件,來取代一個外部相依物件

註記:在測試程式中裡面,透過虛設常式來避免直接相依物件造成的問題。只做模擬相依物件行為

接者開始實作,首先我定義Order Interface出來,因為在旅遊系統當中,常常會調用別人家API或是物件

EX:自由行,會呼叫訂房平台與機票平台

範例一,如果今天我訂房平台要跟模擬出agoda 訂單檢驗的物件

    public interface IOrder
    {
        bool IsValid(string orderNo, string guestName);
    }

    public class BookingOrder : IOrder
    {
        public bool IsValid(string orderNo, string guestName)
        {
            return true;
        }
    }

    public class StubOrder : IOrder
    {
        public bool IsValid(string orderNo, string guestName)
        {
            return true;
        }
    }
    public class Order
    {
        private IOrder _iOrder;

        public Order(IOrder iOrder)
        {
            _iOrder = iOrder;
        }

        public bool IsCheckValid(string orderNo, string guestName)
        {
            return _iOrder.IsValid(orderNo, guestName);
        }
    }

開始編寫Test Method
 

    [TestFixture]
    public class OrderTest
    {
        [Test]
        public void IsValidOrder()
        {
            IOrder iorder = new StubOrder();
            Order agodaOrder = new Order(iorder);
            bool result = agodaOrder.IsCheckValid("20180120001", "旅客E先生");
            Assert.IsTrue(result);
        }
    }

範例二:加入分層架構的概念進行假物件

    public interface IProductRepository
    {
        string GetByName(string productId);
    }

    public class ProductRepository : IProductRepository
    {
        public string GetByName(string productId) => "";
    }

    public class StubProductRepository : IProductRepository
    {
        public string GetByName(string productId) => "16 GB隨身碟";
    }
    public class ProductService
    {
        private readonly IProductRepository _productRepository;

        public ProductService(IProductRepository productRepository)
            => _productRepository = productRepository;

        public string GetProductName(string productId)
            => _productRepository.GetByName(productId);

         
    }
        [Test]
        public void GetProductName()
        {
            IProductRepository stubProductRepository = new StubProductRepository();
            ProductService productService = new ProductService(stubProductRepository);
            Assert.AreEqual("16 GB隨身碟", productService.GetProductName("1000"));
        }

這種利用實現假物件的技術,專案裡有太多這種為了測試而寫的類別,將來可能不好維護

元哥的筆記