Popular Answer

Consider a two-layer solution.

MyApp.Web

MyApp.Data

You will have something like this in your data layer:

public class ProductsRepository : IProductsRepository
{
     public List<Product> GetAll()
     {
        //EF stuff 
        return _dbcontext.Products;
     }
} 

IProductsRepository's location

public interface IProductsRepository
{
   List<Product> GetAll();
}

This is the general trend on MyApp.Web.

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 inserts ProductsRepository at runtime into the constructor? For this, people employ dependency injection frameworks like Ninject. Yet why? They may fake the ProductsRepository and do things like this because of this.

public class FakeProductsRepository : IProductsRepository
{
     public List<Product> GetAll()
     {
        return new List<Product> 
           { 
              new Product { Name = "PASTE" }
              new Product { Name = "BRUSH" } 
           }, 
     }
} 

and the controller went DEVICE TEST.

 [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);
 }

You are essentially creating a database, which makes the unit test quick and independent of the database. Sometimes while faking, people will utilize a mocking software that functions similarly to a Moq.

Since it relies on an external source, testing the ProductsRepository is no longer considered a unit test. You are essentially testing Entityframework when you test those.

People use frameworks like Specflow to do integration tests in addition to unit tests. In essence, you may instantiate the Productscontroller with the genuine ProductsRepository and examine the output.

18
10/16/2013 11:07:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow