Story Details for articles
Golf Tracker - Ep. 5 - Service Layer and Unit Tests
8/24/2011 7:49:50 PM
8/24/2011 7:49:50 PM
Golf Tracker - Service Layer and Unit TestsSimilar to the last episode where I built some simple unit tests for the CourseRepository, in this episode I'll test the service layer classes.
Again like previously I have a choice of whether to use a mocking framework like RhinoMocks, Moq, etc., or simply test against a fake repository. And in this case since I'm testing the service layer which isn't directly connected to the data repositories, I can either test the service layer functionality directly, or do what I call "pass-through" testing, which will test against our existing fake repositories. I will be choosing the latter.
Note: when I'm testing against data from a data source such as SQL Server, I prefer to create fake repositories as much as I can to test against. This way I can really see if my queries are working and if my class structures are working. If I'm building an API type of application, I may choose to mock the tests instead. It all depends on the overall scenario.
What I'll do first is create a new class in the UnitTests project for the Course Service tests.
Here's a look at the early version of the service class unit tests.
As you can see these are very simple tests, and they should be. Each unit test should be as small as possible and be written just to the point that it passes.
Each method first instantiates a new CourseService() class and then applies the dependency injection with the GetRepository() method. At this point we can call any of the methods of the service class. At first we want to make sure everything is working as it should so the tests will be very simple, but as I build the application they will most likely get more complex.
At first all the tests should fail since at this point there is no CourseService concrete class. This is good. RED, GREEN, REFACTOR. After running the tests, we can create the class.
This is the default CourseService class with the Dependency Injection property set and the interface members implemented.
Now I can run tests against this class. Needless to say the initial tests will fail since all the methods still contain the NotImplementedException() class. In order to make these tests pass I'll just modify the methods that I need to get working. For the first test it will be the GetAll() method.
Now when I run this test it will pass, as long as the number of records in the fake repository hasn't changed.
For the second test I'll need to modify the GetById() method of the CourseService class.
At this point when I run all tests, they all turn Green!
Stay tuned and in the next episode I'll move up to the presentation layer and begin setting everything up that I need to make the application work the way I need and also help me generate code using tooling such as T4 templates.