cheap oakleys replica michael kors bags cheap christian louboutin online elite jerseys wholesale cheap nfl jerseys discount ray bans cheap michael kors cheap ray bans replica oakleys wholesale replica michael kors wholesale oakley sunglasses cheap fake ray bans cheap jerseys china cheap christian louboutin outlet fake cheap oakleys cheap oakleys cheap jerseys sale cheap christian louboutin discount oakleys wholesale nfl jerseys cheap michael kors handbags michael kors handbags discount christian louboutin cheap jerseys michael kors on sale discount ray bans wholesale jerseys cheap michael kors fake oakleys online cheap michael kors bags replica ray bans discount ray bans authentic jerseys cheap christian louboutin cheap oakleys cheap oakleys outlet nfl jerseys red bottoms shoes on sale cheap ray bans cheap nfl jerseys cheap replica oakleys michael kors on sale cheap christian louboutin outlet Cheap Elite Jerseys cheap michael kors cheap ray bans cheap jerseys free shopping cheap fake oakleys cheap oakleys sale cheap michael kors outlet ray bans shop fake cheap oakleys cheap authentic nike jerseys christian louboutin online fake cheap oakleys fake oakleys store cheap jerseys wholesale cheap christian louboutin replica oakleys cheap jerseys wholesale cheap replica oakleys michael kors handbags wholesale jerseys china discount nhl jerseys wholesale replica michael kors cheap ray bans cheap jerseys cheap fake oakleys fake oakleys cheap michael kors store cheap ray bans wholesale oakleys jerseys wholesale christian louboutin outlet cheap mlb jerseys oakley sunglasses authentic jerseys christian louboutin outlet cheap replica oakleys wholesale authentic jerseys wholesale mlb jerseys michael kors handbags cheap jerseys online shopping cheap nhl jerseys michael kors bags cheap fake oakleys cheap jerseys from china cheap fake oakleys 2016 cheap fake oakleys cheap michael kors cheap discount ray bans fake cheap oakleys cheap jerseys free shopping cheap christian louboutin online wholesale nfl jerseys cheap jerseys from china wholesale christian louboutin wholesale mlb jerseys official jerseys fake cheap oakleys cheap michael kors handbags wholesale jerseys cheap wholesale jerseys cheap fake oakleys oakley sunglasses cheap discount oakleys oakleys sunglasses usa cheap michael kors online wholesale and retail oakleys cheap michael kors outlet cheap wholesale jerseys wholesale cheap jerseys china cheap replica oakleys fake oakleys online authentic jerseys wholesale ray bans fake cheap oakleys jerseys wholesale replica ray bans wholesale sunglasses wholesale mlb jerseys cheap cheap nfl jerseys cheap michael kors outlet cheap fake ray bans cheap oakleys sale cheap fake ray bans oakleys sunglasses michael kors bags fake cheap oakleys fake cheap oakleys authentic wholesale jerseys nhl jerseys cheap michael kors outlet cheap oakleys online wholesale jerseys fake ray bans online store michael kors handbags outlet wholesale jerseys china fake ray bans ray bans outlet cheap christian louboutin cheap nba jerseys cheap ray bans cheap ray bans wholesale nfl jerseys wholesale sunglasses michael kors bags outlet cheap ray bans on sale fake cheap oakleys cheap nfl jerseys cheap nhl jerseys cheap oakleys cheap jerseys cheap fake oakleys michael kors outlet cheap jerseys store fake ray bans christian louboutin shoes discount nba jerseys michael kors for sale cheap fake oakleys fake ray bans sunglasses cheap michael kors handbags oakley sunglasses michael kors handbags michael kors on sale fake cheap oakleys cheap nfl jerseys replica oakleys cheap oakleys outlet cheap oakleys cheap authentic nfl jerseys paypal cheap fake oakley sunglasses cheap oakleys cheap jerseys paypal
Writing Database Independent Unit Tests » Inder Singh's Blog
Apr 072013
 

I always heard the terms like loosely-coupled systems, mock objects, database independent unit tests, etc. which sounded nice but they were all abstract concepts for a long time. It was after a many years of work experience that I really grasped them for implementation purpose and realized more meaning than some abstract concepts. In this post I will share my experiences in using all these concepts and write some tests for business logic. The term Unit Testis being loosely used here because these tests might not be unit tests in true sense; they are just automated tests to verify business logic. The concepts explained here might not be anything new but the idea here is to enhance understanding by providing some simple examples. Please note that the example used here is very simple but the same principles can be applied to much more complex scenarios to yield quality code.

