Back-End Development

Unit Testing Custom Rules, Actions, and Conditions with FakeDb – Part 1 – Testing Conditions

Software Testing@1x.jpg

Recently I was working on 2 new implementations of the Sitecore rules engine – adding new rule “types” that would be executed by an existing Sitecore pipeline. More news will come about those rules in the upcoming videos in BrainJocks SCORE University.

We at BrainJocks are heavily vested in using Sitecore.FakeDb – so I decided to see if I could write unit tests for my custom actions and conditions using this tool – and I was really pleased with how easy it was to do.

3 Types of Tests

There were 3 “types” of tests I decided to write – condition testsaction tests, and rule execution tests. Condition and action tests are by far the easiest – so we’ll start with one of those.

Testing a custom condition

In this example, we will simulate what Sitecore does when it executes and evaluates conditions – specifically, Sitecore will construct an object of type RuleStack for the results of each condition evaluation to be “pushed”. Then the rule stack and the context for your condition will be passed as arguments to the condition’s Evaluate method.

[TestCase("", "", false)]
[TestCase("DataSource=/sitecore/$test123", "", false)]
[TestCase("", "$test123", false)]
[TestCase("DataSource=query:${test}/something", "${test}", true)]
[TestCase("DataSource=query:$(test)/something", "$(test)", true)]
[TestCase("DataSource=query:/sitecore/content/something", "${test}", false)]

public void DoesQueryContainTokenCondition(string source, string token, bool expectedResult)
   using (var db = new Db {
      new DbItem("item")
   }) {

      Item item = db.GetItem("/sitecore/content/item");
      var context = new MyRuleContext {
                  Item = item,
                  ContextItem = item,
                  Source = source };

      var condition = new QueryContainsToken<MyRuleContext>
        Token = token

      var ruleStack = new RuleStack();

      // act
      condition.Evaluate(context, ruleStack);

      // assert
      object value = ruleStack.Pop();

After the execution of the Evaluate method, the stack should contain the expected result based on the context you have presented.

Thoughts on “Unit Testing Custom Rules, Actions, and Conditions with FakeDb – Part 1 – Testing Conditions”

  1. Pingback: Make a custom device detector in Sitecore “Poor mans device detector” | Visions In Code

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Brian Beckham

As a Sitecore MVP, Brian spends most of his time consulting and architecting software solutions for enterprise-level Sitecore projects.

More from this Author

Subscribe to the Weekly Blog Digest:

Sign Up
Follow Us