Author : MD TAREQ HASSAN

What is Moq

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:

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