The main pre-requisite for unit tests is that there should be some real business logic to test, if your application is basic data entry which writes out the object constructed from form data to database then there is not a whole lot that can be done to make tests database independent. Now, assuming you have some real business logic to test the business classes need to be designed in a certain way to be able to perform some database independent testing.

Let’s start with some ground rules and then we can elaborate using concrete examples:

  • Domain objects which represent business entities are persistence ignorant
  • Repositories used for a persistence related activities
  • Command classes implemented to perform business transaction on business entities

We will design classes for an Order Processing system, assumption is that the Order is already saved to the database (user submitted the order using a web application) and backend job processes these pending orders.
The task at hand is to process the Order and following are the requirements:

  • Order must be in status New or Pending
  • Check Item Inventory to see if Order can be fulfilled
    • If all order items are available then Dispatch Order Message to Warehouse System and update Order Status to Complete
    • Else update Order Status to Pending
  •   public class Order
        {
            public int OrderId { get; set; }
            public DateTime OrderDate { get; set; }
            public List<OrderDetail> OrderDetails { get; set; }
            public string OrderStatus { get; set; }
            public int? OrderDispatchConfirmationNumber { get; set;}
    
            public string ShippingAddress { get; set; }
        }
    
        public class OrderDetail
        {
            public int OrderDetailId { get; set; }
            public int ItemId { get; set; }
            public decimal ItemPrice { get; set; }
            public int Quantity { get; set; }
        }
    
        public class ItemInventory
        {
            public int ItemId { get; set; }
            public int QuantityAvailable { get; set; }
        }
    
    
    
    public interface IOrderRepository
        {
            Order GetByOrderId(int orderId);
            void SaveOrder(Order order);
        }   
    
    
    public interface IWarehouseSystem
        {
            public ItemInventory GetItemInventoryByItemId(int itemId);        
            public int DispatchOrder(Order order);
        }
    
    

    The key to writing database independent tests is to encapsulate the business transaction code like Processing Order into an object. Instead of mixing the business transaction code with the business entity create a class whose sole purpose is to perform the business transaction. In our example, instead of implementing ProcessOrder function in Order class implement a separate class ProcessOrderCommand.

    ProcessOrderComand Data Requirements:

    1. Read Order information
    2. Validate Order is in status New or Pending
    3. Read Item Inventory information
    4. If all the items on the Order are available then
      • Dispatch Order to Warehouse System
      • Update Order to Complete
    5. Else Update Order status to Pending and no further processing needed

    ProcessOrderCommand is implemented to use interfaces for external dependencies (data repository and warehouse system), the result is a loosely couple system where fake implementations can be injected to achieve our goal of database independent tests. Now, let’s implement this class.

    
      public class ProcessOrderCommand
        {
            public IOrderRepository OrderRepository { get; set; } /* External Dependency */
            public IWarehouseSystem WarehouseSystem { get; set; } /* External Dependency */
    
            public int OrderId { get; set; } /* Input Data */
    
            public void ExecuteCommand()
            {
                Order order = this.OrderRepository.GetByOrderId(this.OrderId);
    
                if (order == null)
                    throw new InvalidOperationException("Order not found for OrderId - " + this.OrderId);
    
                if (order.OrderStatus != "Pending" && order.OrderStatus != "New")
                    throw new InvalidOperationException("Order must be in status Pending or New to be processed");
    
                bool orderItemsAvailable = CheckOrderItemAvailability(order);
    
                if (orderItemsAvailable)
                {
                    order.OrderDispatchConfirmationNumber = this.WarehouseSystem.DispatchOrder(order);
                    order.OrderStatus = "Shipped";
                }
                else
                {
                    order.OrderStatus = "Pending";
                }
    
                this.OrderRepository.SaveOrder(order);
            }
    
            private bool CheckOrderItemAvailability(Order order)
            {
    
                foreach (OrderDetail orderDetail in order.OrderDetails)
                {
                    ItemInventory itemInventory = this.WarehouseSystem.GetItemInventoryByItemId(orderDetail.ItemId);
                    if (itemInventory == null || itemInventory.QuantityAvailable < orderDetail.Quantity)
                        return false;
                }
    
                return true;
            }
        }
    

    ProcessOrderCommand relies on interfaces so we can setup a mock OrderRepository to return an Order object in status Complete and then try to execute the command. The expected result is an exception and a unit test can be written to verify this validation rule. Since, we can use a mock implementation of IOrderRepository to return an Order in status Complete there is no need to create Order records in database to be able to test such logic. Hence, we have achieved our goal of writing database independent unit tests!

    Following are examples for Mock implementations:

    
      public class MockOrderRepository : IOrderRepository
        {
            public Order GetByOrderId(int orderId)
            {
                Order order = null;
    
                if (orderId == 1) ///New Order
                {
                    order = new Order { OrderId = 1, OrderDate = DateTime.Now, OrderStatus = "New", ShippingAddress = "45 University Ave, Minneapolis MN 55890" };
                    order.OrderDetails = new List<OrderDetail>();
                    order.OrderDetails.Add(new OrderDetail() { OrderDetailId = 100, ItemId = 1, ItemPrice = 50, Quantity = 10 });
                }
                else if (orderId == 2)
                {
                    order = new Order { OrderId = 2, OrderDate = DateTime.Now, OrderStatus = "Pending", ShippingAddress = "45 University Ave, Minneapolis MN 55890" };
                    order.OrderDetails = new List<OrderDetail>();
                    order.OrderDetails.Add(new OrderDetail() { OrderDetailId = 110, ItemId = 2, ItemPrice = 10, Quantity = 50 });
                }
                else if (orderId == 3) //Complete Order
                {
                    order = new Order { OrderId = 3, OrderDate = DateTime.Now, OrderStatus = "Complete", ShippingAddress = "45 University Ave, Minneapolis MN 55890" };
                    order.OrderDetails = new List<OrderDetail>();
                    order.OrderDetails.Add(new OrderDetail() { OrderDetailId = 200, ItemId = 6, ItemPrice = 50, Quantity = 10 });
                }            
    
    
                return order;
            }
    
            public void SaveOrder(Order order)
            {
              //Does Nothing - Simulate Order saved successfully
            }
        }
    
        public class MockWarehouseSystem : IWarehouseSystem
        {
    
            public ItemInventory GetItemInventoryByItemId(int itemId)
            {
                if (itemId == 1)
                    return new ItemInventory() { ItemId = 1, QuantityAvailable = 500 };
                else if (itemId == 3)
                    return new ItemInventory() { ItemId = 3, QuantityAvailable = 10 };
                else if (itemId == 6)
                    return new ItemInventory() { ItemId = 6, QuantityAvailable = 100 };
                else
                    return null;
                    
            }
    
            public int DispatchOrder(Order order)
            {
                //Does Nothing - Simulates successful Order Dispatch
                return (new Random()).Next();
            }
        }
    
    

    It might be quite a bit of coding effort to write the mock implementation and that’s where Mocking frameworks come into play. In another post, I will describe how to use a Mocking Framework (Moq) to setup mock implementations of IOrderRepository and IWarehouseRepository. Using the mocking framework we will be able to write even more extensive tests but for now the following would suffice.

    
    [TestMethod]
           public void InvalidOrderIdTest()
           {
               int invalidOrderId = 10;
    
               ProcessOrderCommand processOrderCommand = new ProcessOrderCommand();
               processOrderCommand.OrderRepository = new MockOrderRepository();
               processOrderCommand.WarehouseSystem = new MockWarehouseSystem();
               processOrderCommand.OrderId = invalidOrderId;
    
               try
               {
                   processOrderCommand.ExecuteCommand();
                   Assert.Fail("ProcessOrderCommand expected to throw an exception for invalid OrderId");
               }
               catch (Exception ex)
               {
                   Assert.IsTrue(ex.Message == "Order not found for OrderId - " + invalidOrderId, "Expected Exception Message not found for Invalid OrderId");
               }
           }
    
            [TestMethod]
            public void InvalidOrderStatusTest()
            {
                int completeOrderid = 3;
    
                ProcessOrderCommand processOrderCommand = new ProcessOrderCommand();
                processOrderCommand.OrderRepository = new MockOrderRepository();
                processOrderCommand.WarehouseSystem = new MockWarehouseSystem();
                processOrderCommand.OrderId = completeOrderid;
    
                try
                {
                    processOrderCommand.ExecuteCommand();
    
                    Assert.Fail("ProcessOrderCommand expected to throw an exception for invalid OrderId");
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(ex.Message == "Order must be in status Pending or New to be processed", "Expected Exception Message not found for Complete Order");
                }
            }
    

    Note: Performing string comparison in the unit tests might not be a good idea, I did not want to add more code to this post that’s why I have resorted to string comparison but in real world applications you might want to define an enumeration with all possible error conditions and throw a custom exception which has a property of error condition enumeration type. Then your tests can compare against the Enumeration.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>