Show Menu

MOQ Cheat Sheet by

MOQ Mocking Library
development     moq

Normal Mock, Setup, Verify

//Arrange

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

//Act
InvoiceService.Create(new Invoice());

//Assert
mockRepository.VerifyAll();

Verify the parameters for a call

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

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

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

//Assert
mockCalcShipping.Verify(x => x.CalcShipping(
It.Is<string>(fn=>fn.Equals(invoice.ZipCode, StringComparison.InvariantCultureIgnoreCase)),
It.Is<decimal>(fn=>fn.Equals(Invoice.Weight)))));

Stubbing Properties

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

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

Verify Times a Method was Called

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

Verify Getter Was Called

mockRepository.VerifyGet(x=>x.ConnectionString);

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
//media.cheatography.com/storage/thumb/gregfinzer_moq.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readable.io is a collection of tools to make your writing better. More readable content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

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