Show Menu

MOQ Cheat Sheet by

MOQ Mocking Library
development     moq

Normal Mock, Setup, Verify


//Creating a Mock
var mockRepository = new Mock<IInvoiceRepository>();

//Perform method setup
mockRepository.Setup(o => o.Save(It.IsAny<Invoice>())).Returns(true);

//Pass in the mock with the Object property
var invoiceService = new InvoiceService(mockRepository.Object);

InvoiceService.Create(new Invoice());


Verify the parameters for a call

var mockCalcShipping = new Mock<ICalcShipping>();
Invoice invoice = new Invoice();

mockCalcShipping.Setup(o => o.CalcShipping(It.IsAny<string>(), It.IsAny<decimal>())).Returns(5.95M);

mockCalcShipping.CalcShipping(invoice.ZipCode, invoice.Weight);

mockCalcShipping.Verify(x => x.CalcShipping(
It.Is<string>(fn=>fn.Equals(invoice.ZipCode, StringComparison.InvariantCultureIgnoreCase)),

Stubbing Properties

//Stub property
mockRepository.SetupProperty(o => o.ConnectionString, "Test");

//Stub multiple properties
mockRepository.Object.ConnectionString = "Test";

Verify Times a Method was Called

mockInvoiceRepository.Verify(x=>x.Save(It.IsAny<Invoice>()), Times.Once());

Verify Getter Was Called


Verify Setter Was Called

mockRepository.VerifySet(x=>x.ConnectionString = It.IsAny<string>());

Throwing Exceptions

mockRepository.Setup(x => x.Save(It.IsAny<Invoice>())).Throws<ChangedByAnotherUserException>();

Mock Events

mockRepository.Raise(x=>x.NotifySalesTeam += null, new NotifySalesTeamEventArgs("jim"));

Download the MOQ Cheat Sheet

2 Pages

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!



No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet
          JavaScript Cheat Sheet

          More Cheat Sheets by GregFinzer

          Node Package Manager Cheat Sheet
          Yarn Package Manager Cheat Sheet
          RhinoMocks Cheat Sheet