SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
And how I went through the 4 stages of developer denial
Prepared by: Jason St-Cyr
Microsoft Fakes
Sitecore Dev team unit testing prototype:
https://github.com/Sitecore/sitecore-seven-unittest-example
Nextdigital blog: Shooting for the Sky:
http://www.nextdigital.com/voice/shooting-for-the-sky

Stackoverflow: Unit Testing IQueryable operations:
http://stackoverflow.com/questions/20863942/unit-testing-iqueryable-operations
Stage 1: Egotism
Stage 2: Confusion
Sitecore Resources…

From the community…

• Sitecore Dev team unit
testing prototype:

• Nextdigital blog: Shooting
for the Sky:

https://github.com/Sitecore/sitecore
-seven-unittest-example

http://www.nextdigital.com/voice/shoot
ing-for-the-sky

• Stackoverflow: Unit Testing
IQueryable operations:

http://stackoverflow.com/questions/208
63942/unit-testing-iqueryableoperations
Test Data

[TestMethod]
public void GetAll()
{
//A small data set of entities with different Template IDs
var data = new List<SearchResultItem>()
{
new CaseStudy { TemplateId = CaseStudy.TemplateId, Title = "Match 1", TeaserText = "Match 1 is awesome.", Name = "Match-1" },
new CallToActionGeneral { TemplateId = CallToActionGeneral.TemplateId, Content = "This is not a match. This is a call to action", Name = "Not-a-match" },
new CaseStudy { TemplateId = CaseStudy.TemplateId, Title = "Match 2", TeaserText = "Match 2 is kind of neat.", Name = "Match-2" },
};

Faking the Index

//Create the fake index that will be used to replace the standard Sitecore index
var index = CreateFakeIndex<SearchResultItem>(data);
//Create the provider that will be tested
var provider = new CaseStudyProvider(index);
//Test the GetAll method, ensuring we return all possible results.
var caseStudies = provider.GetAll(data.Count);
//Verify that only 2 of the 3 returned.
Assert.AreEqual(caseStudies.Count(), 2);

Running the test

//Verify that the 2 returned are the correct ones
foreach (CaseStudy caseStudy in caseStudies)
{
var isMatch1 = caseStudy.Name != null && caseStudy.Name.ToLower().Equals("match-1");
var isMatch2 = caseStudy.Name != null && caseStudy.Name.ToLower().Equals("match-2");
Assert.IsTrue(isMatch1 || isMatch2, "Result {0} is not expected.", caseStudy.Name);
}
}
public class CaseStudyProvider : ICaseStudyProvider
{
private ISearchIndex Index { get; set; }
public CaseStudyProvider(ISearchIndex index) {
Index = index;
}

/// <summary>
/// Searches the index for components that are of type 'Case Study' and returns the entity
/// </summary>
/// <param name="numberOfStudies">The maximum number of studies to return</param>
/// <returns>A list of CaseStudy entities</returns>
public IEnumerable<CaseStudy> GetAll(int numberOfStudies)
{
//Get the queryable that will be used to get the case studies
var context = Index.CreateSearchContext();
var queryable = context.GetQueryable<SearchResultItem>();
return queryable.Where(item => item.TemplateId == CaseStudy.TemplateId).Take(numberOfStudies).Cast<CaseStudy>();
}
}

Based on the UpcomingEventsProvider by Dan Solovay in
his Stack Overflow post.
Simplified to only return the items in the index
with the correct Template ID.
Sitecore Example Fixture (FakeItEasy):
[SetUp]
public void Setup()
{
this.fakeIndex = A.Fake<ISearchIndex>();
this.fakeSearchContext = A.Fake<IProviderSearchContext>();
A.CallTo(() => this.fakeIndex.CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck)).Returns(this.fakeSearchContext);
}

