I have a model which contains a link to sql query that fetches information from my db then I loop it out in my view which renders a partial with the resultset in a table. Quite simple and straightforward. Although as I’m really struggling to get better at doing TDD I want to have a test for this. Bare in mind that if you find a test that forces me to rethink my design that’s just fine. Tests should help you see flaws in your designpatterns. I will post some of the code below of my model, and partial:
public class ApplicationModel
{
public static DeployEntities DeployEntities = new DeployEntities();
public static IQueryable<Application> GetApplicationList()
{
var applications = DeployEntities.Applications.OrderByDescending(a => a.Name);
return applications.AsQueryable<Application>().Distinct();
}
}
@{
foreach (var a in Deploy.Models.ApplicationModel.GetApplicationList())
{
<tr id="applications">
<td class="row-heading">
<p class="pseudo">@a.Name</p>
</td>
<td class="insert-col">
<div class="number-insert">
<p>Deploy Number</p>
<span class="count"></span>
</div>
So any thoughts on how I could go about with a test for this. I’m using MVC3 as you can see from the Razor syntax, and Entity Framework. Thanks in advance.
The following line ruins your model:
A static hardcoded dependency => impossible to unit test your model in isolation.
In order to weaken the coupling between your DAL and model you could introduce an abstraction:
and then your model could use constructor injection:
Now in a unit test you could use a mocking framework such as Rhino Mocks or Moq to mock this repository and set expectations on it and be able to unit test the GetApplicationList method in isolation.