Currently I'm reading a book (Pro ASP.Net Framework).
In this book, the author suggests to use a Moq framework to help to do TDD.
[Test]
public void List_Presents_Correct_Page_Of_Products()
{
IProductsRepository repository = MockProductsRepository(
new Product { Name = "P1" }, new Product { Name = "P2" },
new Product { Name = "P3" }, new Product { Name = "P4" },
new Product { Name = "P5" }
);
ProductsController controller = new ProductsController(repository);
...
}
static IProductsRepository MockProductsRepository(params Product[] prods)
{
// Generate an implementor of IProductsRepository at runtime using Moq
var mockProductsRepos = new Moq.Mock<IProductsRepository>();
mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable());
return mockProductsRepos.Object;
}
In the model layer, we've define a FakeRepository, and a SqlRepository.
The fact is I don't see the advantage of using this moq framework. Why don't we only use our FakeRepository ? Or clear our FakeRepository and add fake product on it ?
At first, I thought that the moq framework was there to generate fake data so you don't have to if you have for example 100 fake objects to generate.
What I miss ?
A complete mocking framework like JustMock enables developers to focus solely on testing the system under test and forget about the distracting mocking details. Mock objects are created automatically in memory when the tests are run based on the simple configuration in the unit test.
It is used to isolate each dependency and help developers in performing unit testing in a concise, quick, and reliable way. Creating mock objects manually is very difficult and time-consuming. So, to increase your productivity, you can go for the automatic generation of mock objects by using a Mocking Framework.
Verify methods were called Mocking frameworks add another way to test - checking whether methods were called, in which order, how many times and with which arguments. For example, let's say that a new test is required for adding a new user: if that user does not exist than call IDataAccess. AddNewUser method.
To isolate the behavior of the object you want to test you replace the other objects by mocks that simulate the behavior of the real objects. So in simple words, mocking is creating objects that simulate the behavior of real objects. In unit testing we want to test methods of one class in isolation.
Some advantages of mock frameworks over hand-rolled mocks:
Some disadvantages:
(This is what I can think of right now. Feel free to edit and add more.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With