SlideShare a Scribd company logo
Unit Testing and Mocking using MOQ
Your
Code
Test
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
[TestMethod]
public void Method_Scenario_Result()
{
// Set dependencies, build SUT, set
// expectations
// Exercise the SUT
// Check behaviour/state of SUT
// Check that expectations have been met
}
Assert
Act
Arrange
[TestMethod]
public void Method_Scenario_Result()
{
// Set dependencies, build SUT, set
// expectations
// Exercise the SUT
// Check behaviour/state of SUT
// Check that expectations have been met
}
Assert
Act
Arrange
[Test]
public void CreateNumString_TwoSimpleNumbers_ReturnsStringWithCommaBetween()
{
StringCalc sc = new StringCalc();
string result = sc.CreateNumString(1, 2);
Assert.AreEqual(String.Format("{0},{1}", x, y), result);
}
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
SUT Dependancy
Dependancy
Dependency
public class Sample{
private DatabaseThingie myDatabase;
public Sample() {
myDatabase = new DatabaseThingie();
}
public void DoStuff() {
myDatabase.GetData();
}
}
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ

More Related Content

PPTX
Mocking with Moq
ODP
Unit testing with Easymock
PPTX
PPTX
Jsp session 10
PPTX
Easy mockppt
PDF
PDF
Beautiful java script
PDF
Testing the unpredictable
Mocking with Moq
Unit testing with Easymock
Jsp session 10
Easy mockppt
Beautiful java script
Testing the unpredictable

What's hot (20)

PDF
iOS testing
PDF
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
PDF
Effective Unit Test Style Guide
PDF
JavaScript Unit Testing with an Angular 5.x Use Case 101
PDF
Isomorphic React Apps Testing
PPTX
Efficient JavaScript Mutation Testing
PPTX
Easy mock
PPTX
React hooks
PDF
Magic methods
PPTX
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
PPTX
Dependency Injection for Android
DOCX
Implement Search Screen Using Knockoutjs
PPSX
Javascript variables and datatypes
PDF
PDF
From OOP to FP: The validation case
PDF
Deep Dive into React Hooks
PDF
04 - Dublerzy testowi
PPTX
Java script basic
PPTX
What Do the Asserts in a Unit Test Tell Us About Code Quality? (CSMR2013)
PPT
Krazykoder struts2 interceptors
iOS testing
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Effective Unit Test Style Guide
JavaScript Unit Testing with an Angular 5.x Use Case 101
Isomorphic React Apps Testing
Efficient JavaScript Mutation Testing
Easy mock
React hooks
Magic methods
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android
Implement Search Screen Using Knockoutjs
Javascript variables and datatypes
From OOP to FP: The validation case
Deep Dive into React Hooks
04 - Dublerzy testowi
Java script basic
What Do the Asserts in a Unit Test Tell Us About Code Quality? (CSMR2013)
Krazykoder struts2 interceptors
Ad

Similar to Unit Testing and Mocking using MOQ (20)

PPTX
preparecallablepptx__2023_09_11_14_40_58pptx__2024_09_23_11_14_59.pptx
PPTX
Junit4&testng presentation
PDF
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
PDF
Confitura 2012 Bad Tests, Good Tests
PDF
GeeCON 2012 Bad Tests, Good Tests
DOCX
Scrollable Test App
PPT
Junit and testNG
PDF
How to write clean tests
PPT
JDBC for CSQL Database
PPTX
The secret unit testing tools no one ever told you about
PPTX
The secret unit testing tools no one has ever told you about
PDF
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
PDF
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
PPTX
Testing with VS2010 - A Bugs Life
PPT
Refactoring Jdbc Programming
PPT
Web based development
PPT
PDF
谷歌 Scott-lessons learned in testability
PPT
2012 JDays Bad Tests Good Tests
PPS
Jdbc api
preparecallablepptx__2023_09_11_14_40_58pptx__2024_09_23_11_14_59.pptx
Junit4&testng presentation
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
Confitura 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Scrollable Test App
Junit and testNG
How to write clean tests
JDBC for CSQL Database
The secret unit testing tools no one ever told you about
The secret unit testing tools no one has ever told you about
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Testing with VS2010 - A Bugs Life
Refactoring Jdbc Programming
Web based development
谷歌 Scott-lessons learned in testability
2012 JDays Bad Tests Good Tests
Jdbc api
Ad

More from Bruce Johnson (8)

