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 tests, action 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 ruleStack.Should().HaveCount(1); object value = ruleStack.Pop(); value.Should().Be(expectedResult); } }After the execution of the
Evaluate
method, the stack should contain the expected result based on the context you have presented.
Pingback: Make a custom device detector in Sitecore “Poor mans device detector” | Visions In Code