以下の内容はhttps://cheatography.com///gregfinzer/cheat-sheets/moq/より取得しました。


Cheatography

MOQ Cheat Sheet by

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

Comments

No comments yet. Add yours below!

Add a Comment

Related Cheat Sheets

Regular Expressions Cheat Sheet
Python Cheat Sheet

More Cheat Sheets by GregFinzer

Loving Your Neighbor Cheat Sheet
AWS Core Service Options Cheat Sheet
Unity Container Cheat Sheet



以上の内容はhttps://cheatography.com///gregfinzer/cheat-sheets/moq/より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14