Wednesday, May 18, 2022

Sitecore Unit Test Examples

 The examples of  Unit tests are listed below..

1.  Constructor test

         [Fact]

        public void ProcessorConstructorTest()

        {

            var repo = Substitute.For<IService>();

            CreateProcessor processor = new CreateProcessor(repo);

            Assert.NotNull(processor);

        }



2.   Controller rendering action method

         [Fact]

        public void SubmitUserDetailsTest()

        {

            //Assign

            var repo = Substitute.For<IUserRepository>();

            var userData = UserMockData.UserMockDetails();

            UserResponse model = new UserResponse();

            repo.SubmitUserDetails(userData).ReturnsForAnyArgs(model);

            //Act

            var controller = new CustomerController(repo);

            var result = controller.SubmitUserData(userData);


            //Assert

            Assert.NotNull(controller);

            Assert.NotNull(result);

            Assert.IsType<CustJsonResult>(result);

            var returnresult = (UserResponse )(result.Data);

            Assert.IsType<UserResponse >(returnresult);

        }

public static UserMockData UserMockDetails()

        {

            return new UserMockData()

            {

                Station= "XYZ",

                LocatorList = new System.Collections.Generic.List<string>{ "{56ZR-GF67856-dfgd56-GHGH5767HJ}", "{HJ678J-HJ67-7HJK-&JKKL-JK789JKL}" },

                Endpoints = new System.Collections.Generic.List<string> { "{JK578KL-68HJ-HJK67-A7D0-KLH78HJ}", "{HJ678J-HJ67-7HJK-&JKKL-JK789JKL}", "{HJ678J-JKL78-HJK567-JKKL-JK789JKL}" },

                 IsMigrated= true

            };

        }

     [DataContract]

    [Bind(Include = "")]

    public class UserMockData

    {

        [DataMember]

        public string Station{ get; set; }

        [DataMember]

        public List<string>  LocatorList { get; set; }

        [DataMember]

        public List<string> Endpoints { get; set; }

        [DataMember]

        public bool IsMigrated{ get; set; }

    }



3. Mock Sitecore Pipeline Processor and Commerce user request

[Fact]

        public void Index()

        {

            var args = new ServicePipelineArgs(new GetUserInfoRequest("12345"),new GetUserInfoResult()

            {

                CommerceUser= new CommerceUser

                {

                    UserName = "XYZ"

                }

                

            });

            using (var db = new Sitecore.FakeDb.Db())

            {

                var processor =

                    Substitute.For<Sitecore.FakeDb.Pipelines.IPipelineProcessor>();


                processor

                    .When(p => p.Process(args))

                    .Do(ci => ci.Arg<ServicePipelineArgs>()

                        .CustomData["Result"] = "Ok");


                db.PipelineWatcher.Register("commerce.customers.User", processor);

                //Assign

                var repo = Substitute.For<ICustInfoRepository>();

                CustInfoApiController controller = new CustInfoApiController(repo);

                SetupCallContext();

                CallContext.Current.Shopping.ShoppingSite = "commtest";

                CallContext.Current.User.IsLoggedIn = true;

                CallContext.Current.User.UserId = "12345";   

            

                SetCustInfoData(CallContext.Current.User.UserId ?? CallContext.Current.User.CurrentUserId);

            

                var result = controller.Index("12345");

                //Assert

                Assert.NotNull(controller);

                Assert.NotNull(result); 

            }

        }

public void SetCustInfoData(string userId)

        {

            var custInfoData = GetCustInfoData();

            SessionCacheHelper.Set<Customer>(ABCCookieHelper.GetCustomerSessionKey(userId), custInfoData );

        }


        public Customer GetCustInfoData()

        {

            return new Customer()

            {


                CardId= "12345",

                Lane = "6",

                Email = "sdfgh@xyz.com",

                Mobileno = "1234567890",

                FullName = "SSSSS",

                Nationality = "DF",

                Gender = "M",

                Dob = Convert.ToDateTime("09/05/1990"),

                ContactId = "6687888787",

                CustomerId = "fghhg777hjhjh"

            };

        }


4. Create Sitecore datasource/Item

using Sitecore.Data;

using Sitecore.FakeDb;

using Sitecore.Sites;

using System;

using Xunit;

using NSubstitute;

 private static DbItem SetFakeContentRoot()

        {

            var PageID1 = new ID(Guid.NewGuid());

            var PageID2 = new ID(Guid.NewGuid());


            var FakeContentRoot = new DbItem("FakeContentRoot")

            {

                new DbItem("PageID1", PageID1),

                new DbItem("PageID2", PageID2)

            };

            return FakeContentRoot;

        }

No comments:

Post a Comment

How to Create a Public Link Using the Sitecore Content Hub REST API

Creating a public link using the Sitecore Content Hub REST API is a straightforward process that enables you to share content externally whi...