PPTX
Introducing ASP.NET vNext
PPTX
Silverlight 4 Out Of Browser
PPTX
Setting Your Data Free With OData
PPTX
Silverlight 4 and Expression Blend
PPTX
Overview of VS2010 and .NET 4.0
PPTX
Data Bondage in WPF
PPTX
Code Contracts In .Net
PPTX
Whats New In Silverlight 3
Introducing ASP.NET vNext
Silverlight 4 Out Of Browser
Setting Your Data Free With OData
Silverlight 4 and Expression Blend
Overview of VS2010 and .NET 4.0
Data Bondage in WPF
Code Contracts In .Net
Whats New In Silverlight 3

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Electronic commerce courselecture one. Pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Approach and Philosophy of On baking technology
PPTX
MYSQL Presentation for SQL database connectivity
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
Understanding_Digital_Forensics_Presentation.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The Rise and Fall of 3GPP – Time for a Sabbatical?
Review of recent advances in non-invasive hemoglobin estimation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Spectral efficient network and resource selection model in 5G networks
Advanced methodologies resolving dimensionality complications for autism neur...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Electronic commerce courselecture one. Pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Approach and Philosophy of On baking technology
MYSQL Presentation for SQL database connectivity

Unit Testing and Mocking using MOQ

Editor's Notes

  • #15: publicvoidProductService_Create_CallsRepositorySave() {varmockProductRepository=newMock<IProductRepository>();mockProductRepository.Setup(r=>r.Save(It.IsAny<Product>()));varservice=newProductService(mockProductRepository.Object);service.Create(newProductViewModel());mockProductRepository.VerifyAll(); }
  • #16: [Test] [ExpectedException(typeof (InvalidProductIdException))]publicvoidProductService_Create_ExceptionIfIdNotCreated() {ProductViewModelproductViewModel=newProductViewModel() { Description="Nice product", Name="ProductA" };varmockProductRepository=newMock<IProductRepository>();mockProductRepository.Setup(r=>r.Save(It.IsAny<Product>()));varmockProductIdBuilder=newMock<IProductIdBuilder>();varservice=newProductService(mockProductRepository.Object, mockProductIdBuilder.Object);service.Create(productViewModel); }
  • #17: [Test]publicvoidProductService_CreateMany_VerifyCallsWereMade() {List<ProductViewModel>productViewModels=newList<ProductViewModel>() {newProductViewModel(){Name="ProductA", Description="Great product"},newProductViewModel(){Name="ProductB", Description="Bad product"},newProductViewModel(){Name="ProductC", Description="Cheap product"},newProductViewModel(){Name="ProductD", Description="Expensive product"} };varmockProductRepository=newMock<IProductRepository>();varmockIdBuilder=newMock<IProductIdBuilder>();mockIdBuilder.Setup(b=>b.BuildProductIdentifier()).Returns(newProductIdentifier());varservice=newProductService(mockProductRepository.Object, mockIdBuilder.Object);service.CreateMany(productViewModels);mockProductRepository.Verify(p=>p.Save(It.IsAny<Product>()), Times.Exactly(productViewModels.Count)); }
  • #19: publicvoidProductService_CreateMany_VerifyCallsWereMadeWithCallbacks() {List<ProductViewModel>productViewModels=newList<ProductViewModel>() {newProductViewModel(){Name="ProductA", Description="Great product"},newProductViewModel(){Name="ProductB", Description="Bad product"},newProductViewModel(){Name="ProductC", Description="Cheap product"},newProductViewModel(){Name="ProductD", Description="Expensive product"} };List<int>productIds=newList<int>();varmockProductRepository=newMock<IProductRepository>();mockProductRepository.Setup(r=>r.Save(It.IsAny<Product>())).Callback<Product>(p=>productIds.Add(p.Identifier.RawValue));varmockIdBuilder=newMock<IProductIdBuilder>();intproductId=1;mockIdBuilder.Setup(b=>b.BuildProductIdentifier()).Returns(() =>newProductIdentifier(){RawValue=productId}).Callback(() =>newProductIdentifier() { RawValue=productId++ });varservice=newProductService(mockProductRepository.Object, mockIdBuilder.Object);service.CreateMany(productViewModels);mockProductRepository.Verify(p=>p.Save(It.IsAny<Product>()), Times.Exactly(productViewModels.Count));vargroupings=fromxinproductIdsgroupxbyxintogletcount=g.Count()orderbycountdescendingselectnew { Value=g.Key, Count=count };foreach (varxingroupings)Assert.IsTrue(x.Count==1); } }
  • #20: [Test]publicvoidProductService_CallCreate_TryThreeTimesOnFailedSave() {varmockProductRepository=newMock<IProductRepository>();mockProductRepository.Setup(r=>r.Save(It.IsAny<Product>())).Throws(newDbConnectionException());varmockIdBuilder=newMock<IProductIdBuilder>();mockIdBuilder.Setup(b=>b.BuildProductIdentifier(It.IsAny<string>())).Returns(newProductIdentifier());varservice=newProductService(mockProductRepository.Object, mockIdBuilder.Object);service.Create(newProductViewModel());mockProductRepository.Verify(r=>r.Save(It.IsAny<Product>()), Times.Exactly(3)); }