I am going to demonstrate the use of a very popular mocking framework, MOQ, to mock the database/service calls.
The example in the article is an Order Processing class, mimicking the order processing system. The business logic in this class is to fetch an order from a database (by order Id), adding 10% GST on the amount, and then saving it back to the database.
To test this business logic, I will be writing a unit test. The unit test will have the Order Id as an input, so it can fetch the order from the DB (as database fetch and save is part of business logic).
However, we have some trouble if we were to write a unit test case…
- If we fetch and assert some predetermined output from a DB, it probably will be successful first time because the second time, the data will be changed.
- DB may or may not be online at the time of the test.
- It is strictly no-no to run this unit test in UAT or Prod environment, as it should not be manipulating the data.
So, the question is do we really need to fetch the data from DB to test business logic? Well, the answer is "No".
For argument (the example I considered) you might want to say, “move the DB operation to separate methods”. Yes, you are absolutely right in this instance, however, my focus is to demonstrate the capability of mocking.
Alright. too much talk; let’s get into some action.
Here is my “OrderProcessing” class. Here I am fetching record from database, calculating total amount by adding 10% GST on the order amount and saving it back to database.
- public class OrderProcessing
- {
- // object responsible for database operation
- DBContext dbContext = new DBContext();
- public Order ProcessGSTForNextOrder(int orderId)
- {
- var nextOrder = dbContext.GetNextOrderDetailFromDB(orderId);
- nextOrder.Amount = CalculateTotalAmountWithGST(nextOrder);
- dbContext.SaveOrder(nextOrder);
- return nextOrder;
- }
- public decimal CalculateTotalAmountWithGST(Order order)
- {
- return order.Amount + (order.Amount * (10 / 100));
- }
- }
The unit test generally looks like this.
- [TestMethod]
- public void TestOrderProcessing()
- {
- var dummyOrderId = 1234;
- OrderProcessing orderProcessing = new OrderProcessing();
- var modifiedOrder = orderProcessing.ProcessGSTForNextOrder(dummyOrderId);
- Assert.IsTrue(modifiedOrder.Amount == 1000);
- }

John CanessaPosted Jan 25, 2023, 10:01 PM
Return order.Amount + (order.Amount * 10 / 100); This statement returns order.Amount. The 10% is not added.
vishal pawarPosted Jul 31, 2020, 7:03 AM
Nice article, but where is actual method we tested?WE re-write the logic in moq class.We cant rewrite logic for all the classes's methods