MOQ Mock

 

Unit Testing For C# Developers

https://freecoursesite.com/unit-testing-for-c-developers-1/

https://www.seedr.cc/?r=2911610


Return  IEnumerable List.

var _deactivateOperation = new Mock<IDeactivateOperation>();
           var deactivateOperationlist = new List<IDeactivateOperation>();
 
           _deactivateOperation.Setup(x => x.EnvironmentEligibility(It.IsAny<WebStore>())).Returns(true);
           deactivateOperationlist.Add(_deactivateOperation.Object);
 
           _deactivateServices.Setup(m => m.GetEnumerator()).Returns(() => deactivateOperationlist.GetEnumerator());


Throw Exception Example

[Test]
        public void ExecuteDeactivation_ExceptionOccured_ThrowException()
        {
            // Arrange
            var webstore = new WebStore { WebStoreId = 1 };
 
            // Act          
 
            // Assert
            Assert.That(() => deactivateHelperService.ExecuteDeactivation(webstore), Throws.Exception);
            _logService.Verify(s => s.Log(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<Exception>()), Times.Exactly(2));
            _logService.Verify(s => s.SaveLog(It.IsAny<int>(), It.IsAny<IPrincipal>(), LogType.DeactivateWebstore, It.IsAny<bool>(), It.IsAny<Exception>()), Times.Once);
 
        }


Assert.That(() => applicationInsightsHelperService.InstallAppInsights(webStore), Throws.Exception);
_logService.Verify(s => s.Log(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<Exception>()), Times.Exactly(2));


Get By Id

var webStore = new WebStore { WebStoreId = 1 };
           _unitOfWork.Setup(x => x.GetRepository<WebStore>().GetById(It.IsAny<int>())).Returns(webStore);


Parameters

[TestCase(false, false, false, false, "Domain1,Domain2")]
        [TestCase(false, false, true, true, "Domain1")]
        [TestCase(true, true, false, false, "Domain2")]
        [TestCase(false, true, false, true, "")]
        [TestCase(true, false, true, false, "")]
        [TestCase(true, true, true, true, "")]
        [Test]
        public void GetWebstoreDomains_WhenWebStoreDomainWithDifferentValues_ReturnWebstore(bool isErrorOccured1, bool isDeleted1, bool isErrorOccured2, bool isDeleted2, string expectedResults)
        {
            // Arrange 
            WebStore webStore = new WebStore
            {
                StoreDomains = new List<WebStoreDomain>
                {
                    new WebStoreDomain{  WebStoreDomainName = "Domain1",IsCustomDomainBindingErrorOccured=isErrorOccured1 ,IsDeleted=isDeleted1},
                    new WebStoreDomain{  WebStoreDomainName = "Domain2",IsCustomDomainBindingErrorOccured=isErrorOccured2 ,IsDeleted=isDeleted2}
                }
            };
            //Act
            var result = migrationHelperService.GetWebstoreDomains(webStore);
 
            // Assert            
            Assert.That(result, Is.EqualTo(expectedResults));
        }


