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