public void BeforeEach() { mockDataRepo = MoqHelpers.CreateMockDataRepository(); mockScopeBL = new Mock <IScopeBusinessLogic>(); mockFileRepo = new Mock <IFileRepository>(); _mockDraftFileBL = new Mock <IDraftFileBusinessLogic>(); }
public void BeforeEach() { _mockDataRepo = MoqHelpers.CreateMockDataRepository(); _mockSearchRepo = new Mock <ISearchRepository <EmployerSearchModel> >(); _mockSearchSicCodeRepo = new Mock <ISearchRepository <SicCodeSearchModel> >(); _mockCommonLogic = new Mock <ISharedBusinessLogic>(); }
public void BeforeEach() { mockDataRepo = MoqHelpers.CreateMockDataRepository(); ; mockFileRepo = new Mock <IFileRepository>(); testSearchBL = new SearchBusinessLogic(testSearchRepo, Mock.Of <ISearchRepository <SicCodeSearchModel> >(), Mock.Of <IAuditLogger>()); // setup mocks ans ensures they call their implementations. (We override calls per test when need be!) mockScopeBL = new Mock <ScopeBusinessLogic>(testCommonBL, mockDataRepo.Object, testSearchBL); mockScopeBL.CallBase = true; mockOrganisationBL = new Mock <OrganisationBusinessLogic>( testCommonBL, mockDataRepo.Object, new Mock <ISubmissionBusinessLogic>().Object, new Mock <IScopeBusinessLogic>().Object, new Mock <IEncryptionHandler>().Object, new Mock <ISecurityCodeBusinessLogic>().Object, new Mock <IObfuscator>().Object); mockOrganisationBL.CallBase = true; // service under test testScopePresenter = new ScopePresenter(mockScopeBL.Object, mockDataRepo.Object, mockOrganisationBL.Object, testCommonBL); }
public void SavesComparedEmployersToCookie() { // Arrange var AppendWasCalled = false; mockHttpContext.Setup(x => x.Request.Cookies[It.Is <string>(arg => arg == CookieNames.LastCompareQuery)]) .Returns("12345678"); var testPresenter = new ComparePresenter( MoqHelpers.CreateIOptionsSnapshotMock(new ViewingOptions()), mockHttpContextAccessor.Object, Mock.Of <IHttpSession>()); var testIds = new[] { "AAA", "BBB", "CCC" }; testPresenter.AddRangeToBasket(testIds); mockHttpContext.Setup( x => x.Response.Cookies.Append( It.Is <string>(arg => arg == CookieNames.LastCompareQuery), It.IsAny <string>(), It.IsAny <CookieOptions>())) .Callback( (string key, string value, CookieOptions options) => { // Assert Assert.AreEqual(string.Join(",", testIds), value); AppendWasCalled = true; }); // Act testPresenter.SaveComparedEmployersToCookie(null); // Assert Assert.IsTrue(AppendWasCalled); }
public void BeforeEach() { mockSharedBusinessLogic = MoqHelpers.CreateFakeSharedBusinessLogic(); mockDataRepo = MoqHelpers.CreateMockDataRepository(); mockScopeBL = new Mock <IScopeBusinessLogic>(); mockDraftFileBL = new Mock <IDraftFileBusinessLogic>(); }
public async Task ViewingService_BySectorType_Null_Or_Empty_Search_Returns_Zero( string nullWhitespaceOrEmptySearchKeyWords) { // Arrange var mockDataRepo = MoqHelpers.CreateMockDataRepository(); const SearchTypes searchType = SearchTypes.BySectorType; var mockViewingService = new Mock <IViewingService>(); mockViewingService.Setup(m => m.SearchBusinessLogic.EmployerSearchRepository).Returns(_azureSearchRepo); var testPresenter = new ViewingPresenter(mockViewingService.Object, Mock.Of <ISharedBusinessLogic>()); var mockedSearchParameters = Mock.Of <EmployerSearchParameters>( x => x.Keywords == nullWhitespaceOrEmptySearchKeyWords && x.Page == 1 && x.SearchType == searchType); // Act var result = await testPresenter.SearchAsync(mockedSearchParameters); // Assert var actualNumberOfRecords = result.Employers.ActualRecordTotal; Assert.AreEqual( 0, actualNumberOfRecords, $"Expected term [{nullWhitespaceOrEmptySearchKeyWords}], when searching {searchType} to return no records."); }
public async Task ReportCountIsControlledBySubmissionOptions(SectorTypes testSector, int testEditableReportCount) { // Arrange var testConfig = new SubmissionOptions { EditableReportCount = testEditableReportCount }; var testOrg = new Organisation { OrganisationId = 1, SectorType = testSector }; var testUserOrg = new UserOrganisation { Organisation = testOrg }; DateTime testSnapshotDate = mockSharedBusinessLogic.GetAccountingStartDate(testOrg.SectorType); var mockService = new Mock <SubmissionPresenter>( mockDataRepo.Object, mockScopeBL.Object, null, mockDraftFileBL.Object, MoqHelpers.CreateIOptionsSnapshotMock(testConfig)); // Call the real functions unless overridden mockService.CallBase = true; // Act SubmissionPresenter testService = mockService.Object; List <ReportInfoModel> actualResults = await testService.GetAllEditableReportsAsync(testUserOrg, testSnapshotDate); // Assert Assert.AreEqual( testEditableReportCount, actualResults.Count, $"Expected editable report count to be {testEditableReportCount}"); }
private static IContainer BuildContainerIoC(params object[] dbObjects) { var builder = new ContainerBuilder(); builder.RegisterType <Jobs.Functions>().InstancePerDependency(); //Create an in-memory version of the database if (dbObjects != null && dbObjects.Length > 0) { builder.RegisterInMemoryTestDatabase(dbObjects); } else { var mockDataRepo = MoqHelpers.CreateMockDataRepository(); builder.Register(c => mockDataRepo.Object).As <IDataRepository>().InstancePerLifetimeScope(); } builder.Register(c => Mock.Of <ICompaniesHouseAPI>()).As <ICompaniesHouseAPI>().SingleInstance(); builder.Register(c => Mock.Of <ISearchServiceClient>()).As <ISearchServiceClient>().SingleInstance(); //Create the mock repositories builder.Register(c => new MockFileRepository()).As <IFileRepository>().SingleInstance(); builder.Register(c => new MockSearchRepository()).As <ISearchRepository <EmployerSearchModel> >() .SingleInstance(); builder.RegisterType(typeof(AzureSicCodeSearchRepository)).As <ISearchRepository <SicCodeSearchModel> >() .SingleInstance(); // BL Services builder.RegisterInstance(ConfigHelpers.Config).SingleInstance(); builder.RegisterType <SharedBusinessLogic>().As <ISharedBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <ScopeBusinessLogic>().As <IScopeBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <SubmissionBusinessLogic>().As <ISubmissionBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <SecurityCodeBusinessLogic>().As <ISecurityCodeBusinessLogic>() .InstancePerLifetimeScope(); builder.RegisterType <OrganisationBusinessLogic>().As <IOrganisationBusinessLogic>() .InstancePerLifetimeScope(); builder.RegisterType <SearchBusinessLogic>().As <ISearchBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <UpdateFromCompaniesHouseService>().As <UpdateFromCompaniesHouseService>() .InstancePerLifetimeScope(); //Register some singletons builder.RegisterType <InternalObfuscator>().As <IObfuscator>().SingleInstance() .WithParameter("seed", ConfigHelpers.SharedOptions.ObfuscationSeed); builder.RegisterType <EncryptionHandler>().As <IEncryptionHandler>().SingleInstance(); builder.Register(c => Mock.Of <IMessenger>()).As <IMessenger>().SingleInstance(); builder.Register(c => Mock.Of <IGovNotifyAPI>()).As <IGovNotifyAPI>().SingleInstance(); builder.RegisterInstance(new NullLoggerFactory()).As <ILoggerFactory>().SingleInstance(); builder.RegisterGeneric(typeof(Logger <>)) .As(typeof(ILogger <>)) .SingleInstance(); SetupHelpers.SetupMockLogRecordGlobals(builder); return(builder.Build()); }
public void BeforeEach() { // setup mocks mockDataRepository = MoqHelpers.CreateMockDataRepository(); // sut scopeBusinessLogic = new WebUI.BusinessLogic.Services.ScopeBusinessLogic(mockDataRepository.Object); }
public async Task OrganisationBusinessLogic_GetCompareData_Leaves_Null_Values_At_The_Bottom_Of_The_ListAsync() { // Arrange var listOfReturns = GetFourOrgsWithVariousReturns(); var listOfOrgs = listOfReturns.Select(ret => ret.Organisation); var mockedDataRepository = MoqHelpers.CreateMockDataRepository(); mockedDataRepository.SetupGetAll(listOfOrgs, listOfReturns); var dataRepository = mockedDataRepository.Object; var mockedSharedBusinessLogic = Get <ISharedBusinessLogic>(); var submissionBusinessLogic = new SubmissionBusinessLogic(mockedSharedBusinessLogic, dataRepository, Mock.Of <IRecordLogger>()); var mockedScopeBusinessLogic = Get <IScopeBusinessLogic>(); var mockedSecurityCodeBusinessLogic = Get <ISecurityCodeBusinessLogic>(); var mockedEncryptionHandler = Get <IEncryptionHandler>(); var mockedObfuscator = Get <IObfuscator>(); var mockedDnBRepo = Get <IDnBOrgsRepository>(); var organisationBusinessLogic = new OrganisationBusinessLogic( mockedSharedBusinessLogic, dataRepository, submissionBusinessLogic, mockedScopeBusinessLogic, mockedEncryptionHandler, mockedSecurityCodeBusinessLogic, mockedDnBRepo, mockedObfuscator); var listEncOrgIds = listOfReturns.Select(x => mockedObfuscator.Obfuscate(x.OrganisationId.ToString())); var year = 2017; var sortColumn = "DiffMedianBonusPercent"; var sortAscending = true; // Act var data = await organisationBusinessLogic.GetCompareDataAsync( listEncOrgIds, year, sortColumn, sortAscending); // Assert }
GetViewModelForSubmission_Given_a_new_submission_Then_returns_empty_model_with_org_id_and_reporting_date_onlyAsync() { var testUserId = 123; int testYear = VirtualDateTime.Now.AddYears(-1).Year; // Mocks var testOrganisation = new Organisation { OrganisationId = 524124, SectorType = SectorTypes.Private }; mockDataRepo.Setup(dr => dr.GetAll <UserOrganisation>()) .Returns( new[] { new UserOrganisation { UserId = testUserId, OrganisationId = testOrganisation.OrganisationId, Organisation = testOrganisation } }.AsQueryable() .BuildMock() .Object); mockDataRepo.Setup(dr => dr.GetAll <Return>()) .Returns(new Return[] { }.AsQueryable().BuildMock().Object); var testDraftFileFileBusinessLogic = new DraftFileBusinessLogic(MoqHelpers.CreateMockDataRepository().Object); Draft actualDraftFile = testDraftFileFileBusinessLogic.GetExistingOrNew( testOrganisation.OrganisationId, testYear, testUserId); var testService = new SubmissionService( mockDataRepo.Object, mockScopeBL.Object, testDraftFileFileBusinessLogic); // Test ReturnViewModel actualModel = await testService.GetReturnViewModelAsync(testOrganisation.OrganisationId, testYear, testUserId); // Assert Assert.NotNull(actualModel); Assert.AreEqual(testOrganisation.OrganisationId, actualModel.OrganisationId); Assert.AreEqual(testYear, actualModel.AccountingDate.Year); testDraftFileFileBusinessLogic.DiscardDraft(actualDraftFile, null, true); }
/* These do NOT return results - in other words, need further investigation */ // [TestCase("J C B", 733)] // [TestCase("ricewater", 99999)] // searching for 'pricewaterhousecoopers' :: middle of the word, 'infix' search in azure search needs further investigation. // https://social.msdn.microsoft.com/Forums/en-US/dbbc078d-af02-4d90-b213-944fd77c9213/how-to-use-wildcard-like-contains-search-in-azure-search // https://social.msdn.microsoft.com/Forums/azure/en-US/c23446db-17af-4b99-b76f-1a6b006612a3/azure-search-net-sdk-filter-and-startwith // https://stackoverflow.com/questions/40056213/behavior-of-asterisk-in-azure-search-service // https://stackoverflow.com/questions/40857057/how-to-practially-use-a-keywordanalyzer-in-azure-search public async Task ViewingService_Search_Returns_At_Least_One_Result(string searchKeyWords, int expectedOrganisationId) { // Arrange var mockDataRepo = MoqHelpers.CreateMockDataRepository(); var mockViewingService = new Mock <IViewingService>(); mockViewingService.Setup(m => m.SearchBusinessLogic.EmployerSearchRepository).Returns(_azureSearchRepo); var testPresenter = new ViewingPresenter(mockViewingService.Object, Mock.Of <ISharedBusinessLogic>()); var mockedSearchParameters = Mock.Of <EmployerSearchParameters>( x => x.Keywords == searchKeyWords && x.Page == 1 && x.SearchType == SearchTypes.ByEmployerName); // Act var result = await testPresenter.SearchAsync(mockedSearchParameters); // Assert var totalNumberOfRecordsFound = result.Employers.ActualRecordTotal; Assert.GreaterOrEqual( totalNumberOfRecordsFound, 1, $"Expected term [{searchKeyWords}] to return at least one record."); var organisationFound = result.Employers.Results.FirstOrDefault(x => x.OrganisationId == expectedOrganisationId.ToString()); Assert.NotNull( organisationFound, $"Search term \"{searchKeyWords}\" should have returned organisationId {expectedOrganisationId} within its list of results but it was NOT FOUND"); var organisationPosition = result.Employers.Results.IndexOf(organisationFound); Assert.LessOrEqual( organisationPosition, 10, $"Search term \"{searchKeyWords}\" should have returned organisationId {expectedOrganisationId} within the top 10 list of results but it was present in position {organisationPosition}"); // This last assertion is to make sure that the search term hasn't returned the whole database - some 11k records (so to confirmed that the query was NOT transformed to be a search 'all', search=*) Assert.LessOrEqual(totalNumberOfRecordsFound, 9000); }
public void LoadsEmployersFromCookie(params string[] expectedEmployerIds) { // Arrange mockHttpContext.Setup(x => x.Request.Cookies[It.Is <string>(arg => arg == CookieNames.LastCompareQuery)]) .Returns(string.Join(",", expectedEmployerIds)); var testPresenter = new ComparePresenter( MoqHelpers.CreateIOptionsSnapshotMock(new ViewingOptions()), mockHttpContextAccessor.Object, Mock.Of <IHttpSession>()); // Act testPresenter.LoadComparedEmployersFromCookie(); // Assert Assert.AreEqual( expectedEmployerIds.Length, testPresenter.BasketItemCount, $"Expected basket to contain {expectedEmployerIds.Length} employers"); Assert.IsTrue(testPresenter.ComparedEmployers.Value.Contains(expectedEmployerIds), "Expected employer ids to match basket items"); }
public void BeforeEach() { // setup mocks mockDataRepository = MoqHelpers.CreateMockDataRepository(); var mockedSnapshotDateHelper = Get <ISnapshotDateHelper>(); var mockedSourceComparer = Get <ISourceComparer>(); var mockedSendEmailService = Get <ISendEmailService>(); var mockedNotificationService = Get <INotificationService>(); var mockedFileRepository = Get <IFileRepository>(); var mockedDataRepository = Get <IDataRepository>(); mockSharedBusinessLogic = new SharedBusinessLogic(mockedSnapshotDateHelper, mockedSourceComparer, mockedSendEmailService, mockedNotificationService, mockedFileRepository, mockedDataRepository); // sut scopeBusinessLogic = new Submission.ScopeBusinessLogic( mockSharedBusinessLogic, mockDataRepository.Object, null, null); }
public void OrganisationBusinessLogic_GetCompareData_Leaves_Null_Values_At_The_Bottom_Of_The_List() { // Arrange List <Return> listOfReturns = GetFourOrgsWithVariousReturns(); IEnumerable <Organisation> listOfOrgs = listOfReturns.Select(ret => ret.Organisation); Mock <IDataRepository> mockedDataRepository = MoqHelpers.CreateMockDataRepository(); mockedDataRepository.SetupGetAll(listOfOrgs, listOfReturns); IDataRepository dataRepository = mockedDataRepository.Object; var submissionBusinessLogic = new SubmissionBusinessLogic(dataRepository); var mockedEncryptionHandler = Get <IEncryptionHandler>(); var mockedObfuscator = Get <IObfuscator>(); var organisationBusinessLogic = new OrganisationBusinessLogic( dataRepository, submissionBusinessLogic, mockedEncryptionHandler, mockedObfuscator); IEnumerable <string> listEncOrgIds = listOfReturns.Select(x => mockedObfuscator.Obfuscate(x.OrganisationId.ToString())); var year = 2017; var sortColumn = "DiffMedianBonusPercent"; var sortAscending = true; // Act IEnumerable <CompareReportModel> data = organisationBusinessLogic.GetCompareData( listEncOrgIds, year, sortColumn, sortAscending); // Assert }
public async Task ViewingService_Search_Ignores_Terms_Limited_And_Uk_(string searchKeyWords, int maxNumberOfRecordsExpected) { // Arrange var mockDataRepo = MoqHelpers.CreateMockDataRepository(); var mockViewingService = new Mock <IViewingService>(); mockViewingService.Setup(m => m.SearchBusinessLogic.EmployerSearchRepository).Returns(_azureSearchRepo); var testPresenter = new ViewingPresenter(mockViewingService.Object, Mock.Of <ISharedBusinessLogic>()); var mockedSearchParameters = Mock.Of <EmployerSearchParameters>( x => x.Keywords == searchKeyWords && x.Page == 1 && x.SearchType == SearchTypes.ByEmployerName); // Act var result = await testPresenter.SearchAsync(mockedSearchParameters); // Assert var totalNumberOfRecordsFound = result.Employers.ActualRecordTotal; Assert.LessOrEqual(totalNumberOfRecordsFound, maxNumberOfRecordsExpected); }
public void BeforeEach() { // setup mocks mockDataRepository = MoqHelpers.CreateMockDataRepository(); var mockedSnapshotDateHelper = Get <ISnapshotDateHelper>(); var mockedSourceComparer = Get <ISourceComparer>(); var mockedSendEmailService = Get <ISendEmailService>(); var mockedNotificationService = Get <INotificationService>(); var mockedFileRepository = Get <IFileRepository>(); var mockedDataRepository = Get <IDataRepository>(); mockSharedBusinessLogic = new SharedBusinessLogic(mockedSnapshotDateHelper, mockedSourceComparer, mockedSendEmailService, mockedNotificationService, mockedFileRepository, mockedDataRepository); // setup data var currentPrivateSnapshotDate = mockSharedBusinessLogic.GetAccountingStartDate(SectorTypes.Private); var currentPublicSnapshotDate = mockSharedBusinessLogic.GetAccountingStartDate(SectorTypes.Public); testOrgs = new List <Organisation>(); testOrgs.Add(CreateOrgWithExistingScopeForAllYears(1, SectorTypes.Private, currentPrivateSnapshotDate)); testOrgs.Add(CreateOrgWithExistingScopeForAllYears(2, SectorTypes.Public, currentPublicSnapshotDate)); testOrgs.Add(CreateOrgWithMissingScopesForAllYears(3, SectorTypes.Private)); testOrgs.Add(CreateOrgWithMissingScopesForAllYears(4, SectorTypes.Public)); testOrgs.Add(CreateOrgWithUnknownScopesForAllYears(5, SectorTypes.Private, currentPrivateSnapshotDate)); testOrgs.Add(CreateOrgWithUnknownScopesForAllYears(6, SectorTypes.Public, currentPublicSnapshotDate)); mockDataRepository.SetupGetAll(testOrgs); // sut scopeBusinessLogic = new Submission.ScopeBusinessLogic( mockSharedBusinessLogic, mockDataRepository.Object, null, null); }
public void BeforeEach() { // setup mocks mockDataRepository = MoqHelpers.CreateMockDataRepository(); // setup data DateTime currentPrivateSnapshotDate = SectorTypes.Private.GetAccountingStartDate(); DateTime currentPublicSnapshotDate = SectorTypes.Public.GetAccountingStartDate(); testOrgs = new List <Organisation>(); testOrgs.Add(CreateOrgWithExistingScopeForAllYears(1, SectorTypes.Private, currentPrivateSnapshotDate)); testOrgs.Add(CreateOrgWithExistingScopeForAllYears(2, SectorTypes.Public, currentPublicSnapshotDate)); testOrgs.Add(CreateOrgWithMissingScopesForAllYears(3, SectorTypes.Private)); testOrgs.Add(CreateOrgWithMissingScopesForAllYears(4, SectorTypes.Public)); testOrgs.Add(CreateOrgWithUnknownScopesForAllYears(5, SectorTypes.Private, currentPrivateSnapshotDate)); testOrgs.Add(CreateOrgWithUnknownScopesForAllYears(6, SectorTypes.Public, currentPublicSnapshotDate)); mockDataRepository.SetupGetAll(testOrgs); // sut scopeBusinessLogic = new WebUI.BusinessLogic.Services.ScopeBusinessLogic(mockDataRepository.Object); }
public void ClearsBasketBeforeLoadingFromCookie() { // Arrange mockHttpContext.Setup(x => x.Request.Cookies[It.Is <string>(arg => arg == CookieNames.LastCompareQuery)]) .Returns("12345678"); var testPresenter = new ComparePresenter( MoqHelpers.CreateIOptionsSnapshotMock(new ViewingOptions()), mockHttpContextAccessor.Object, Mock.Of <IHttpSession>()); var testPreviousIds = new[] { "AAA", "BBB", "CCC" }; testPresenter.AddRangeToBasket(testPreviousIds); // Act testPresenter.LoadComparedEmployersFromCookie(); // Assert Assert.AreEqual(1, testPresenter.BasketItemCount, "Expected basket to contain 1 employer"); Assert.IsFalse( testPresenter.ComparedEmployers.Value.Contains(testPreviousIds), "Expected previous employer ids to be cleared from basket"); }
public async Task SubmitController_DraftComplete_POST_MaleBonusIsZero_ShowsErrors() { // Arrange var user = new User { UserId = 1, EmailAddress = "*****@*****.**", EmailVerifiedDate = VirtualDateTime.Now }; var organisation = new Organisation { OrganisationId = 1, SectorType = SectorTypes.Public }; var userOrganisation = new UserOrganisation { OrganisationId = organisation.OrganisationId, Organisation = organisation, UserId = 1, PINConfirmedDate = VirtualDateTime.Now, PIN = "1" }; //set mock routeData var routeData = new RouteData(); routeData.Values.Add("action", "EnterCalculations"); routeData.Values.Add("controller", "submit"); DateTime PrivateAccountingDate = Global.PrivateAccountingDate; var returnViewModel = new ReturnViewModel { AccountingDate = PrivateAccountingDate, MaleMedianBonusPayPercent = 0, FemaleMedianBonusPayPercent = 50, DiffMeanBonusPercent = -50, DiffMedianBonusPercent = -50, DiffMedianHourlyPercent = 50, DiffMeanHourlyPayPercent = 50, FemaleLowerPayBand = 50, FemaleMiddlePayBand = 50, FemaleUpperPayBand = 50, FemaleUpperQuartilePayBand = 50, MaleLowerPayBand = 50, MaleMiddlePayBand = 50, MaleUpperPayBand = 50, MaleUpperQuartilePayBand = 50, SectorType = SectorTypes.Private }; var controller = UiTestHelper.GetController <SubmitController>(1, routeData, user, organisation, userOrganisation); controller.Bind(returnViewModel); var submissionServiceMock = new SubmissionService( null, null, new DraftFileBusinessLogic(MoqHelpers.CreateMockDataRepository().Object)); returnViewModel.ReportInfo.Draft = await submissionServiceMock.GetDraftFileAsync( organisation.OrganisationId, organisation.SectorType.GetAccountingStartDate().Year, user.UserId); // Act controller.StashModel(returnViewModel); controller.ReportingOrganisationId = 1; var result = await controller.SaveDraftAsync(returnViewModel) as ViewResult; // Assert Assert.NotNull(result, "Expected ViewResult"); Assert.Null(result.ViewName, "Incorrect view returned"); Assert.NotNull(result.Model as ReturnViewModel, "Expected ReturnViewModel"); Assert.AreEqual( "Do not enter a bonus difference if 0% of men received a bonus", result.ViewData.ModelState["DiffMedianBonusPercent"].Errors[0].ErrorMessage); Assert.AreEqual( "Do not enter a bonus difference if 0% of men received a bonus", result.ViewData.ModelState["DiffMeanBonusPercent"].Errors[0].ErrorMessage); }
public static IContainer BuildContainerIoC(params object[] dbObjects) { var builder = new ContainerBuilder(); //Create an in-memory version of the database if (dbObjects != null && dbObjects.Length > 0) { builder.RegisterInMemoryTestDatabase(dbObjects); } else { Mock <IDataRepository> mockDataRepo = MoqHelpers.CreateMockDataRepository(); builder.Register(c => mockDataRepo.Object).As <IDataRepository>().InstancePerLifetimeScope(); } //Create the mock repositories // BL Repository builder.Register(c => new SystemFileRepository()).As <IFileRepository>().SingleInstance(); builder.RegisterType <UserRepository>().As <IUserRepository>().SingleInstance(); builder.RegisterType <RegistrationRepository>().As <RegistrationRepository>().SingleInstance(); builder.RegisterType <OrganisationService>().As <OrganisationService>().InstancePerLifetimeScope(); builder.RegisterType <ReturnService>().As <ReturnService>().InstancePerLifetimeScope(); builder.RegisterType <DraftReturnService>().As <DraftReturnService>().InstancePerLifetimeScope(); // BL Services builder.RegisterInstance(Config.Configuration); builder.RegisterType <UpdateFromCompaniesHouseService>().As <UpdateFromCompaniesHouseService>().InstancePerLifetimeScope(); builder.RegisterType <DraftFileBusinessLogic>().As <IDraftFileBusinessLogic>().InstancePerLifetimeScope(); builder.Register( c => c.ResolveAsMock <ScopeBusinessLogic>( false, typeof(IDataRepository)) .Object) .As <IScopeBusinessLogic>() .InstancePerLifetimeScope(); builder.Register( c => c.ResolveAsMock <SubmissionBusinessLogic>(false, typeof(IDataRepository)).Object) .As <ISubmissionBusinessLogic>() .InstancePerLifetimeScope(); builder.RegisterType <OrganisationBusinessLogic>().As <IOrganisationBusinessLogic>().InstancePerLifetimeScope(); // builder.Register(g => new MockGovNotify()).As <IGovNotifyAPI>().SingleInstance(); builder.RegisterType <PinInThePostService>().As <PinInThePostService>().SingleInstance(); builder.Register( c => new ViewingService( c.Resolve <IDataRepository>(), c.Resolve <ViewingSearchService>()) ) .As <IViewingService>() .InstancePerLifetimeScope(); builder.Register( c => new SubmissionService( c.Resolve <IDataRepository>(), c.Resolve <IScopeBusinessLogic>(), c.Resolve <IDraftFileBusinessLogic>())) .As <ISubmissionService>() .InstancePerLifetimeScope(); builder.RegisterType <CompareViewService>().As <ICompareViewService>().InstancePerLifetimeScope(); builder.RegisterType <SearchViewService>().As <ISearchViewService>().InstancePerLifetimeScope(); builder.RegisterType <AuditLogger>().As <AuditLogger>().SingleInstance(); builder.RegisterType <AutoCompleteSearchService>().As <AutoCompleteSearchService>().InstancePerLifetimeScope(); builder.RegisterType <ViewingSearchService>().As <ViewingSearchService>().InstancePerLifetimeScope(); builder.Register(c => Mock.Of <IObfuscator>()).As <IObfuscator>().SingleInstance(); builder.Register(c => Mock.Of <IEncryptionHandler>()).As <IEncryptionHandler>().SingleInstance(); //Register WebTracker builder.Register(c => Mock.Of <IWebTracker>()).As <IWebTracker>().InstancePerLifetimeScope(); //Register all BaseControllers - this is required to ensure KeyFilter is resolved in constructors builder.RegisterAssemblyTypes(typeof(BaseController).Assembly) .Where(t => t.IsAssignableTo <BaseController>()) .InstancePerLifetimeScope() .WithAttributeFiltering(); //Register all controllers - this is required to ensure KeyFilter is resolved in constructors builder.RegisterType <AdminUnconfirmedPinsController>().InstancePerLifetimeScope(); builder.Register(c => new MockCache()).As <IDistributedCache>().SingleInstance(); builder.RegisterType <HttpCache>().As <IHttpCache>().SingleInstance(); builder.RegisterType <HttpSession>().As <IHttpSession>().InstancePerLifetimeScope(); builder.Register(c => Mock.Of <IHttpContextAccessor>()).As <IHttpContextAccessor>().InstancePerLifetimeScope(); builder.RegisterType <ActionContextAccessor>().As <IActionContextAccessor>().SingleInstance(); builder.Register(c => Mock.Of <IUrlHelper>()).SingleInstance(); builder.RegisterType <EmailSendingService>().As <EmailSendingService>().InstancePerLifetimeScope(); MockBackgroundJobsApi = new Mock <IBackgroundJobsApi>(); builder.Register(c => MockBackgroundJobsApi.Object).As <IBackgroundJobsApi>().InstancePerLifetimeScope(); var environmentMock = new Mock <IHostingEnvironment>(); environmentMock.SetupGet(m => m.WebRootPath).Returns(Environment.CurrentDirectory); builder.RegisterInstance(environmentMock.Object).As <IHostingEnvironment>().SingleInstance(); IContainer container = builder.Build(); return(container); }
public async Task ViewingService_Search_BySectorType_Selects_Sectors_That_Contain_All_Terms( string searchKeyWords, string csvListOfSicSectionsExpectedToBeSelected) { // Arrange var sicCodeSearchServiceClient = new SearchServiceClient( ConfigHelpers.SearchOptions.AzureServiceName, new SearchCredentials(ConfigHelpers.SearchOptions.AzureApiAdminKey)); var sicCodeSearchIndexClient = new AzureSicCodeSearchRepository(Mock.Of <IAuditLogger>(), sicCodeSearchServiceClient, ConfigHelpers.SearchOptions.SicCodeIndexName); var mockDataRepo = MoqHelpers.CreateMockDataRepository(); var mockViewingService = new Mock <IViewingService>(); mockViewingService.Setup(m => m.SearchBusinessLogic.EmployerSearchRepository).Returns(_azureSearchRepo); mockViewingService.Setup(m => m.SearchBusinessLogic.SicCodeSearchRepository) .Returns(sicCodeSearchIndexClient); var testPresenter = new ViewingPresenter(mockViewingService.Object, Mock.Of <ISharedBusinessLogic>()); #region Calculate the expected number of records // Convert the received csv list to a list of EmployerSearchParameters var listOfSicSectionDescriptionsToBeSelected = csvListOfSicSectionsExpectedToBeSelected .SplitI(";") .Select( sicSectionDescriptionFoundInList => { var sicCodeToSearchBy = sicSectionDescriptionFoundInList.SplitI("~")[1].Trim(); return(Mock.Of <EmployerSearchParameters>( searchParam => searchParam.Keywords == sicCodeToSearchBy && searchParam.Page == 1 && searchParam.PageSize == 3000 && searchParam.SearchFields == $"{nameof(EmployerSearchModel.SicCodeIds)}" && searchParam.SearchType == SearchTypes.ByEmployerName && searchParam.SearchMode == SearchModes.All)); }); var listOfEmployerSearchModel = new List <EmployerSearchModel>(); foreach (var sicSectionDescriptionSearchParameter in listOfSicSectionDescriptionsToBeSelected) { var sicSectionDescriptionSearchViewModel = await testPresenter.SearchAsync(sicSectionDescriptionSearchParameter); Assert.GreaterOrEqual( sicSectionDescriptionSearchViewModel.EmployerEndIndex, 1, $"When searching for {sicSectionDescriptionSearchParameter.Keywords} we expect to find at least one organisation in the index."); listOfEmployerSearchModel.AddRange(sicSectionDescriptionSearchViewModel.Employers.Results); } var expectedListOfEmployerNames = listOfEmployerSearchModel.Select(x => x.Name).DistinctI().OrderBy(x => x); #endregion var mockedSearchParameters = Mock.Of <EmployerSearchParameters>( x => x.Keywords == searchKeyWords && x.Page == 1 && x.PageSize == 3000 && x.SearchFields == $"{nameof(EmployerSearchModel.SicCodeIds)}" && x.SearchType == SearchTypes.ByEmployerName && x.SearchMode == SearchModes.All); // Act var keywordSearchResultSearchViewModel = await testPresenter.SearchAsync(mockedSearchParameters); // Assert var actualListOfEmployerNames = keywordSearchResultSearchViewModel.Employers.Results.Select(x => x.Name).DistinctI().OrderBy(x => x); var foundMoreRecordsThanThoseExpected = actualListOfEmployerNames.Except(expectedListOfEmployerNames); Assert.IsEmpty(foundMoreRecordsThanThoseExpected); var expectedMoreRecordsThanThoseFound = expectedListOfEmployerNames.Except(actualListOfEmployerNames); Assert.IsEmpty(expectedMoreRecordsThanThoseFound); }
public void BeforeEach() { mockDataRepo = MoqHelpers.CreateMockDataRepository(); }
public void BeforeEach() { _mockDataRepo = MoqHelpers.CreateMockDataRepository(); viewingSearchService = new ViewingSearchService(_mockDataRepo.Object); }
public static IContainer BuildContainerIoC(params object[] dbObjects) { var builder = new ContainerBuilder(); //Create an in-memory version of the database if (dbObjects != null && dbObjects.Length > 0) { builder.RegisterInMemoryTestDatabase(dbObjects); } else { Mock <IDataRepository> mockDataRepo = MoqHelpers.CreateMockDataRepository(); builder.Register(c => mockDataRepo.Object).As <IDataRepository>().InstancePerLifetimeScope(); } // configuration options builder.Register(c => MoqHelpers.CreateIOptionsSnapshotMock(new SubmissionOptions())); builder.Register(c => MoqHelpers.CreateIOptionsSnapshotMock(new ViewingOptions())); //Create the mock repositories // BL Repository builder.Register(c => new SystemFileRepository(new StorageOptions())).As <IFileRepository>().SingleInstance(); builder.Register(c => new MockSearchRepository()).As <ISearchRepository <EmployerSearchModel> >().SingleInstance(); builder.Register(c => Mock.Of <ISearchRepository <SicCodeSearchModel> >()).As <ISearchRepository <SicCodeSearchModel> >(); builder.RegisterType <UserRepository>().As <IUserRepository>().SingleInstance(); builder.RegisterType <RegistrationService>().As <IRegistrationService>().SingleInstance(); // BL Services builder.RegisterInstance(ConfigHelpers.Config); builder.RegisterType <SharedBusinessLogic>().As <ISharedBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <SearchBusinessLogic>().As <ISearchBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <UpdateFromCompaniesHouseService>().As <UpdateFromCompaniesHouseService>().InstancePerLifetimeScope(); builder.RegisterType <SecurityCodeBusinessLogic>().As <ISecurityCodeBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <DraftFileBusinessLogic>().As <IDraftFileBusinessLogic>().InstancePerLifetimeScope(); builder.RegisterType <DownloadableFileBusinessLogic>().As <IDownloadableFileBusinessLogic>().InstancePerLifetimeScope(); builder.Register( c => c.ResolveAsMock <ScopeBusinessLogic>( false, typeof(ISharedBusinessLogic), typeof(IDataRepository), typeof(ISearchBusinessLogic)) .Object) .As <IScopeBusinessLogic>() .InstancePerLifetimeScope(); builder.Register( c => c.ResolveAsMock <SubmissionBusinessLogic>(false, typeof(ISharedBusinessLogic), typeof(IDataRepository)).Object) .As <ISubmissionBusinessLogic>() .InstancePerLifetimeScope(); builder.RegisterType <OrganisationBusinessLogic>().As <IOrganisationBusinessLogic>().InstancePerLifetimeScope(); // builder.RegisterType <MockPrivateEmployerRepository>() .As <IPagedRepository <EmployerRecord> >() .Keyed <IPagedRepository <EmployerRecord> >("Private") .SingleInstance(); builder.RegisterType <MockPublicEmployerRepository>() .As <IPagedRepository <EmployerRecord> >() .Keyed <IPagedRepository <EmployerRecord> >("Public") .SingleInstance(); builder.Register(g => new MockGovNotify()).As <IGovNotifyAPI>().SingleInstance(); builder.Register(g => new MockClassQueue(QueueNames.SendEmail)).Keyed <IQueue>(QueueNames.SendEmail).SingleInstance(); builder.Register(g => new MockClassQueue(QueueNames.ExecuteWebJob)).Keyed <IQueue>(QueueNames.ExecuteWebJob).SingleInstance(); builder.Register(c => Mock.Of <LogEventQueue>()).SingleInstance(); builder.Register(c => Mock.Of <LogRecordQueue>()).SingleInstance(); builder.RegisterType <PinInThePostService>().As <PinInThePostService>().SingleInstance(); // UI Presentation builder.Register( c => c.ResolveAsMock <ScopePresenter>( false, typeof(IScopeBusinessLogic), typeof(IDataRepository), typeof(IOrganisationBusinessLogic)) .Object) .As <IScopePresenter>() .InstancePerLifetimeScope(); builder.RegisterType <ViewingPresenter>().As <IViewingPresenter>().InstancePerLifetimeScope(); builder.RegisterType <SubmissionPresenter>().As <ISubmissionPresenter>().InstancePerLifetimeScope(); builder.RegisterType <ComparePresenter>().As <IComparePresenter>().InstancePerLifetimeScope(); builder.RegisterType <SearchPresenter>().As <ISearchPresenter>().InstancePerLifetimeScope(); builder.RegisterType <ChangeEmailViewService>().As <IChangeEmailViewService>().InstancePerLifetimeScope(); builder.RegisterType <ChangeDetailsViewService>().As <IChangeDetailsViewService>().InstancePerLifetimeScope(); builder.RegisterType <ChangePasswordViewService>().As <IChangePasswordViewService>().InstancePerLifetimeScope(); builder.RegisterType <CloseAccountViewService>().As <ICloseAccountViewService>().InstancePerLifetimeScope(); builder.RegisterInstance(new NullLoggerFactory()).As <ILoggerFactory>().SingleInstance(); builder.RegisterGeneric(typeof(Logger <>)).As(typeof(ILogger <>)).SingleInstance(); builder.RegisterType <AuditLogger>().As <AuditLogger>().SingleInstance(); builder.Register(c => new Mock <IAdminService>().Object).As <IAdminService>().InstancePerLifetimeScope(); builder.Register(c => Mock.Of <IObfuscator>()).As <IObfuscator>().SingleInstance(); builder.Register(c => Mock.Of <IEncryptionHandler>()).As <IEncryptionHandler>().SingleInstance(); //Register WebTracker builder.Register(c => Mock.Of <IWebTracker>()).As <IWebTracker>().InstancePerLifetimeScope(); //Register all BaseControllers - this is required to ensure KeyFilter is resolved in constructors builder.RegisterAssemblyTypes(typeof(BaseController).Assembly) .Where(t => t.IsAssignableTo <BaseController>()) .InstancePerLifetimeScope() .WithAttributeFiltering(); //Register all controllers - this is required to ensure KeyFilter is resolved in constructors builder.RegisterType <AdminUnconfirmedPinsController>().InstancePerLifetimeScope(); builder.Register(c => new MockCache()).As <IDistributedCache>().SingleInstance(); builder.RegisterType <HttpCache>().As <IHttpCache>().SingleInstance(); builder.RegisterType <HttpSession>().As <IHttpSession>().InstancePerLifetimeScope(); builder.Register(c => Mock.Of <IHttpContextAccessor>()).As <IHttpContextAccessor>().InstancePerLifetimeScope(); builder.RegisterType <ActionContextAccessor>().As <IActionContextAccessor>().SingleInstance(); builder.Register(c => Mock.Of <IUrlHelper>()).SingleInstance(); //builder.Register(c => new Mock()).As<IFileRepository>(); var environmentMock = new Mock <IWebHostEnvironment>(); environmentMock.SetupGet(m => m.WebRootPath).Returns(Environment.CurrentDirectory); builder.RegisterInstance(environmentMock.Object).As <IWebHostEnvironment>().SingleInstance(); SetupHelpers.SetupMockLogRecordGlobals(builder); // Initialise AutoMapper MapperConfiguration mapperConfig = new MapperConfiguration(config => { // register all out mapper profiles (classes/mappers/*) config.AddMaps(typeof(Program)); // allows auto mapper to inject our dependencies //config.ConstructServicesUsing(serviceTypeToConstruct => //{ // //TODO //}); }); builder.RegisterInstance(mapperConfig.CreateMapper()).As <IMapper>().SingleInstance(); IContainer container = builder.Build(); return(container); }