I use LINQ to Objects and DI.
So let's say I have a service which uses a repository:
public FooService : Service, IFooService
{
private IFooRepository Repository { get; set; }
public GetSpecialFoos()
{
return from f in Repository.SelectAll()
where f.IsSpecial
select f;
}
public FooService(IFooRepository repository)
{
this.Repository = repository;
}
}
Now I can use constructor injection to inject a mock repository for testing. Generally, you'd use a DI framework for this. But the important thing is the mock repository can use LINQ to Objects:
public MockFooRepository : IFooRepository
{
public IList<Foo> Data { get; set; }
public IQueryable<Foo> SelectAll()
{
return Data.AsQueryable();
}
}
Now I can test:
[TestMethod]
public void GetSpecialFoos_returns_only_special_foos()
{
var specialId = 1;
var notSoSpecialId = 2;
var foos = new List<Foo>
{
new Foo
{
Id = specialId,
IsSpecial = true
},
new Foo
{
Id = notSoSpecialId,
IsSpecial = false
}
}
// use a DI framework here instead, in the real world
var repository = new MockFooRepository
{
Data = foos
};
var service = new FooService(repository);
var actual = service.GetSpecialFoos();
var returned = actual.First();
Assert.AreEqual(true, returned.IsSpecial);
Assert.AreEqual(specialId, returned.Id);
}