How to Write Testable Code in .NET

Introduction

 
In this article, I give a brief introduction to writing testable code. Although I have described and used samples in the context of .NET, the high-level principles of writing testable code applies to most of the programming language.  
 

What is Testable Code?

 
Testable code refers to the loosely coupled code where code does not directly depend on internal/external dependencies, so we can easily replace the real dependencies (sometimes referred to as real service) with mock services in test cases. For example, if my code calls a method GetProductInfo() which is connecting to a real database, fetching the product information, and returning to the main method. To test my main method functionality without actually connecting to the real database, I can write a test that uses a mock service to get product data.
 
While it might seem a little confusing at this point, it is actually very simple when you see a working example of it.
 

Why is it important to write testable code?

 
Writing testable code is crucial, as it helps you to identify and resolve the potential problems/ bugs in the early development stage instead of getting issues in UAT or production when working with real services. Also, testing the fake services is fast compared to testing real services. For example, connecting to a real database is more time consuming than testing with fake data in mock service.
 

How to write testable code

 
Writing testable code is all about dependency management. If we are writing code using the SOLID principles, then our code will already be loosely coupled and in compliance with testing standards. While writing testable code, our main objective is to identify the dependencies and moving the instantiation of those dependencies outside of our code. When we create an object of the class using a new keyword inside the current class, then this class directly depends on the class whose object we are creating. For example, in the below code ProcessProduct class creating the object of DBService class. Hence DBService class is the dependency and ProcessProduct class depends directly on DBService.
  1. class Product  
  2.     {  
  3.         public int Id { getset; }  
  4.         public string Name { getset; }  
  5.         public string Category { getset; }  
  6.         public float Price { getset; }  
  7.   
  8.     }  
  9.     class ProcessProduct  
  10.     {  
  11.         public void DisplayProduct()  
  12.         {  
  13.             DBService dbService = new DBService();  
  14.             var product = dBService.getProduct();  
  15.             Console.WriteLine($" Product Name: { product.Name } Category: { product.Category } Price: { product.Price }");  
  16.         }  
  17.           
  18.     }  
  19.   
  20.     class DBService  
  21.     {  
  22.         public Product getProduct() {  
  23.             throw new NotImplementedException("Get product from database");  
  24.         }  
  25.     }  
To make this code loosely coupled, we will use a very popular design pattern called dependency injection. There are several ways to implement dependency injection which is itself a very wide topic. So to keep this article simple, I will use one of the ways to implement dependency injection-  Dependency injection using Constructor.
 
In this method, instead of creating the object of DBService inside ProcessProduct, we will inject the object through the constructor of the dependent class and save it in a private variable as shown in the below code:
  1. class Product  
  2. {  
  3.     public int Id { getset; }  
  4.     public string Name { getset; }  
  5.     public string Category { getset; }  
  6.     public float Price { getset; }  
  7.   
  8. }  
  9. class ProcessProduct  
  10. {  
  11.     private IDBservice _dbService;  
  12.   
  13.     public ProcessProduct(IDBservice dbService)  
  14.     {  
  15.         _dbService = dbService;  
  16.     }  
  17.     public void DisplayProduct()  
  18.     {  
  19.         var product = _dbService.getProduct();  
  20.         Console.WriteLine($" Product Name: { product.Name } Category: { product.Category } Price: { product.Price }");  
  21.     }  
  22.       
  23. }  
  24.   
  25. interface IDBservice {  
  26.      Product getProduct();  
  27. }  
  28.   
  29. class DBService : IDBservice  
  30. {  
  31.     public Product getProduct() {  
  32.         throw new NotImplementedException("Get product from database");  
  33.     }  
  34. }  
We have also created an interface IDBService in the above example and declared the object of DBService using this interface. By using this interface, we allow any class’object that implements the IDBService interface to inject through the constructor.
 
Below is an example of passing a mock class object for testing.
  1. class ProcessProduct  
  2.     {  
  3.         private IDBservice _dbService;  
  4.   
  5.         public ProcessProduct(IDBservice dbService)  
  6.         {  
  7.             _dbService = dbService;  
  8.         }  
  9.         public void DisplayProduct()  
  10.         {  
  11.             var product = _dbService.getProduct();  
  12.             Console.WriteLine($" Product Name: { product.Name } Category: { product.Category } Price:  { product.Price }");  
  13.         }  
  14.   
  15.     }  
  16.   
  17.     interface IDBservice {  
  18.         Product getProduct();  
  19.     }  
  20.   
  21.     class MockDBService : IDBservice  
  22.     {  
  23.         public Product getProduct()  
  24.         {  
  25.             return new Product()  
  26.             {  
  27.                 Id = 2124,  
  28.                 Name = "Eggs",  
  29.                 Category = "Food",  
  30.                 Price = 2.23m  
  31.             };  
  32.   
  33.         }  
  34.   
  35.     }  
  36.   
  37.     class TestProcessProduct  
  38.     {  
  39.         void Test()  
  40.         {  
  41.             ProcessProduct processProduct = new ProcessProduct(new MockDBService());  
  42.             processProduct.DisplayProduct();  
  43.         }  
  44.     }  
In this example, we want to test the ProcessProduct class to display product information without actually connecting to the real database. To achieve this, instead of injecting the DBService class object we are injecting the MockDBService class object. And because of dependency injection, we do not need to do any changes in the ProcessProduct class. Hence, this code is loosely coupled and testable.
 

Conclusion

 
In this article, I have explained the fundamentals of writing testable code with a simple example. The real-life projects might include many dependencies and it is difficult to manage them. So in those cases, we want to use some Dependency Injection Containers like “Unity Container” to create and resolve dependencies. Also writing mock cases can be cumbersome, so instead, we can use frameworks to write mock services.
 
Thanks for reading!


Similar Articles