In my previous post I explained the basics of test driven development (TDD) and what advantages it can bring. In this post, I will give you an example of using test driven development with the MVC4 .NET and entity framework (EF). This framework helps the developer by splitting the system into 3 different types of components with well defined responsibilities. This is known as the model-view-controller design pattern:
The model handles the application data, part of it can be automatically generated using the EF to reflect your database schema. The view renders what the user actually sees and can contain information from the model. The controllers are the intermediate between the model and the view, they handle user interaction, and contain most of the business logic.
Because the logic in the controllers is typically more complex they should always have thorough unit tests. So we’ll use a controller as an example.
Any useful controllers would be using the model data. However to unit test them we need to break this dependency, otherwise the tests will have to read and write data from a database in order to run.
Say we are using an EF generated model and we are implementing MyController as a class that provides a RESTful service. This for example could look like:
public class MyController: ApiController{ Entities entities=new Entities(); // That is EF generated Model public string Get(){ //do stuff on entities //return a string } }
This class is dependant on an Entities class. To break this dependency we want to instead pass it in as constructor parameter. This technique is known as Dependency Injection. Our class would look like:
public class MyController: ApiController{ Entities entities; public MyController():this(new Entities()){} public MyController(Entities entites){ this.entites=entities; } public string Get(){ //do stuff on entities //return a string } }
The next thing to consider is that Entities is an implemented class. So, what we’ve done so far does not help at all because we are still depending on this particular class. The solution is to inject a mock object to isolate the controller for our unit tests. The next step would be to extract the interface of this class and pass it as parameter so that we can mock it.
However, as Entities is automatically generated it is probably wiser to implement a repository class to abstract away data persistence. This means we won’t have to change our implementation if we change the data model in the future. For example:
public class MyController: ApiController{ IRepository repository; public MyController():this(new Repository()){}//our implementation is default public MyController(IRepository repository){ this.repository=repository; } public string Get(){ /// }
Now our controller is ready to test!
For this example I have used the Moq framework (https://github.com/Moq/moq4/wiki/Quickstart ). Our unit test would look like:
[TestMethod] public void CertainScenarioShouldPass(){ var mock_repo= new Mock(); //setup what we want the repo to return var someStuff=new Stuff(); mock_repo.Setup(x=>x.getMyStuff()).Returns(someStuff); MyController controller= new MyController(mock_repo.Object); //we are using rest api so we need to mock up some url var controllerReturn=controller.Get(); Assert.Equal(“myStuff”,controllerReturn); }
Finally you can run the test and see that it passes. I hope that example helps show how to get started with TDD in .NET. Feel free to get in touch in the comments if you have any questions.
We work with our clients to de-risk and accelerate their business goals realisation. Our approach is based on tailoring our services to fit your needs leveraging our portfolio of strategy, execution, innovation and service delivery offerings to help you reach your objectives
We’re always on the lookout for exceptional talent and people who share our values. Even as we continue to grow, we maintain a family environment with respect and teamwork core to our culture.
Companies can start deploying containerised workloads to Kubernetes In days not months, by leveraging Automation Logic’s Kubernetes Platform Accelerator.
Largest Irish-Founded Tech Employer Surpasses 3000 Employees Signing 15th and 16th Acquisition Deals Version 1, a leading digital transformation partner, is to acquire Automation Logic – for an undisclosed sum as part of its ambitious growth strategy for 2023 and beyond. The Automation Logic deal is subject to clearance by the National Security and Investment […]
Automation Logic were recognised as one of the UK’s best Workplaces again for the 5th year running! We also placed 29th in best workplaces for women. This highlights the great work that we are doing as a business, including all the wonderful work being put in by the employee-led DE&I groups. This award means so […]