Author : MD TAREQ HASSAN
What is Moq
- A mocking library (developed from scratch to take full advantage of .NET Linq expression trees and lambda expressions)
- It supports mocking interfaces as well as classes
- Quickly stubbing out dependencies
- See: Moq Quickstart
Setup
Install-Package Moq
Basic Mocking
public interface IFoo
{
bool DoSomething(string value);
}
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);
mock.Verify();
Notes:
Setup()
=> setting up for expected outcomeSetup()
takesFunc<IFoo, TReturn>
& a mocked implementation will be passed as argument to that Func- Checking return value:
.Returns(TReturn)
Setup(foo => foo.DoSomething("ping")).Returns(true);
=> Expectingfoo.DoSomething("ping")
to return truemock.Verify()
=> verifyingfoo.DoSomething("ping")
returned true
Varifying
.Verify()
var mockCustomerRepository = new Mock<ICustomerRepository>();
// setup for verifying Save() method call
mockCustomerRepository.Setup(customerRepository => customerRepository.Save(It.IsAny<Customer>());
var customerService = new CustomerService(mockCustomerRepository.Object);
// creating customer, so customerRepository.Save() should be called
customerService.Create(new Customer());
mockCustomerRepository.Verify(); // verifying: customerRepository.Save() was called
var listOfCustomers = new List<Customer> { // 3 customers here };
customerService.Create(listOfCustomers); // creating 3 customers
mockCustomerRepository.Verify(customerRepository => customerRepository.Save(It.IsAny<Customer>(), listOfCustomers.Count); // verifying that Save() was called 3 times
Note: It
is a static class provided by Moq