Test-Driven
Sitecore
@DanSolovay
Sitecore Practice
Lead at Velir
MVP x 3
dansolovay.com
velir.com/blog
What’s the plan?
1. Unit Testing and Test-Driven Development
2. Isolating dependencies
3. Isolating Sitecore
4. Testing Sitecore itself
5. How to get started
1. Unit Testing and Test-
Driven Development
What is a Unit
Test?
• Can be automated
• In memory
(no DB or File access)
• Consistent & Fast
• Single Logical Concept
Unit Testing
is a Waste of
Time
…unless you plan
to make changes
to your code.
Unit Tests Let You…
• Change code with confidence
• Refactor
• Keep code simple
• Work well with others
Test-Driven
Development
• RED: Make a failing test.
• GREEN: Make it pass.
• REFACTOR: Make it clean.
This is stupid!
"It's going to slow me down, it's a
waste of time and effort, it will just
break my flow."
However…
Imagine if you walked into a room full of
people working this way. A minute ago, all
of their code worked.
Robert Martin, The Three Rules of TDD
bit.ly/tdd3rules
Calculator Kata
A classic exercise to learn TDD
bit.ly/tdd-kata
Recap
• Code is always working
• RED: Add functionality
• GREEN: Add design
• Practice, practice, practice
2. Isolating
Dependencies
Isolation
How do I keep out the real world?
• Talk to interfaces
• Wire with AutoFac
• Fake with NSubstitute
AutoFac
• Constructor injection
• Interfaces  Classes
• Code to abstractions
NSubstitute
• Create fakes from interfaces
• Script output
• Verify input
Recap
• MVC + AutoFac:
Interfaces  Production Objects
• NSubstitute:
Interfaces  Fakes
3. Isolating Sitecore
Sitecore and Testability
Sitecore items are FAT objects
• Knowledge of database
• Hard to “new up”
• God-like Static methods
Glass Mapper
• Injects items into light objects
• Plays well with AutoFac & MVC
• Code Gen option
Documentation: http://glass.lu
Sitecore.FakeDB
• Creates fake Items
• Can fake:
• Hierarchies
• Templates
• Security
• Still in Development
Github: bit.ly/FakeDB
Recap
• Glass for isolating Sitecore
• Sitecore.FakeDB for legacy code
4. Testing Sitecore Itself
Codeflood
Test Runner
• Available at
CodeFlood.net
• Useful for testing
Sitecore behavior
Recap
• Integration tests talk to real things
• Use for testing Sitecore tools
• Use unit tests to build logic
5. How to Get Started
Some Practical Tips
• Start small. One hour a week.
• Pair up.
• Keep tests clean.
• Keep tests passing.
• Do a Kata workshop.
• Do TDD Ping Pong.
NSubstitute
ReSharper
NCrunch
XUnit?
To Learn More
• My talk videos: bit.ly/tdd-videos
• String Calculator: bit.ly/tdd-kata
• Alistair Deneys’ blog: bit.ly/sitecore-testing
Photo Credits
Clock:
© littlenelly, Flickr
Traffic Light:
© Niels Sienaert, Flickr
Lighthouse:
© Dennis Jarvis, Flickr
Screwdriver:
© Gal, Flickr
Dan:
© Chris Brady, Velir
Thanks…
@DanSolovay
@Velir

Test-Driven Sitecore