Lets say you have 2 layer solution
MyApp.Web
MyApp.Data
In your Data layer you will have something like this:
public class ProductsRepository : IProductsRepository
{
public List<Product> GetAll()
{
//EF stuff
return _dbcontext.Products;
}
}
where IProductsRepository is
public interface IProductsRepository
{
List<Product> GetAll();
}
In the MyApp.Web the trend is to do this.
public class ProductsController : Controller
{
private readonly IProductsRepository _productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
_productsRepository = productsRepository;
}
public ActionResult Index(int page=1)
{
var allProducts = _productsRepository.GetAll();
return View(allProducts)
}
}
Who puts in ProductsRepository into the constructor at runtime? People use Dependency injection like Ninject frameworks for this. But why? Because this enables them to fake the ProductsRepository and like this
public class FakeProductsRepository : IProductsRepository
{
public List<Product> GetAll()
{
return new List<Product>
{
new Product { Name = "PASTE" }
new Product { Name = "BRUSH" }
},
}
}
and then UNIT TEST the controller like this
[TestMethod]
public void IndexGetsAllProducts()
{
//Arrange
var fakeProductRepo = new FakeProductsRepository();
var productsController = new ProductsController(fakeProductRepo);
//Act
var result = productsController.Index(1) as ViewResult;
//Assert
var model = result.Model as List<Product>;
Assert.AreEqual(2, model.Count);
}
Essentially you are faking the database so the unit test is fast and independent of the database. Sometimes for faking people use a mocking framework like Moq, which essentially does the same thing.
If you want to test the ProductsRepository then it is no longer called a unit test because it depends on an external source. To test those you are essentially testing Entityframework.
In combination to unit tests people do Integration testing using frameworks like Specflow. Essentially you can instantiate the Productscontroller with the real ProductsRepository and check the results coming back.