Simplify Automation Unit Testing Using IOC And MOQ

Introduction

A few years ago, I got an opportunity to work on a project, which needed a migration from Web form to MVC and I was assigned a task to come up with a good testing approach to test the site. Afterwards, I worked with various companies, but I found an approach and I helped them to simplify the unit testing, using the same approach. It may be helpful to you also, as I would like to know what you think about it.

The example code is in very simple form and you can improvise it as, per your requirement. it is available at https://github.com/vicharemakrand/SampleCode-Testing

Background

You should have knowledge of the following.

  • MOQ
  • IOC – e.g. Structure map is used in the example.
  • Unit Testing Framework – e.g. MS unit / Nunit / Xunit.
  • Nbuilder is for generating mock data.

Take Away

  • Using IOC to create mock objects.
  • Maintain the test cases with less efforts.
  • Helps to maintain uniformity in the code, which is very useful in scrum based projects.

Drawbacks of Traditional approach

  • Lots of repeated code, where we mock the dependencies.
  • Need efforts to keep the test cases up to date.
  • It may lead to losing focus on testing business cases properly.

About the approach

Instead of mocking each method for each test and deciding the output, we will be using in- memory databases, which will be generated, using Nbuilder and the dependencies will be handled by an IOC.

Also, we don’t use mock Service layer method, using the MOQ but we use all the methods, as it is to call repository layer, which is mocked to use in the memory database.

Let’s start from the bottom up. The sample code covers User table, which is available on GitHub at https://github.com/vicharemakrand/SampleCode-Testing

