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

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
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Ryosuke Uchitate
 
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
uanna
 

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

Darfur1
Darfur1Darfur1
Darfur1
mjap23
 
Non Functional Testing
Non Functional TestingNon Functional Testing
Non Functional Testing
Nishant Worah
 

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

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.docx
tidwellveronique
 
China Science Challenge
China Science ChallengeChina Science Challenge
China Science Challenge
remko caprio
 

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

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

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
 

Dernier (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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