SlideShare uma empresa Scribd logo
1 de 19
Your
Code
Test
[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);
}
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

Mais conteúdo relacionado

Mais procurados

Efficient JavaScript Mutation Testing
Efficient JavaScript Mutation TestingEfficient JavaScript Mutation Testing
Efficient JavaScript Mutation Testing
SALT Lab @ UBC
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
Neeraj Kaushik
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Krazykoder struts2 interceptors
Krazykoder struts2 interceptorsKrazykoder struts2 interceptors
Krazykoder struts2 interceptors
Krazy Koder
 

Mais procurados (20)

iOS testing
iOS testingiOS testing
iOS testing
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101
 
Isomorphic React Apps Testing
Isomorphic React Apps TestingIsomorphic React Apps Testing
Isomorphic React Apps Testing
 
Efficient JavaScript Mutation Testing
Efficient JavaScript Mutation TestingEfficient JavaScript Mutation Testing
Efficient JavaScript Mutation Testing
 
Easy mock
Easy mockEasy mock
Easy mock
 
React hooks
React hooksReact hooks
React hooks
 
Magic methods
Magic methodsMagic methods
Magic methods
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Rspec
RspecRspec
Rspec
 
From OOP to FP: The validation case
From OOP to FP: The validation caseFrom OOP to FP: The validation case
From OOP to FP: The validation case
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React Hooks
 
04 - Dublerzy testowi
04 - Dublerzy testowi04 - Dublerzy testowi
04 - Dublerzy testowi
 
Java script basic
Java script basicJava script basic
Java script basic
 
What Do the Asserts in a Unit Test Tell Us About Code Quality? (CSMR2013)
What Do the Asserts in a Unit Test Tell Us About Code Quality? (CSMR2013)What Do the Asserts in a Unit Test Tell Us About Code Quality? (CSMR2013)
What Do the Asserts in a Unit Test Tell Us About Code Quality? (CSMR2013)
 
Krazykoder struts2 interceptors
Krazykoder struts2 interceptorsKrazykoder struts2 interceptors
Krazykoder struts2 interceptors
 

Semelhante a Unit Testing and Mocking using MOQ

Unit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, MelonUnit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
beITconference
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
chanwook Park
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz lin
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew
 

Semelhante a Unit Testing and Mocking using MOQ (20)

Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, MelonUnit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Scrollable Test App
Scrollable Test AppScrollable Test App
Scrollable Test App
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has 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)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
 
Web based development
Web based developmentWeb based development
Web based development
 
Junit
JunitJunit
Junit
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
 

Mais de Bruce Johnson

Mais de Bruce Johnson (8)

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

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Unit Testing and Mocking using MOQ

Notas do Editor

  1. publicvoidProductService_Create_CallsRepositorySave() {varmockProductRepository=newMock<IProductRepository>();mockProductRepository.Setup(r=>r.Save(It.IsAny<Product>()));varservice=newProductService(mockProductRepository.Object);service.Create(newProductViewModel());mockProductRepository.VerifyAll(); }
  2. [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); }
  3. [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)); }
  4. 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); } }
  5. [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)); }