Code Explanation

  1. In-memory mock database
    We need mock data for each entity model, which is mapped to a database table.

    • Create some mock records for the user table.
      1. namespace SampleCode.IOC.Test.MockTestData {  
      2.     public class UserModelTestData {  
      3.         public static List < UserModel > GetTestRecords() {  
      4.             return Builder < UserModel > .CreateListOfSize(10).Build().ToList();  
      5.         }  
      6.     }  
      7. }  
    • Create a class to store the mock records in a collection
      1. public static class MockEntities {  
      2.     public static Dictionary < string, dynamic > MockData = new Dictionary < string, dynamic > ();  
      3.     public static void LoadData() {  
      4.         MockData.Add(typeof(UserModel).Name, UserModelTestData.GetTestRecords());  
      5.     }  
      6.     public static List < T > GetData < T > () where T: class {  
      7.         return (List < T > ) MockData[typeof(T).Name];  
      8.     }  
      9. }  
  2. Create a mock repository object using MOQ
    Here, we set up repository methods but instead of hardcoding the sresult, we do actual simple operation related to the methods. This approach is the same with lots of duplicate code and maintenance efforts.
    1. namespace SampleCode.IOC.Test {  
    2.     public static class MockRepositoryGenerator < Model > where Model: BaseModel {  
    3.         private static List < Model > DummyTable {  
    4.             get {  
    5.                 return MockEntities.GetData < Model > ();  
    6.             }  
    7.         }  
    8.         public static T RepositoryMock < T > () where T: class, IBaseRepository < Model > {  
    9.             Mock < T > repository = new Mock < T > (MockBehavior.Strict);  
    10.             repository.Setup(o => o.Get(It.IsAny < Expression < Func < Model, bool >>> ())).Returns((Expression < Func < Model, bool >> i) => DummyTable.Where(i.Compile()).FirstOrDefault());  
    11.             return repository.Object;  
    12.         }  
    13.     }  
    14. }  
  3. IOC - interface and class mapping
    Here, we map interfaces with the generated mock objects, which also stores mockdata with them
    1. class StructureMapTestRegistry: Registry {  
    2.     / <summary> /  
    3.     Initializes a new instance of the < see cref = "DependencyConfigurationRegistry" / > class. / < /summary>  
    4.     public StructureMapTestRegistry() {  
    5.         MockEntities.LoadData();  
    6.         For < IUserRepository > ().Use(MockRepositoryGenerator < UserModel > .RepositoryMock < IUserRepository > ());  
    7.         For < IUnitOfWork > ().Use(MockGenerator.UnitOfWorkMock());  
    8.         For < IDataContext > ().Use(MockGenerator.DataContextMock());  
    9.     }  
    10. }  
  4. Create IOC container for test project.
    1. public static class TestBootstrapper {  
    2.     public static void TestConfigureStructureMap() {  
    3.         ObjectFactory.Container.Dispose();  
    4.         ObjectFactory.Initialize(o => o.AddRegistry(new StructureMapTestRegistry()));  
    5.         ObjectFactory.Container.AssertConfigurationIsValid();  
    6.     }  
    7. }  
  5. Now writing test cases will be quite simpler

    1. Test cases for Service layer are shown below.
      1. [TestClass]  
      2. public class UserServiceTest {  
      3.     private IUserService domainService;  
      4.     / <summary> / Initialize() is called once during test execution before / test methods in this test class are executed. / < /summary> [TestInitialize]  
      5.     public void Initialize() {  
      6.             TestBootstrapper.TestConfigureStructureMap();  
      7.             AutoMapperInit.BuildMap();  
      8.             domainService = ObjectFactory.GetInstance < IUserService > ();  
      9.             domainService.UserRepository = ObjectFactory.GetInstance < IUserRepository > ();  
      10.             domainService.UnitOfWork = ObjectFactory.GetInstance < IUnitOfWork > ();  
      11.         }  
      12.         [TestMethod]  
      13.     public void Save_AddNewUser_returnsSaveUser() {  
      14.             var response = domainService.Save(new UserViewModel() {  
      15.                 Id = 0, FirstName = "Mak11", LastName = "Vichare11"  
      16.             });  
      17.             Assert.AreEqual("Vichare11", response.ViewModel.LastName);  
      18.         }  
      19.         [TestMethod]  
      20.     public void Save_UpdateExistingUser_returnsSaveUser() {  
      21.         var response = domainService.GetById(5);  
      22.         response.ViewModel.FirstName = "Makrand";  
      23.         var newResponse = domainService.Save(response.ViewModel);  
      24.         Assert.AreEqual(response.ViewModel.FirstName, newResponse.ViewModel.FirstName);  
      25.     }  
      26. }  
    2. Test cases for Repository layer are shown below.
      1. [TestClass]  
      2. public class UserRepositoryTest {  
      3.     private IUserRepository repository;  
      4.     [TestInitialize]  
      5.     public void Initialize() {  
      6.             TestBootstrapper.TestConfigureStructureMap();  
      7.             repository = ObjectFactory.GetInstance < IUserRepository > ();  
      8.         }  
      9.         [TestMethod]  
      10.     public void Add_AddNewUser_returnsSaveUser() {  
      11.             var model = repository.Add(new UserModel() {  
      12.                 Id = 11, FirstName = "Mak", LastName = "Vichare"  
      13.             });  
      14.             Assert.AreEqual("Vichare", model.LastName);  
      15.         }  
      16.         [TestMethod]  
      17.     public void Update_UpdateExistingUser_returnsSaveUser() {  
      18.         var oldModel = repository.GetById(5);  
      19.         oldModel.FirstName = "Makrand";  
      20.         var model = repository.Update(oldModel);  
      21.         Assert.AreEqual(oldModel.FirstName, model.FirstName);  
      22.     }  
      23. }  
    3. MVC controller Test cases are shown below.
      1. [TestClass]  
      2. public class UserControllerTest {  
      3.     private UserController userController;  
      4.     IUserService userService;  
      5.     [TestInitialize]  
      6.     public void Initialize() {  
      7.             userService = ObjectFactory.GetInstance < IUserService > ();  
      8.             userController = new UserController(userService);  
      9.             MockControllerHelpers.RegisterTestRoutes();  
      10.         }  
      11.         [TestMethod]  
      12.     public void Edit_updates_the_object_and_returns_a_JsonResult_containing_the_redirect_URL() {  
      13.         Arrange  
      14.         userController.SetMockController("~/User/Edit");  
      15.         Act  
      16.         var result = userController.Edit(1);  
      17.         Assert  
      18.         Assert.IsInstanceOfType(result, typeof(JsonResult));  
      19.     }  
      20. }  

Final Thought

In the real project, this approach can be implemented in various ways. You don't have to implement it completely. If you don't agree with this approach 100%, then also you can pick up a few things like, using IOC for the creation of mock objects or repository layer test cases.

Let me know what you think and suggest about this style.