Show Menu

MOQ Mocking Library


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"));

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi


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

          More Cheat Sheets by GregFinzer

          Salesforce CLI Cheat Sheet
          Crownpeak Input Controls Cheat Sheet