Dan Solovay Example (NSubstitute):
private static ISearchIndex MakeSubstituteIndex(List<EventPageSearchItem> itemsToReturn)
{
ISearchIndex index = Substitute.For<ISearchIndex>();
_eventTemplateId = MyProject.Library.IEvent_PageConstants.TemplateId;
SimpleFakeRepo<EventPageSearchItem> repo = new
SimpleFakeRepo<EventPageSearchItem>(itemsToReturn);
index.CreateSearchContext().GetQueryable<EventPageSearchItem>().Returns(repo);
return index;
}
• My good buddy Joe
comes by…

• And then I’m all like…
Stage 3: Frustration
/// <summary>
/// The Fake Provider Search Context will always return the repository assigned to it
/// </summary>
public class FakeProviderSearchContext : IProviderSearchContext
{
/// <summary>
/// Storage for repository used by this instance of the context
/// </summary>
public IQueryable Repository { get; set; }

Storing data

/// <summary>
/// Returns the repository
/// </summary>
/// <typeparam name="TItem"></typeparam>
/// <returns></returns>
public IQueryable<TItem> GetQueryable<TItem>() where TItem : new()
{
return Repository.Cast<TItem>();
}

…

Faking Data Return

Right?
• At some point during the flow, even if explicitly set, the
search context object was going null.
• That means no results.

• …no success.
• …full of anger.

• …desire to push forward, so close.
Stage 4: Success
Doesn’t
work

Fake
Index

Fake
Context
Fake
Index

Fake
Context

Works!
/// <summary>
/// Represents the fake index. Can be bound to a repository so that
/// all search contexts created will bind to this repository.
/// </summary>
public class FakeSearchIndex : ISearchIndex
{
/// <summary>
/// Storage for the repository data used on the index
/// </summary>
public IQueryable Repository { get; set; }

Store the data

/// <summary>
/// Implement a fake search context creation which will allow us to persist
/// a fake data associated to the index
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public IProviderSearchContext CreateSearchContext(SearchSecurityOptions options = SearchSecurityOptions.EnableSecurityCheck)
{
var context = new FakeProviderSearchContext();
context.Index = this;
context.SecurityOptions = options;
context.Repository = Repository;
return context;
}

…

Create each context
with the data
/// <summary>
/// Create a fake index that contains the data specified
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
private static ISearchIndex CreateFakeIndex<T>(List<T> items) where T:SearchResultItem
{
var repository = new FakeRepository<T>(items);
var index = new FakeSearchIndex();
index.Repository = repository;
return index;
}

Set the data

Once the data was moved to the Index object,
each context was successfully created, and the
test passed!
•

A single FakeSearchIndex class can represent any index.

•

It only takes about 20 lines of actual code to implement the fake
objects for the index, context, and repository.

•

Need to have unit tests create sample data to fill the fake index.

•

Sitecore.ContentSearch and
Sitecore.ContentSearch.SearchTypes are your namespace
friends.

•

No mocking needed to test business logic that queries indexes!

- Limited use: can only support testing queries on the context, unless the
rest of the ISearchIndex implementation is built out.
Jason St-Cyr
 Solution Architect, nonlinear digital

