SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Kürzlich hochgeladen (20)

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

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