Show Menu
Cheatography

MOQ Mocking Library

Links

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

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
 

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

          More Cheat Sheets by GregFinzer

          Salesforce CLI Cheat Sheet
          Crownpeak Input Controls Cheat Sheet