 Background in .NET software development and Application Lifecycle
Management
 Contact me: jst-cyr@nonlinear.ca
 Around the web:
 Technical Blog:
http://theagilecoder.wordpress.com
 LinkedIn Profile:
http://www.linkedin.com/pub/jason-st-cyr/26/a73/645
 Nonlinear Thinking:
http://blog.nonlinearcreations.com/en/author/jason-st-cyr/
 Twitter: @AgileStCyr

Contenu connexe

Tendances

Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Fwdays
 
iOS Behavior-Driven Development
iOS Behavior-Driven DevelopmentiOS Behavior-Driven Development
iOS Behavior-Driven DevelopmentBrian Gesiak
 
Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questionsarchana singh
 
Overview of Google spreadsheet API for Java by Nazar Kostiv
Overview of Google spreadsheet API for Java by Nazar Kostiv Overview of Google spreadsheet API for Java by Nazar Kostiv
Overview of Google spreadsheet API for Java by Nazar Kostiv IT Booze
 
The Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockThe Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockNaresha K
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Ryosuke Uchitate
 
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...Alex Thissen
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputuanna
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 

Tendances (16)

Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"Artem Storozhuk "Building SQL firewall: insights from developers"
Artem Storozhuk "Building SQL firewall: insights from developers"
 
ADO.NETObjects
ADO.NETObjectsADO.NETObjects
ADO.NETObjects
 
iOS Behavior-Driven Development
iOS Behavior-Driven DevelopmentiOS Behavior-Driven Development
iOS Behavior-Driven Development
 
Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questions
 
C#
C#C#
C#
 
Overview of Google spreadsheet API for Java by Nazar Kostiv
Overview of Google spreadsheet API for Java by Nazar Kostiv Overview of Google spreadsheet API for Java by Nazar Kostiv
Overview of Google spreadsheet API for Java by Nazar Kostiv
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
The Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockThe Groovy Way of Testing with Spock
The Groovy Way of Testing with Spock
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
 
Servlet Filters
Servlet FiltersServlet Filters
Servlet Filters
 
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...I dont feel so well. Integrating health checks in your .NET Core solutions - ...
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple input
 
2nd-Order-SQLi-Josh
2nd-Order-SQLi-Josh2nd-Order-SQLi-Josh
2nd-Order-SQLi-Josh
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 

En vedette

The Safety Net of Functional Web Testing
The Safety Net of Functional Web TestingThe Safety Net of Functional Web Testing
The Safety Net of Functional Web Testingogborstad
 
Darfur1
Darfur1Darfur1
Darfur1mjap23
 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyondmguillem
 
What are the advantages of non functional testing
What are the advantages of non functional testingWhat are the advantages of non functional testing
What are the advantages of non functional testingMaveric Systems
 
Continuous Testing of eCommerce Apps
Continuous Testing of eCommerce AppsContinuous Testing of eCommerce Apps
Continuous Testing of eCommerce AppsSauce Labs
 
The importance of non functional testing
The importance of non functional testingThe importance of non functional testing
The importance of non functional testingMaveric Systems
 
Non-functional Testing (NFT) Overview
Non-functional Testing (NFT) Overview Non-functional Testing (NFT) Overview
Non-functional Testing (NFT) Overview Assaf Halperin
 
Non Functional Testing
Non Functional TestingNon Functional Testing
Non Functional TestingNishant Worah
 
Testing web services
Testing web servicesTesting web services
Testing web servicesTaras Lytvyn
 

En vedette (10)

The Safety Net of Functional Web Testing
The Safety Net of Functional Web TestingThe Safety Net of Functional Web Testing
The Safety Net of Functional Web Testing
 
Darfur1
Darfur1Darfur1
Darfur1
 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
 
Test-Driven Sitecore
Test-Driven SitecoreTest-Driven Sitecore
Test-Driven Sitecore
 
What are the advantages of non functional testing
What are the advantages of non functional testingWhat are the advantages of non functional testing
What are the advantages of non functional testing
 
Continuous Testing of eCommerce Apps
Continuous Testing of eCommerce AppsContinuous Testing of eCommerce Apps
Continuous Testing of eCommerce Apps
 
The importance of non functional testing
The importance of non functional testingThe importance of non functional testing
The importance of non functional testing
 
Non-functional Testing (NFT) Overview
Non-functional Testing (NFT) Overview Non-functional Testing (NFT) Overview
Non-functional Testing (NFT) Overview
 
Non Functional Testing
Non Functional TestingNon Functional Testing
Non Functional Testing
 
Testing web services
Testing web servicesTesting web services
Testing web services
 

Similaire à Sitecore 7: A developers quest to mastering unit testing

F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise7sharp9
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Shakir Majeed Khan
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxtidwellveronique
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers StealBen Scofield
 
Framework Project
Framework  ProjectFramework  Project
Framework ProjectMauro_Sist
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenchesIsmail Mayat
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQLRaji Ghawi
 
China Science Challenge
China Science ChallengeChina Science Challenge
China Science Challengeremko caprio
 
SgCodeJam24 Workshop
SgCodeJam24 WorkshopSgCodeJam24 Workshop
SgCodeJam24 Workshopremko caprio
 
Automation Testing
Automation TestingAutomation Testing
Automation TestingRomSoft SRL
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answerskavinilavuG
 
iOS Development Methodology
iOS Development MethodologyiOS Development Methodology
iOS Development MethodologySmartLogic
 
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...Sencha
 

Similaire à Sitecore 7: A developers quest to mastering unit testing (20)

F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
 
Framework Project
Framework  ProjectFramework  Project
Framework Project
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
YQL & Yahoo! Apis
YQL & Yahoo! ApisYQL & Yahoo! Apis
YQL & Yahoo! Apis
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
 
China Science Challenge
China Science ChallengeChina Science Challenge
China Science Challenge
 
SgCodeJam24 Workshop
SgCodeJam24 WorkshopSgCodeJam24 Workshop
SgCodeJam24 Workshop
 
Automation Testing
Automation TestingAutomation Testing
Automation Testing
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
 
iOS Development Methodology
iOS Development MethodologyiOS Development Methodology
iOS Development Methodology
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
SenchaCon 2016: Building a Faceted Catalog of Video Game Assets Using Ext JS ...
 
Servlets
ServletsServlets
Servlets
 

Plus de nonlinear creations

Sitecore User Group: Session State and Sitecore xDB
Sitecore User Group: Session State and Sitecore xDB Sitecore User Group: Session State and Sitecore xDB
Sitecore User Group: Session State and Sitecore xDB nonlinear creations
 
Unofficial Sitecore Training - Data enrichment and personalization
Unofficial Sitecore Training - Data enrichment and personalizationUnofficial Sitecore Training - Data enrichment and personalization
Unofficial Sitecore Training - Data enrichment and personalizationnonlinear creations
 
The SickKids Foundation on enabling a digital CXM 'hub' with Sitecore
The SickKids Foundation on enabling a digital CXM 'hub' with SitecoreThe SickKids Foundation on enabling a digital CXM 'hub' with Sitecore
The SickKids Foundation on enabling a digital CXM 'hub' with Sitecorenonlinear creations
 
Design Credibility: No one trusts an ugly website
Design Credibility: No one trusts an ugly websiteDesign Credibility: No one trusts an ugly website
Design Credibility: No one trusts an ugly websitenonlinear creations
 
National Wildlife Federation- OMS- Dreamcore 2011
National Wildlife Federation- OMS- Dreamcore 2011National Wildlife Federation- OMS- Dreamcore 2011
National Wildlife Federation- OMS- Dreamcore 2011nonlinear creations
 
Sitecore MVC: Converting Web Forms sublayouts
Sitecore MVC: Converting Web Forms sublayoutsSitecore MVC: Converting Web Forms sublayouts
Sitecore MVC: Converting Web Forms sublayoutsnonlinear creations
 
Sitecore MVC: What it is and why it's important
Sitecore MVC: What it is and why it's importantSitecore MVC: What it is and why it's important
Sitecore MVC: What it is and why it's importantnonlinear creations
 
Spiral into control with Knowledge Management
Spiral into control with Knowledge ManagementSpiral into control with Knowledge Management
Spiral into control with Knowledge Managementnonlinear creations
 
8 tips for successful change management
8 tips for successful change management8 tips for successful change management
8 tips for successful change managementnonlinear creations
 
Cms project-failing-the-software-or-the-partner
Cms project-failing-the-software-or-the-partnerCms project-failing-the-software-or-the-partner
Cms project-failing-the-software-or-the-partnernonlinear creations
 
Understanding cloud platform services
Understanding cloud platform servicesUnderstanding cloud platform services
Understanding cloud platform servicesnonlinear creations
 
ALM 101: An introduction to application lifecycle management
ALM 101: An introduction to application lifecycle managementALM 101: An introduction to application lifecycle management
ALM 101: An introduction to application lifecycle managementnonlinear creations
 
Understanding web engagement management (WEM) and your social media presence
Understanding web engagement management (WEM) and your social media presenceUnderstanding web engagement management (WEM) and your social media presence
Understanding web engagement management (WEM) and your social media presencenonlinear creations
 
Sitecore: Understanding your visitors and user personas
Sitecore: Understanding your visitors and user personas Sitecore: Understanding your visitors and user personas
Sitecore: Understanding your visitors and user personas nonlinear creations
 
Social intranets: 10 ways to drive adoption
Social intranets: 10 ways to drive adoptionSocial intranets: 10 ways to drive adoption
Social intranets: 10 ways to drive adoptionnonlinear creations
 

Plus de nonlinear creations (18)

Sitecore User Group: Session State and Sitecore xDB
Sitecore User Group: Session State and Sitecore xDB Sitecore User Group: Session State and Sitecore xDB
Sitecore User Group: Session State and Sitecore xDB
 
Sitecore on Azure
Sitecore on AzureSitecore on Azure
Sitecore on Azure
 
Unofficial Sitecore Training - Data enrichment and personalization
Unofficial Sitecore Training - Data enrichment and personalizationUnofficial Sitecore Training - Data enrichment and personalization
Unofficial Sitecore Training - Data enrichment and personalization
 
The SickKids Foundation on enabling a digital CXM 'hub' with Sitecore
The SickKids Foundation on enabling a digital CXM 'hub' with SitecoreThe SickKids Foundation on enabling a digital CXM 'hub' with Sitecore
The SickKids Foundation on enabling a digital CXM 'hub' with Sitecore
 
Intranet trends to watch
Intranet trends to watchIntranet trends to watch
Intranet trends to watch
 
Design Credibility: No one trusts an ugly website
Design Credibility: No one trusts an ugly websiteDesign Credibility: No one trusts an ugly website
Design Credibility: No one trusts an ugly website
 
National Wildlife Federation- OMS- Dreamcore 2011
National Wildlife Federation- OMS- Dreamcore 2011National Wildlife Federation- OMS- Dreamcore 2011
National Wildlife Federation- OMS- Dreamcore 2011
 
Sitecore MVC: Converting Web Forms sublayouts
Sitecore MVC: Converting Web Forms sublayoutsSitecore MVC: Converting Web Forms sublayouts
Sitecore MVC: Converting Web Forms sublayouts
 
Sitecore MVC: What it is and why it's important
Sitecore MVC: What it is and why it's importantSitecore MVC: What it is and why it's important
Sitecore MVC: What it is and why it's important
 
Spiral into control with Knowledge Management
Spiral into control with Knowledge ManagementSpiral into control with Knowledge Management
Spiral into control with Knowledge Management
 
Icebergs
IcebergsIcebergs
Icebergs
 
8 tips for successful change management
8 tips for successful change management8 tips for successful change management
8 tips for successful change management
 
Cms project-failing-the-software-or-the-partner
Cms project-failing-the-software-or-the-partnerCms project-failing-the-software-or-the-partner
Cms project-failing-the-software-or-the-partner
 
Understanding cloud platform services
Understanding cloud platform servicesUnderstanding cloud platform services
Understanding cloud platform services
 
ALM 101: An introduction to application lifecycle management
ALM 101: An introduction to application lifecycle managementALM 101: An introduction to application lifecycle management
ALM 101: An introduction to application lifecycle management
 
Understanding web engagement management (WEM) and your social media presence
Understanding web engagement management (WEM) and your social media presenceUnderstanding web engagement management (WEM) and your social media presence
Understanding web engagement management (WEM) and your social media presence
 
Sitecore: Understanding your visitors and user personas
Sitecore: Understanding your visitors and user personas Sitecore: Understanding your visitors and user personas
Sitecore: Understanding your visitors and user personas
 
Social intranets: 10 ways to drive adoption
Social intranets: 10 ways to drive adoptionSocial intranets: 10 ways to drive adoption
Social intranets: 10 ways to drive adoption
 

Dernier

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Dernier (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Sitecore 7: A developers quest to mastering unit testing

  • 1. And how I went through the 4 stages of developer denial Prepared by: Jason St-Cyr
  • 2.
  • 4.
  • 5. Sitecore Dev team unit testing prototype: https://github.com/Sitecore/sitecore-seven-unittest-example Nextdigital blog: Shooting for the Sky: http://www.nextdigital.com/voice/shooting-for-the-sky Stackoverflow: Unit Testing IQueryable operations: http://stackoverflow.com/questions/20863942/unit-testing-iqueryable-operations
  • 6.
  • 7.
  • 9.
  • 10.
  • 12.
  • 13.
  • 14. Sitecore Resources… From the community… • Sitecore Dev team unit testing prototype: • Nextdigital blog: Shooting for the Sky: https://github.com/Sitecore/sitecore -seven-unittest-example http://www.nextdigital.com/voice/shoot ing-for-the-sky • Stackoverflow: Unit Testing IQueryable operations: http://stackoverflow.com/questions/208 63942/unit-testing-iqueryableoperations
  • 15.
  • 16. Test Data [TestMethod] public void GetAll() { //A small data set of entities with different Template IDs var data = new List<SearchResultItem>() { new CaseStudy { TemplateId = CaseStudy.TemplateId, Title = "Match 1", TeaserText = "Match 1 is awesome.", Name = "Match-1" }, new CallToActionGeneral { TemplateId = CallToActionGeneral.TemplateId, Content = "This is not a match. This is a call to action", Name = "Not-a-match" }, new CaseStudy { TemplateId = CaseStudy.TemplateId, Title = "Match 2", TeaserText = "Match 2 is kind of neat.", Name = "Match-2" }, }; Faking the Index //Create the fake index that will be used to replace the standard Sitecore index var index = CreateFakeIndex<SearchResultItem>(data); //Create the provider that will be tested var provider = new CaseStudyProvider(index); //Test the GetAll method, ensuring we return all possible results. var caseStudies = provider.GetAll(data.Count); //Verify that only 2 of the 3 returned. Assert.AreEqual(caseStudies.Count(), 2); Running the test //Verify that the 2 returned are the correct ones foreach (CaseStudy caseStudy in caseStudies) { var isMatch1 = caseStudy.Name != null && caseStudy.Name.ToLower().Equals("match-1"); var isMatch2 = caseStudy.Name != null && caseStudy.Name.ToLower().Equals("match-2"); Assert.IsTrue(isMatch1 || isMatch2, "Result {0} is not expected.", caseStudy.Name); } }
  • 17. public class CaseStudyProvider : ICaseStudyProvider { private ISearchIndex Index { get; set; } public CaseStudyProvider(ISearchIndex index) { Index = index; } /// <summary> /// Searches the index for components that are of type 'Case Study' and returns the entity /// </summary> /// <param name="numberOfStudies">The maximum number of studies to return</param> /// <returns>A list of CaseStudy entities</returns> public IEnumerable<CaseStudy> GetAll(int numberOfStudies) { //Get the queryable that will be used to get the case studies var context = Index.CreateSearchContext(); var queryable = context.GetQueryable<SearchResultItem>(); return queryable.Where(item => item.TemplateId == CaseStudy.TemplateId).Take(numberOfStudies).Cast<CaseStudy>(); } } Based on the UpcomingEventsProvider by Dan Solovay in his Stack Overflow post. Simplified to only return the items in the index with the correct Template ID.
  • 18. Sitecore Example Fixture (FakeItEasy): [SetUp] public void Setup() { this.fakeIndex = A.Fake<ISearchIndex>(); this.fakeSearchContext = A.Fake<IProviderSearchContext>(); A.CallTo(() => this.fakeIndex.CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck)).Returns(this.fakeSearchContext); } Dan Solovay Example (NSubstitute): private static ISearchIndex MakeSubstituteIndex(List<EventPageSearchItem> itemsToReturn) { ISearchIndex index = Substitute.For<ISearchIndex>(); _eventTemplateId = MyProject.Library.IEvent_PageConstants.TemplateId; SimpleFakeRepo<EventPageSearchItem> repo = new SimpleFakeRepo<EventPageSearchItem>(itemsToReturn); index.CreateSearchContext().GetQueryable<EventPageSearchItem>().Returns(repo); return index; }
  • 19. • My good buddy Joe comes by… • And then I’m all like…
  • 21.
  • 22. /// <summary> /// The Fake Provider Search Context will always return the repository assigned to it /// </summary> public class FakeProviderSearchContext : IProviderSearchContext { /// <summary> /// Storage for repository used by this instance of the context /// </summary> public IQueryable Repository { get; set; } Storing data /// <summary> /// Returns the repository /// </summary> /// <typeparam name="TItem"></typeparam> /// <returns></returns> public IQueryable<TItem> GetQueryable<TItem>() where TItem : new() { return Repository.Cast<TItem>(); } … Faking Data Return Right?
  • 23.
  • 24. • At some point during the flow, even if explicitly set, the search context object was going null. • That means no results. • …no success. • …full of anger. • …desire to push forward, so close.
  • 28. /// <summary> /// Represents the fake index. Can be bound to a repository so that /// all search contexts created will bind to this repository. /// </summary> public class FakeSearchIndex : ISearchIndex { /// <summary> /// Storage for the repository data used on the index /// </summary> public IQueryable Repository { get; set; } Store the data /// <summary> /// Implement a fake search context creation which will allow us to persist /// a fake data associated to the index /// </summary> /// <param name="options"></param> /// <returns></returns> public IProviderSearchContext CreateSearchContext(SearchSecurityOptions options = SearchSecurityOptions.EnableSecurityCheck) { var context = new FakeProviderSearchContext(); context.Index = this; context.SecurityOptions = options; context.Repository = Repository; return context; } … Create each context with the data
  • 29. /// <summary> /// Create a fake index that contains the data specified /// </summary> /// <param name="items"></param> /// <returns></returns> private static ISearchIndex CreateFakeIndex<T>(List<T> items) where T:SearchResultItem { var repository = new FakeRepository<T>(items); var index = new FakeSearchIndex(); index.Repository = repository; return index; } Set the data Once the data was moved to the Index object, each context was successfully created, and the test passed!
  • 30. • A single FakeSearchIndex class can represent any index. • It only takes about 20 lines of actual code to implement the fake objects for the index, context, and repository. • Need to have unit tests create sample data to fill the fake index. • Sitecore.ContentSearch and Sitecore.ContentSearch.SearchTypes are your namespace friends. • No mocking needed to test business logic that queries indexes! - Limited use: can only support testing queries on the context, unless the rest of the ISearchIndex implementation is built out.
  • 31. Jason St-Cyr  Solution Architect, nonlinear digital  Background in .NET software development and Application Lifecycle Management  Contact me: jst-cyr@nonlinear.ca  Around the web:  Technical Blog: http://theagilecoder.wordpress.com  LinkedIn Profile: http://www.linkedin.com/pub/jason-st-cyr/26/a73/645  Nonlinear Thinking: http://blog.nonlinearcreations.com/en/author/jason-st-cyr/  Twitter: @AgileStCyr