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.
Piotr Grześkowiak has been at Automation Logic for just over five years, starting out in our DevOps Academy after graduating in Computer Science with Information Security. During those 5 years, he’s gone from an engineer in training to a well respected senior engineer, trusted by the whole company. Piotr’s been on three Central Government client […]
We interviewed AL’s co-founders Kris & Norm about their journey building Automation Logic into the business it is over the last 12 years. From the values they’ve set in place, to the struggles they’ve faced. And obviously, because it’s pretty difficult not to mention it these days, the impact covid had.
A memoir of a Workload Migration engineer by Liam Rae-McLauchlan We’ve all read the blogs and articles about migrating to the Cloud and its benefits, but in practice it can be a daunting task. Maybe your organisation is planning to move to the cloud, or is already trying – up to 85% of enterprises are […]