I'm using LINQ-to-SQL
with ASP.NET MVC 4, and as of this moment I have a repository layer which contacts a real database. This is not very good when I want to unit test.
Also there should never be a logic in the repository layer, so this is why I want to mock the LINQ DataContext
so I can create a service layer that talks either to the mock DataContext
or to the real DataContext
.
I see that my LINQ DataContext class inherits DataContext
, but there is no interface, so I can't really mock that. I also see that DataContext uses Table<>
class and there exists an interface ITable
, so I probably could mock that. Also my LINQ DataContext
is a partial class, so maybe I could manipulate that in some kind of way?
When I google this, all articles are from 2008 and are outdated. Can anyone guide me in the right appropriate direction?
Here is an example of what I want to do. I will have seperate service class for each controller.
public class MyServiceClass
{
IDataContext _context;
// Constructors with dependency injection
public MyServiceClass()
{
_context = new MyRealDataContext();
}
public MyServiceClass(IDataContext ctx)
{
_context = ctx;
}
// Service functions
public IEnumerable<ModelClass> GetAll()
{
return _context.ModelClass;
}
public ModelClass GetOne(int id)
{
return _context.Where(s => s.ID == id).SingleOrDefault();
}
}