Skip to content

Instantly share code, notes, and snippets.

@nthdeveloper
Last active December 14, 2023 11:21
Show Gist options
  • Save nthdeveloper/13ded7fdd9dabc80b973c49df081f987 to your computer and use it in GitHub Desktop.
Save nthdeveloper/13ded7fdd9dabc80b973c49df081f987 to your computer and use it in GitHub Desktop.
Moq cheat sheet for most common scenarios

Quick start documentation

https://github.com/Moq/moq4/wiki/Quickstart

Installation

Install-Package Moq

Simplest Usage

//Create mock
var mockRepository = new Mock<ICustomerRepository>();
//Get the mocked object instance
mockRepository.Object;

Setup Method Calls

//Setup a method (simplest way, no return value)
mockRepository.Setup(r => r.Save(It.IsAny<Customer>()));
//Setup a method and mark as "verifiable"
mockRepository.Setup(r => r.Save(It.IsAny<Customer>())).Verifiable();
//Setup return value (directly)
mockRepository.Setup(r => r.FetchAll()).Returns(new List<Customer>());
//Setup return value (usng lambda expression)
mockRepository.Setup(r => r.FetchAll()).Returns(()=> new List<Customer>(){ });
//Return NULL
mockRepository.Setup(r => r.FetchAll()).Returns(()=> null);
//Setup "out" parameters
Address address = new Address() {Country="Sweden", City="Stockholm"};
mockAddressBuilder.Setup(x => x.TryParse(It.IsAny<string>(), out address)).Returns(() => true);
//Setup a callback operation for a method
mockIdFactory.Setup(x => x.Create()).Returns(() => id).Callback(() => id++);
//Control flow based on parameters
mockMaturityCalculator.Setup(m => m.GetMaturity(It.Is<CustomerDto>(c => c.Age >= 18))).Returns(MaturityStatus.Mature);
//Throw an exception
mockAddressBuilder.Setup(m => m.From(It.IsAny<CustomerDto>())).Throws<InvalidAddressException>();

Setup Properties

//Setup property "set"
mockRepository.SetupSet(m => m.LocalTimeZone == "...").Verifiable();
//Setup property "get"
mockAppSettings.Setup(m => m.WorkstationId).Returns(123);
//Setup property deep hiarachy
mockAppSettings.Setup(m => m.SystemConfiguration.AuditingInformation.WorkstationId).Returns(123);
//Setup property
mockAppSettings.SetupProperty(m => m.WorkstationId); //setup without initial value
mockAppSettings.SetupProperty(m => m.WorkstationId, 1234);//setup with initial value
mockAppSettings.SetupAllProperties();//Setups all properties (makes them stubable)
/* Sample set value */mockAppSettings.Object.WorkstationId = 12345;//To do this, property must be setup individually or by SetupAllProperties

Verify

//Verify a specific method call
mockRepository.Verify(m=>m.Save(It.IsAny<Customer>()));
//Verify all verifiables (setups, expectations)
mockRepository.Verify();
//Verify all expectations regardless of whether they have been flagged as verifiable 
mockRepository.VerifyAll();
//Verify the number of calls to a method
mockRepository.Verify(x => x.Save(It.IsAny<Customer>()), Times.Exactly(3));
//Verify with parameter values (exact values)
mockFullNameBuilder.Verify(m => m.From(customerDto.Name, customerDto.Surname));
//Verify with parameter values (matching values)
mockFullNameBuilder.Verify(
                m => m.From
                (
                        It.Is<string>(n => n.Equals(customerDto.Name, System.StringComparison.InvariantCultureIgnoreCase)),
                        It.Is<string>(s => s.Equals(customerDto.Surname, System.StringComparison.InvariantCultureIgnoreCase))
                ));
//Verify property set
mockRepository.VerifySet(m => m.LocalTimeZone);
mockRepository.VerifySet(m => m.LocalTimeZone = It.IsAny<string>());
### Raise Events From Mock Objects
//Standard evet raise
mockRepository.Raise(m => m.CustomerSaved += null, new CuatomerSavedEventArgs(2));
//Non-standard event raise
mockRepository.Raise(m => m.CustomerUpdated += null, 1, "John");
//Setup raise event in a method call
mockRepository.Setup(m => m.Save(It.IsAny<Customer>())).Raises(m => m.CustomerSaved += null, It.IsAny<CuatomerSavedEventArgs>());

Set Mock and Default Value Behaviors

//Set mocking behavior to strict (default is Loose)
var mockRepository = new Mock<ICustomerRepository>(MockBehavior.Strict);//unexpected calls causes VerfyAll to fail

//Set default value behavior (Empty, Mock, Custom)
//Empty = returns default value (null for refences)
//Mock = returns default value for value types and Mock objects for reference types (always returns the same mock object for the same method or property)
//Custom = Doc says set the Moq.MockFactory.DefaultValueProvider  instead of using this enumeration
var mockBuilderFactory = new Mock<IFullNameBuilderFactory>(){ DefaultValue= DefaultValue.Mock };
var builder = mockBuilderFactory.Object.Create();
var mockBuilder = Mock.Get(builder);//Get the actual mock object from created object

Centralized Verification Using MockRepository

var mockRepository = new MockRepository(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
var mockService1 = mockRepository.Create<IService1>();
var mockService2 = mockRepository.Create<IService2>();  
//... Act
mockFactory.VerifyAll();//Verify all created mock objects 

Protected Methods

//Setup virtual protected method call (Add using Moq.Protected;)
mockFormater.Protected().Setup<string>("ReplaceBadWords", ItExpr.IsAny<string>())                
                .Returns("aaaa")
                .Verifiable();//Important, otherwise it is not verifiable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment