Here is my IProductRepository:
public interface IProductsRepository
{
IQueryable<Product> Products { get; }
}
And here is where I’m using Moq:
public static IProductsRepository MockProductsRepository(params Product[] prods)
{
var mockProductRepos = new Mock<IProductsRepository>();
mockProductRepos.Setup(x => x.Products).Returns(prods.AsQueryable());
return mockProductRepos.Object;
}
And here is how I use this MockProductsRepository method:
[Test]
public void Product_Lists_Include_Correct_Page_Numbers()
{
//Arrange: If there are five products in the repository...
var mockRepository = UnitTestHelpers.MockProductsRepository(
new Product { Name = "P1" }, new Product { Name = "P2" },
new Product { Name = "P3" }, new Product { Name = "P4" },
new Product { Name = "P5" }
);
var controller = new ProductsController(mockRepository) { PageSize = 3 };
//yada yada yada...
}
What exactly is Moq doing? I’m following the book Pro ASP.Net MVC2 and it’s teaching all sorts of new wizardry to me, and before I continue reading, I’d like to understand what’s going on – and right now I just know, “it works” nothing more. 🙂
Thank you for your time.
Moq is generating the IL in memory for a class that implements
IProductsRepository, with all its properties/methods calling back to Moq to see what it should do. TheSetupis configuring theProductsproperty to always return the supplied list of products (as an IQueryable) when it is called. It’s then returning the generated object as aIProductsRepositorywhich can then be passed toProductsControllerwhich is none the wiser about its dynamic nature.