var listWebstore = new List<WebStore>() { new WebStore { WebStoreId = 1, CustomerName = "customerName" } };
 
            _unitOfWork.Setup(x => x.GetRepository<WebStore>()
                .Get(It.IsAny<Expression<Func<WebStore, bool>>>(), It.IsAny<Func<IQueryable<WebStore>,
                IOrderedQueryable<WebStore>>>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
                .Returns(listWebstore);


Sample Method

[Test] // null handle
        public void EnvironmentEligibility_WhenWebStoreIsNull_ReturnWebstore()
        {
            // Arrange
            WebStore webStore = null;
 
            //Act
            var result = piwikTrackerService.EnvironmentEligibility(webStore);
 
            // Assert
            Assert.IsFalse(result);
        }


verify

_unitOfWork.Verify(uow => uow.SaveChanges(_principalUser.Object), Times.Once);
_unitOfWork.Verify(uow => uow.GetRepository<WebstoreResourceAllocation>().Get(It.IsAny<Expression<Func<WebstoreResourceAllocation, bool>>>(), It.IsAny<Func<IQueryable<WebstoreResourceAllocation>,
      IOrderedQueryable<WebstoreResourceAllocation>>>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never);


Date passing as parameters

private static IEnumerable DataWhenScheduleDateTimeLessThanCurrentDate()
       {
           yield return new TestCaseData(new DateTime(2010, 12, 5), new DateTime(2012, 12, 5));
           yield return new TestCaseData(new DateTime(2010, 12, 5), DateTime.Today);
       }
 
 [TestCaseSource(typeof(ClusterUpgradeHelperServiceTest), "DataWhenScheduleDateTimeLessThanCurrentDate")]
 [Test]
 public void GetPendingRewriteRuleBindRequestedWebstore_WhenScheduleDateTimeLessThanCurrentDate_ReturnObject(DateTime scheduledDate, DateTime date)
 {
    // Arrange
 
           var webStore = new WebStore { WebStoreId = 1, WebStoreStateId = (int)WebstoreStatus.BindRedirectUrlRequested };
           var redirectScheduleList = new List<RedirectSchedule>()
           {
               new RedirectSchedule
               {
                   WebstoreId=1,
                   IsExecuted = false,IsBindRedirectUrlApproved =true ,
                   Webstore = webStore,
                   ScheduledDate =scheduledDate
               }
           };
           _unitOfWork.Setup(x => x.GetRepository<RedirectSchedule>()
               .Get(It.IsAny<Expression<Func<RedirectSchedule, bool>>>(), It.IsAny<Func<IQueryable<RedirectSchedule>,
               IOrderedQueryable<RedirectSchedule>>>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
               .Returns(redirectScheduleList);
 
           _timeZoneService.Setup(x => x.GetCurrentDateTimeByTimeZoneId(It.IsAny<string>())).Returns(date);
 
           //Act
           var result = rewriteRuleHelperService.GetPendingRewriteRuleBindRequestedWebstore();
 
           // Assert
           Assert.IsNotNull(result);
       }


List Null Or Empty 

private static IEnumerable DataWhenWebStoreTemporaryDatabaseUserListEmptyOrNull()
        {
            yield return new TestCaseData(null);
            yield return new TestCaseData(new List<WebStoreTemporaryDatabaseUser>());
        }
 
        [Test] //?.ToList()
        [TestCaseSource(typeof(TemporaryDatabaseUserHelperServiceTest), "DataWhenWebStoreTemporaryDatabaseUserListIsEmptyOrNull")]
        public void CreateTemporaryDatabaseUser_WhenWebStoreTemporaryDatabaseUserListIsEmptyOrNull_IsVerified(List<WebStoreTemporaryDatabaseUser> dbUserList)
        {
            _unitOfWork.Setup(x => x.GetRepository<WebStoreTemporaryDatabaseUser>()
                .Get(It.IsAny<Expression<Func<WebStoreTemporaryDatabaseUser, bool>>>(), It.IsAny<Func<IQueryable<WebStoreTemporaryDatabaseUser>,
                IOrderedQueryable<WebStoreTemporaryDatabaseUser>>>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
                .Returns(dbUserList);
 
            //Act
            TemporaryDatabaseUserHelperService.CreateTemporaryDatabaseUser();
 
            // Assert
            _unitOfWork.Verify(uow => uow.SaveChanges(_principalUser.Object), Times.Never);
        }


_principalUser.Setup(x => x.Identity.Name).Returns("A");


Dictionary / IIndex mocking

var _processorDictionary = new Mock<IIndex<ProcessorTypes, IExecuteProcessor>>();
            var _listProcessResponse = new List<ProcessResponse> { new ProcessResponse { ResponseText = "Sample Response text", ErrorText = string.Empty } };
            Mock<IExecuteProcessor> _executeProcessor = new Mock<IExecuteProcessor>();
            _executeProcessor.Setup(x => x.ExecuteProcess(It.IsAny<string[]>(), It.IsAny<int>())).Returns(_listProcessResponse);           
            _processorDictionary.Setup(x => x[It.IsAny<ProcessorTypes>()]).Returns(_executeProcessor.Object);


How to return Null object 

_azure.Setup(x => x.WebApps.GetById(It.IsAny<string>())).Returns((IWebApp)null);


complex item mock :- AksClusterInstallationServiceTest

[Test]  // null handle required.
        public void Install_IsValidSubnetDeploymentTrueAndClusterVnetCreationReturnsNull_ReturnFalseResponseObject()
        {
            // Arrange
            var cluster = new AKSCluster()
            {
                Region = new Region() { Name = "SEA" },
                InstallationProfile = new WebstoreInstallationProfile() { SanaRegionCode = "SEA" },
                VnetAddressSpace = "VnetAddressSpace",
                VnetSubnetAddress = "VnetSubnetAddress"
            };
            _clusterCommonService.Setup(x => x.GetAksClusterVnetResourceName(It.IsAny<string>())).Returns("ResourceName");
            _clusterCommonService.Setup(x => x.GetAksClusterResourceGroupName(It.IsAny<AKSCluster>())).Returns("ResourceGroupName");
            var _azure = new Mock<IAzure>();
            var _blank = new Mock<IBlank>();
            var _withGroup = new Mock<IWithGroup>();
            var _withCreate = new Mock<IWithCreate>();
            var _withCreateAndSubnet = new Mock<IWithCreateAndSubnet>();
            var _creatable = new Mock<ICreatable<INetwork>>();
 
 
            _blank.Setup(c => c.WithRegion(It.IsAny<string>())).Returns(_withGroup.Object);
            _withGroup.Setup(c => c.WithNewResourceGroup(It.IsAny<string>())).Returns(_withCreate.Object);
            _withCreate.Setup(c => c.WithAddressSpace(It.IsAny<string>())).Returns(_withCreateAndSubnet.Object);
            _withCreateAndSubnet.Setup(c => c.WithSubnet(It.IsAny<string>(), It.IsAny<string>())).Returns(_withCreateAndSubnet.Object);
            _creatable.Setup(c => c.Create()).Returns(new Mock<INetwork>().Object);
            _azure.Setup(c => c.Networks.Define(It.IsAny<string>())).Returns(_blank.Object);
 
            _clusterHelperService.Setup(x => x.IsValidClusterDeployment(It.IsAny<AKSCluster>())).Returns(true);
            _clusterHelperService.Setup(x => x.IsValidSubnetDeployment(It.IsAny<AKSCluster>(), It.IsAny<string>())).Returns(true); // Set to False
            _authenticationService.Setup(x => x.AzureAuthentication(It.IsAny<WebstoreInstallationProfile>())).Returns(_azure.Object);
  
            
            // Act
            var result = aksClusterInstallationService.Install(cluster);
 
            // Assert
            Assert.IsFalse(result.IsSuccess);
        }



mock Static methods

https://stackoverflow.com/questions/12580015/how-to-mock-static-methods-in-c-sharp-using-moq-framework



Platform UI description




after adding the release package, at what date need to be the pick for the upgrade. 

it will add a record to DB,


UpgradeWeb job

SanaUpgradeLoadBalancer : 

it will schedule the ring update to  the new version.


first will run load balancer 

Thenk upgrade ring will pick sheduled time





Code level testing (activate)

 


D:\development\SanaPlatform\Sana.Platform.Portal\Scripts\Portal\Webstore\webstore.AllWebstores.js

it will call  url: "/Webstore/Retry",

Sana.Platform.Portal\Controllers\WebstoreController.cs > Retry(int webstoreId)


Sana.Platform.Portal\Controllers\APIControllers\WebstoreApiController.cs > Retry(int webstoreId)


Sana.Platform.Business\Portal\Implementation\WebstoreService.cs >  Retry(int storeId)


request will be add as a item on Azure queue.

Sana.Platform.Business\Infrastructure\AzureStorageQueue.cs















Code level testing (deactivate)

 

Test deactivate 

When Click deactivate button  -->
img1


 
1/Sana.Platform.Portal\Scripts\Portal\ApprovalRequest\webstore.WebstoreDeactivate.Index.js

url: "/Approval/UpdateWebstoreDeactivationApprovalFeedBack",


img2


2/when click "Are you sure you want to deactivate popup" yes > go to Approval section (img2)

When Click Approval section > Deactivate  (img2)

Approval controller /WebstoreDeactivateRequests.cs

ApproveApiController/GetWebstoreDeactivationRequests()

img3


3/if click Approve or Reject

Approval controller /UpdateWebstoreDeactivationApprovalFeedBack

ApproveApiController/ProcessWebstoreDeactivationRequest

WebstoreDeactivationApprovalProvider/ApproveOrRejectChangeRequestAsync


4/then it will go to queue (pending list)

need run Job To Deactivate 

D:\development\SanaPlatform\Sana.Platform.Jobs\Task\Sana.Platform.Jobs.DeactivateWebstore




right click > Debug > New Instance

it will run Deactivatewebstore.exe on the console.

if there are any queue (pending list) items it will run automatically.

Application > Run() method.











run Job when install websore local []

 


Sana.Platform.Jobs.SanaInstallation > debug > start new instanse.




bstore'.'
[502] 1. Job Started.

87 fileHelperService.CleanFiles(webstore);
[502] 2. Cleaning Temporary files.  [0s]
[502] 3. Temporary files were deleted.  [0.004s]

92 webstoreUninstallService.ExecuteUninstall(webstore);
[502] 4. Uninstall Webstore Resources Execution started.  [0.332s]
[502] 5. Aks app uninstallation started.  [0.003s]
[502] 6. Check deployment status started.  [0.001s]
[502] 7. Check deployment status completed.  [2.158s]
[502] 8. RemoveAzureDataBaseResources Execution started.  [0.057s]
[502] 9. RemoveAzureDataBaseResources Execution completed.  [4.967s]
[502] 10. RemoveStorageContainers Execution started.  [0.001s]
[502] 11. Removing blob backups.  [4.325s]
[502] 12. Requesting timestamps.  [0.002s]
[502] 13. Timestamp received.  [0s]
[502] 14. Requesting blob containers.  [0.031s]
[502] 15. Blob containers received.  [0s]
[502] 16. Blob backup removed.  [0s]
[502] 17. RemoveStorageContainers Execution completed.  [0s]
[502] 18. RemoveDNSRecord Execution started.  [0.002s]
[502] 19. RemoveDNSRecord Execution completed.  [4.979s]
[502] 20. Revoking the requested/previous license.  [0.021s]
[502] 21. License request started.  [0.001s]
[502] 22. License request completed.  [0.856s]
[502] 23. Requested/Previous license revoked.  [1.891s]
[502] 24. Error: uninstall: Release not loaded: 502-scczbn2fjbzl21-license: release: not found
  [1.202s]
[502] 25. Uninstall Webstore Resources Execution succeeded.  [0.001s]
[502] 26. Remove automatic upgrade record started.  [0.004s]
[502] 27. Remove automatic upgrade record completed.  [0.033s]
[502] 28. Cleaning Temporary files.  [0.006s]
[502] 29. Temporary files were deleted.  [0s]

93 installationHelperService.ExecuteInstallation(webstore);
[502] 30. Add dns record started  [0.07s]
[502] 31. Add dns record completed  [5.568s]
[502] 32. Starting database installation.  [0.006s]
[502] 33. Deploying database using arm.  [0.019s]
[502] 34. Requesting database resource parameters.  [0.001s]
[502] 35. Database resource parameters received  [0.077s]
[502] 36. Database deployed using arm.  [67.502s]
[502] 37. Creating new database user.  [0.001s]
[502] 38. Database user created.  [2.556s]
[502] 39. Creating initial structure with data.  [0.001s]
[502] 40. Initial structure created with data.  [50.682s]
[502] 41. Creating website domain.  [0.002s]
[502] 42. Webstore domain created.  [0.299s]
[502] 43. Creating default user in azure.  [0.001s]
[502] 44. Default user created in azure.  [0.306s]
[502] 45. Setting default ERP language.  [0.001s]
[502] 46. Default ERP language applied.  [0.216s]
[502] 47. Generate values.yaml configuration file.  [0.026s]
[502] 48. Generate values.yaml configuration file completed.  [0.133s]
[502] 49. Requesting sana license.  [0.001s]
[502] 50. License request started.  [0.038s]
[502] 51. License request completed.  [0.73s]
[502] 52. Sana license received.  [0s]
[502] 53. Release "502-scczbn2fjbzl21-license" does not exist. Installing it now.
NAME: 502-scczbn2fjbzl21-license
LAST DEPLOYED: Mon Sep 27 11:31:39 2021
NAMESPACE: 502-scczbn2fjbzl21
STATUS: deployed
REVISION: 1
TEST SUITE: None
  [3.523s]
[502] 54. Copying helm template files started.  [0.042s]
[502] 55. Copying helm template files completed.  [0.011s]
[502] 56. Generate values.yaml configuration file.  [0.001s]
[502] 57. Generate values.yaml configuration file completed.  [0.012s]
[502] 58. Install app in Aks started.  [0.001s]
[502] 59. Release "502-scczbn2fjbzl21-apphosting" does not exist. Installing it now.
NAME: 502-scczbn2fjbzl21-apphosting
LAST DEPLOYED: Mon Sep 27 11:31:42 2021
NAMESPACE: 502-scczbn2fjbzl21
STATUS: deployed
REVISION: 1
TEST SUITE: None
  [2.585s]
[502] 60. Install app in Aks completed.  [0.001s]
[502] 61. Applying app settings : scczbn2fjbzl21  [0.007s]
[502] 62. Generate values.yaml configuration file.  [0.121s]
[502] 63. Generate values.yaml configuration file completed.  [0.062s]
[502] 64. Release "502-scczbn2fjbzl21-app" does not exist. Installing it now.
NAME: 502-scczbn2fjbzl21-app
LAST DEPLOYED: Mon Sep 27 11:31:45 2021
NAMESPACE: 502-scczbn2fjbzl21
STATUS: deployed
REVISION: 1
TEST SUITE: None
  [2.976s]
[502] 65. Cleaning Temporary files.  [20.005s]
[502] 66. Temporary files were deleted.  [0.003s]
[502] 67. App settings applied : scczbn2fjbzl21  [0s]
[502] 68. Bind custom domain : testabone.sana-test-cloud.net to aks app  started  [0.008s]
[502] 69. Domain chart files copying started  [0.001s]
[502] 70. Domain chart files copying completed  [0.01s]
[502] 71. Save pfx file started  [0.001s]
[502] 72. Save pfx file completed  [0.011s]
[502] 73. Generate cert.pem started  [0.001s]
[502] 74. Generate cert.pem completed  [0.108s]
[502] 75. Generate key.pem started  [0.001s]
[502] 76. Generate key.pem completed  [0.049s]
[502] 77. Generate values.yaml configuration file started.  [0.001s]
[502] 78. Generate values.yaml configuration file completed.  [0.006s]
[502] 79. Execute helm release started.  [0.001s]
[502] 80. Delete deployment started  [0.004s]
[502] 81. Error: uninstall: Release not loaded: 877-testabonesanatestcloudnet: release: not found
  [0.66s]
[502] 82. Delete deployment completed  [0.001s]
[502] 83. NAME: 877-testabonesanatestcloudnet
LAST DEPLOYED: Mon Sep 27 11:32:08 2021
NAMESPACE: 502-scczbn2fjbzl21
STATUS: deployed
REVISION: 1
TEST SUITE: None
  [3.056s]
[502] 84. Check deployment status started.  [0.002s]
[502] 85. Check deployment status completed.  [0.782s]
[502] 86. Execute helm release completed.  [0.001s]
[502] 87. Bind custom domain : testabone.sana-test-cloud.net to aks app completed  [0.001s]
[502] 88. Update web app domain table.  [0.003s]
[502] 89. Update web app domain table completed.  [0.327s]

95 installationHelperService.BridgeFileConfiguration(webstore);
96 installationHelperService.CheckWebstoreAvailability(webstore);
[502] 90. Check webstore availability request #0  [0.028s]
[502] 91. Check webstore availability completed  [9.445s]

97 installationHelperService.SendWebstoreMailInfo(webstore);
[502] 92. Send webstore information to hosting started  [0.016s]
[502] 93. Send webstore information to hosting completed  [0.055s]
[502] 94. Send general webstore information started  [0.001s]
[502] 95. Send general webstore information completed  [0.003s]

99 fileHelperService.CleanFiles(webstore);
[502] 96. Cleaning Temporary files.  [0.009s]
[502] 97. Temporary files were deleted.  [0.002s]

104 logService.SaveLog(webstoreId, user, LogType.Installation);
[502] 98. Job Finished.