0

I am working on a Unit test(MSTest) with Sitecore 9.3. I have created one personalization rule, below is the sample code:

protected override bool Execute(T ruleContext)
        {
            if (_pageContext != null && !string.IsNullOrWhiteSpace(_pageContext.baseketValue))
            {
                var deliveryType = _basketDetailsService.GetBasket(_pageContext.basketValue).deliveryType;
                if (deliveryType != null && deliveryType== DeliveryType.CashOnDelivery)
                {
                    return true;
                }
            }
            return false;
        }

Now I want to create a unit test for this personalization, can anyone guide me?

1
  • All the code within the first if scope should be a separate public method. Then you can write a unit test for that. Oct 5 at 6:20
0

I am giving you an example of few test cases to give you a gist about the way of writing the Unit Test for your Personalization Rule code:

[TestMethod]
        public void Execute_PageContextIsNull_ThenReturnFalse()
        {
            _mockPageContext = null;
            var ruleStack = new RuleStack();
            _sut.Evaluate(new RuleContext(), ruleStack);

            ruleStack.Pop().Should().Be(false);
        }
[TestMethod]
        public void Execute_WhenDeliveryTypeIsCashOnDelivery_ThenReturnsTrue()
        {
            var deliveryType = DeliveryType.CashOnDelivery;
            _mockPageContext.Setup(x => x.basketValue).Returns(“customer-xu78yb”);
            _mockBasketDetailsService.Setup(x => x. GetBasket(“customer-xu78yb”)).Returns(deliveryType);
            var ruleStack = new RuleStack();
            _sut.Evaluate(new RuleContext(), ruleStack);

            ruleStack.Pop().Should().Be(true);
        }

Here is the above example you can see that Sitecore Rules WhenCondition provide two methods Evaluate and Execute. Sitecore will create RuleStack to Pushed the result of each condition we write in Execute method and we passed the rule stack and context of our condition to Evaluate the method as a parameter. Once evaluate method will execute it will return the expected result in the stack based on the context we passed in the method. From the stack using the pop method, we can check the result with the help of Assertion.

From the above two examples, you can write Unit Test for another scenario as well. I hope that helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.