private void TearDown() { if (_mock != null) { _mock.Dispose(); _mock = null; } }
public void GetAlbum_IsValid() { using (var mock = AutoMock.GetLoose()) { //arrange var sampleAlbum = TestData.SampleAlbumData(1); mock.Mock <IDataAccess>() .Setup(x => x.ReadData_Album(1)) .Returns(sampleAlbum[0]); var cls = mock.Create <MusicProcessor>(); //act var expected = sampleAlbum[0]; var actual = cls.GetAlbum(1); //Assert Assert.AreEqual(expected.ArtistName, actual.ArtistName); Assert.AreEqual(expected.IdAlbum, actual.IdAlbum); Assert.AreEqual(expected.AlbumName, actual.AlbumName); } }
public void SaveComicBookCommand_Adding_ValidExecute() { using var mock = AutoMock.GetLoose(); var model = mock.Create <AddEditComicBookViewModel>(); model.CheckPassedComicBookAsync(null); model.SetErrorMessagesChangesAsync(); var comic = TestData.GetComicBooksSample().First(); model.InputModel.Title = comic.Title; model.InputModel.Series = comic.Series; model.InputModel.Price = comic.Price; model.InputModel.Quantity = comic.Quantity; model.InputModel.OnSaleDate = comic.OnSaleDate; model.SelectedArtist = comic.ComicBookArtists.First().Artist; model.AddArtistCommand.Execute(); model.SaveComicBookCommand.Execute(); Assert.False(model.InputModel.HasErrors); Assert.True(model.CanSave); mock.Mock <IRepository <ComicBook> >().Verify(x => x.Add(model.ComicBook), Times.Once); }
public void Setup() { DataStore = new List <Genre>() { new Genre { Id = 1, Name = "Action", DateCreated = DateTime.Now, IsDeleted = false }, new Genre { Id = 2, Name = "Comedy", DateCreated = DateTime.Now, IsDeleted = false, DateUpdated = DateTime.Now.AddDays(2) }, new Genre { Id = 3, Name = "Horror", DateCreated = DateTime.Now, IsDeleted = true, DateUpdated = DateTime.Now.AddDays(2), DateDeleted = DateTime.Now.AddDays(5) } }; AutoMock = AutoMock.GetLoose(); MockRepository = new Mock <IRepository <Genre, int> >(); AutoMock.Provide(MockRepository.Object); AutoMock.Provide <IService <Genre, int>, GenreService>(); AutoMock.Provide <IValidationService <Genre>, GenreValidationService>(); AutoMock.Provide <IValidationExceptionService, ValidationExceptionService>(); }
public void Can_Export() { using (var mock = AutoMock.GetStrict()) { //Arrange mock.Mock <IArrayOperations>(); var array = new CustomArray( new int[, ] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }); var sut = mock.Create <ArrayOperations>(); //Act var actual = sut.Export(array); //Assert Assert.AreEqual("1,2,3\r\n4,5,6\r\n7,8,9\r\n", actual); } }
public void ItWillInvalidatePositionFilterModel() { var filterModel = new PositionFilterDomainModel { Page = -1, PageSize = -25, PositionType = '0', OrderByField = "FakeField", OrderByDirection = '0' }; using (var mock = AutoMock.GetLoose()) { var service = mock.Create <PositionService>(); var result = service.ValidatePositionFilterModel(filterModel); Assert.NotNull(result); Assert.Equal(5, result.Count()); Assert.False(result.IsValid); } }
public void ItWillValidatePositionFilterModel() { var filterModel = new PositionFilterDomainModel { Page = 1, PageSize = 25, PositionType = 'L', OrderByField = "Symbol", OrderByDirection = 'A' }; using (var mock = AutoMock.GetLoose()) { var service = mock.Create <PositionService>(); var result = service.ValidatePositionFilterModel(filterModel); Assert.NotNull(result); Assert.Empty(result); Assert.True(result.IsValid); } }
public void Can_Search_Owners() { using (var mock = AutoMock.GetLoose()) { // Arrange var config = mock.Provide <IAppConfig, TestConfig>(); var searchCriteria = new { field = "emailAddress", value = "test" }; var testOwner = GetTestOwner(); var expectedMetadata = new Metadata(new[] { Link.Self($"{Constants.TOKENIZED_CURRENT_URL}", HttpMethod.Get.Method), Link.Custom("summary", $"{Constants.TOKENIZED_BASE_URL}/{Constants.API_ROUTE_BASE_PATH}{Constants.TOKENIZED_CONTROLLER_PATH}/{testOwner.Id}/summary", HttpMethod.Get.Method), Link.Custom("detail", $"{Constants.TOKENIZED_BASE_URL}/{Constants.API_ROUTE_BASE_PATH}{Constants.TOKENIZED_CONTROLLER_PATH}/{testOwner.Id}/detail", HttpMethod.Get.Method), }); var expectedOwners = new List <OwnerEntity> { testOwner }; var expected = new MultiResponse(Result.Success, expectedMetadata, expectedOwners.Select(Mapper.Map <OwnerEntity, OwnerSummaryModel>).OfType <IModel>().ToList()); mock.Mock <IRepository <OwnerEntity> >().Setup(x => x.Search(searchCriteria.field, searchCriteria.value)).ReturnsAsync(expectedOwners); var systemUnderTest = mock.Create <OwnerService>(); // Act var actual = systemUnderTest.Search(searchCriteria.field, searchCriteria.value).Result; // Assert mock.Mock <IRepository <OwnerEntity> >().VerifyAll(); Assert.IsNotNull(actual); Assert.IsNull(actual.Errors); Assert.IsNotNull(actual.Data); Assert.IsNotNull(actual.Metadata); Assert.IsNotNull(actual.Metadata.Links); Assert.AreEqual(actual.Result, Result.Success); Assert.AreEqual(expected.Data.Count, actual.Data.Count); // todo - compare and assert the actual data Assert.AreEqual(expected.Metadata.ServerVersion, actual.Metadata.ServerVersion); Assert.IsTrue(MetadataLinksAreEqual(expected.Metadata.Links, actual.Metadata.Links)); } }
public void SpellSearchFacade_GetByNameContainingTOWER_ReturnPagedList() { //ensure that capitalization does not effect the search result. //Arrange List <Spell> spells = CreateTestData.GetListOfSpells(); var mockSet = new Mock <DbSet <Spell> >() .SetupData(spells, o => { return(spells.Single(x => x.Spell_id.CompareTo(o.First()) == 0)); }); List <foundSpellCM> expectedList = new List <foundSpellCM>(); foundSpellCM tower = new foundSpellCM { Spell_id = Guid.Parse("46d10bb8-84d2-408d-a928-5847ff99461f"), Name = "Widogast's Nascent Nine-sided Tower" }; expectedList.Add(tower); IPagedList <foundSpellCM> expected = expectedList.ToPagedList(1, 20); using (var mockContext = AutoMock.GetLoose()) { mockContext.Mock <SpellsContext>() .Setup(x => x.Spells).Returns(mockSet.Object); mockContext.Mock <SpellsContext>() .Setup(x => x.Set <Spell>()).Returns(mockSet.Object); SpellsContext context = mockContext.Create <SpellsContext>(); //Act var toTest = new SpellSearchFacade(context); var actual = toTest.searchSpellsToPagedList("TOWER", "Name", 1); //Assert actual.Should().BeEquivalentTo(expected); } }
public void UpdateRotaTest() { using (var mock = AutoMock.GetLoose()) { string firstName = "Jack"; string lastName = "Dane"; int contractHours = 4; int employeeId = 3; string storeId = "1234"; string email = "*****@*****.**"; Year year = new Year(2020); List <DateTime> dates = year.GetWeekStartFinish(15); DateTime firstDate = dates[0]; DateTime secondDate = dates[1]; var employee = mock.Create <Employee>( new NamedParameter("firstName", firstName), new NamedParameter("lastName", lastName), new NamedParameter("contractHours", contractHours), new NamedParameter("id", employeeId), new NamedParameter("storeId", storeId), new NamedParameter("email", email) ); foreach (EmployeeWorkWeek employeeWorkDay in GetWorkHoursRotaUpdate(storeId, firstDate)) { employee.UpdateRota(employeeWorkDay); } mock.Mock <IEmployeeDatabase>() .Verify(x => x.DeleteFromWorkWeek(employeeId, It.IsAny <DateTime>()), Times.Exactly(7)); mock.Mock <IEmployeeDatabase>() .Verify(x => x.InsertWorkHours(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>()), Times.Exactly(5)); } }
public void TestGetPersonPosition() { using (var mock = AutoMock.GetLoose()) { mock.Mock <IPositionDAL>() .Setup(x => x.GetPersonPositions(It.IsAny <int>())).Returns(GetSamplePositions()); var positionDAL = mock.Create <IPositionDAL>(); var expected = GetSamplePositions(); Person person = new Person { LastName = "Doe", FirstName = "Jane", Ssn = "123456789", Gender = "Female", DateOfBirth = DateTime.Now, RoleId = 1, StatusId = 1, Email = "*****@*****.**", StreetAddress = "605 Dance Street", Zipcode = "30101", Phone = "1234443234", Password = "******", Username = "******" }; var actual = positionDAL.GetPersonPositions(person.Id); Assert.True(actual != null); Assert.Equal(expected.Count, actual.Count); Assert.Equal(expected[0].positionID, actual[0].positionID); Assert.Equal(expected[0].positionTitle, actual[0].positionTitle); Assert.Equal(expected[0].positionDescription, actual[0].positionDescription); Assert.Equal(expected[0].isActive, actual[0].isActive); } }
public void TestAddPositionToPerson() { using (var mock = AutoMock.GetLoose()) { var position = new Position { positionTitle = "New Position", positionDescription = "Test Position", isActive = true }; Person person = new Person { LastName = "Doe", FirstName = "Jane", Ssn = "123456789", Gender = "Female", DateOfBirth = DateTime.Now, RoleId = 1, StatusId = 1, Email = "*****@*****.**", StreetAddress = "605 Dance Street", Zipcode = "30101", Phone = "1234443234", Password = "******", Username = "******" }; mock.Mock <IPositionDAL>() .Setup(x => x.AddPositionToPerson(It.IsAny <int>(), It.IsAny <int>())); var newPosition = mock.Create <IPositionDAL>(); newPosition.AddPositionToPerson(person.Id, position.positionID); mock.Mock <IPositionDAL>().Verify(x => x.AddPositionToPerson(person.Id, position.positionID), Times.Exactly(1)); } }
public void DodatiNovi_AkoSeUredjajVecKoristi() { using (var mock = AutoMock.GetLoose()) { List <OsobaUredjaj> list = new List <OsobaUredjaj>() { new OsobaUredjaj() { Uredjaj = new Uredjaj() { Naziv = "upaljac" }, KrajKoriscenja = DateTime.MaxValue } }; var ouDto = new OsobaUredjajDTO() { Osoba = new OsobaDTO() { Ime = "mirsan" }, Uredjaj = new UredjajDTO() { Naziv = "upaljac" } }; mock.Mock <IOsobaUredjajRepository>().Setup(e => e.DajSveEntitete()).Returns(list); var obj = mock.Create <OsobaUredjajController>(); var dobijas = obj.DodatiNovi(ouDto); var ocekujes = $"{ouDto.Osoba.Ime} ne moze koristiti ovaj uredjaj zato sto ga vec neko koristi."; var result = Assert.IsType <BadRequestObjectResult>(dobijas); Assert.Equal(ocekujes, result.Value); } }
public async Task ItWillReturn422ForInvalidInput_GetFiltered() { using (var mock = AutoMock.GetLoose(cfg => cfg.RegisterInstance(_mapper).As <IMapper>())) { mock.Mock <ITransactionService>() .Setup(x => x.ValidateTransactionFilterModel(It.IsAny <TransactionFilterDomainModel>())) .Returns(() => { var modelState = new ModelStateDictionary(); modelState.AddModelError("Key", "Error Message"); return(modelState); }); var controller = mock.Create <TransactionsController>(); var response = await controller.GetFilteredAsync(new TransactionFilterDto { Page = 1, PageSize = 10 }); Assert.NotNull(response); var result = Assert.IsType <UnprocessableEntityObjectResult>(response); Assert.Equal(HttpStatusCode.UnprocessableEntity, (HttpStatusCode)result.StatusCode); var errors = Assert.IsType <SerializableError>(result.Value); Assert.Single(errors); var error = errors.SingleOrDefault(); Assert.Equal("Key", error.Key); Assert.Equal("Error Message", ((string[])error.Value).SingleOrDefault()); mock.Mock <ITransactionService>().Verify(x => x.ValidateTransactionFilterModel(It.IsAny <TransactionFilterDomainModel>()), Times.Once); mock.Mock <ITransactionService>().Verify(x => x.ValidateTransactionFilterModel(It.Is <TransactionFilterDomainModel>(i => i != null && i.Page == 1 && i.PageSize == 10)), Times.Once); mock.Mock <ITransactionService>().Verify(x => x.GetFilteredTransactions(It.IsAny <TransactionFilterDomainModel>(), It.IsAny <string>()), Times.Never); } }
public void SetUp() { mocker = AutoMock.GetLoose(); history = new List <PaymentHistoryEntity>(); var config = new MapperConfiguration(cfg => cfg.AddProfile <RequiredPaymentsProfile>()); config.AssertConfigurationIsValid(); var mapper = new Mapper(config); mocker.Provide <IMapper>(mapper); identifiedLearner = identifiedLearner = new IdentifiedRemovedLearningAim { CollectionPeriod = new CollectionPeriod { AcademicYear = 1819, Period = 1 }, EventId = Guid.NewGuid(), EventTime = DateTimeOffset.UtcNow, IlrSubmissionDateTime = DateTime.Now, JobId = 1, Learner = new Learner { ReferenceNumber = "learner-ref-123", Uln = 2 }, LearningAim = new LearningAim { FrameworkCode = 3, FundingLineType = "funding line type", PathwayCode = 4, ProgrammeType = 5, Reference = "learning-ref-456", StandardCode = 6 }, Ukprn = 7 }; }
public void TestStartWithSubFolderWithParameter() { using (var mock = AutoMock.GetStrict()) { var fileSystem = new MockFileSystem( new Dictionary <string, MockFileData> { { @"C:\root\", new MockDirectoryData() }, { @"C:\root\bla\", new MockDirectoryData() }, { @"C:\root\bla\song.xml", new MockFileData("xml") { Attributes = FileAttributes.Hidden } } }); mock.Provide <IFileSystem>(fileSystem); var settings = mock.Mock <ISettings>(); settings.Setup(m => m.DataFilename).Returns("song.xml"); var expectedDirectoryData = new DirectoryData { Status = DirectoryStatus.UNKNOWN }; var importer = mock.Mock <IImporter>(); importer.Setup(m => m.Read <DirectoryData>(@"C:\root\bla\song.xml")).Returns(expectedDirectoryData); var expectedTask = new Task { Type = TaskType.UNKNOWN, Path = @"C:\root\bla" }; var directoriesService = mock.Mock <IDirectories>(); directoriesService.Setup(m => m.AddTask(expectedTask)); var checker = mock.Create <Checker>(); checker.Start(@"C:\root\bla"); settings.VerifyGet(m => m.DataFilename, Times.Once); importer.Verify(m => m.Read <DirectoryData>(@"C:\root\bla\song.xml"), Times.Once); directoriesService.Verify(m => m.AddTask(expectedTask), Times.Once); } }
public void SetUp() { inProgressMessages = new List <InProgressMessage>(); completedMessages = new List <CompletedMessage>(); mocker = AutoMock.GetLoose(); job = new JobModel { Id = 1, DcJobId = 99, StartTime = DateTimeOffset.UtcNow.AddSeconds(-30), Status = JobStatus.InProgress, LearnerCount = null, JobType = JobType.EarningsJob, DcJobEndTime = null, DcJobSucceeded = null, IlrSubmissionTime = null, Ukprn = null, AcademicYear = 1920, CollectionPeriod = 01 }; mocker.Mock <IJobStorageService>() .Setup(x => x.GetJob(It.IsAny <long>(), It.IsAny <CancellationToken>())) .ReturnsAsync(job); mocker.Mock <IJobStorageService>() .Setup(x => x.GetInProgressMessages(It.IsAny <long>(), It.IsAny <CancellationToken>())) .ReturnsAsync(inProgressMessages); mocker.Mock <IJobStorageService>() .Setup(x => x.GetCompletedMessages(It.IsAny <long>(), It.IsAny <CancellationToken>())) .ReturnsAsync(completedMessages); mocker.Mock <IJobStorageService>() .Setup(x => x.GetJobStatus(It.IsAny <long>(), It.IsAny <CancellationToken>())) .ReturnsAsync((hasFailedMessages: false, endTime: null)); mocker.Mock <IJobServiceConfiguration>() .SetupGet(cfg => cfg.EarningsJobTimeout) .Returns(TimeSpan.FromSeconds(60)); }
public async Task GetAllCards_Valid() { using (var mock = AutoMock.GetLoose()) { // 1. arrange var userId = Guid.NewGuid().ToString(); List <Card> cards = new List <Card>() { new Card() { CardNumber = "m5EUbDvUbksT9LYW1v8AOyL0X2IIPQqDfI1ZfFTiJuQ=", CVC = "mhS2tPsAk1GysMZtXBXhaQ==", Name = "Kun Wang", ExpiryDate = DateTime.Now.AddDays(10) } }; // 2. mock mock.Mock <ICreditcardRepository>() .Setup(c => c.GetCards(userId)) .ReturnsAsync(cards); var cardService = mock.Create <CreditcardService>(); // 3. action var results = await cardService.GetAllCards(userId); // 4. assert Assert.True(results.Any()); Assert.Single(results); var resultCard = results.ToList().FirstOrDefault(); Assert.Equal(cards[0].CardNumber, resultCard.CardNumber); Assert.Equal(cards[0].CVC, resultCard.CVC); Assert.Equal(cards[0].Name, resultCard.Name); Assert.Equal(cards[0].ExpiryDate, resultCard.ExpiryDate); } }
public void ItemsRepository_CharacterLosesItem_ValidCall() { //Arrange - Vax loses Whisper List <Character_Item> heldItems = CreateTestData.GetListOfHeldItems(); List <Item> itemset = CreateTestData.GetListOfItems(); var heldItemsMockSet = new Mock <DbSet <Character_Item> >() .SetupData(heldItems, o => { return(heldItems.Single(x => x.Character_id.CompareTo(o.First()) == 0)); }); var ItemsMockSet = new Mock <DbSet <Item> >() .SetupData(itemset, o => { return(itemset.Single(x => x.Item_id.CompareTo(o.First()) == 0)); }); using (var mockContext = AutoMock.GetLoose()) { var Whisper = CreateTestData.GetSampleItem(); var Whisper_id = Whisper.Item_id; var Vax_id = Guid.Parse("e3a0faef-99da-4d15-bff1-b535a42b955c"); mockContext.Mock <ItemsContext>() .Setup(x => x.Items).Returns(ItemsMockSet.Object); mockContext.Mock <ItemsContext>() .Setup(x => x.HeldItems).Returns(heldItemsMockSet.Object); //Act IItemsRepository toTest = mockContext.Create <ItemsRepository>(); toTest.CharacterLosesItem(Vax_id, Whisper_id); var actual = toTest.GetItemsHeldBy(Vax_id); //Assert actual.Should().NotContain(Whisper); } }
public async Task CallGoToLoginCmd() { var mockB = new Mock <IService>(); mockB.SetupAllProperties(); bool called = false; var callArgs = string.Empty; var mockA = new Mock <INavigationService>(); mockA.Setup(x => x.NavigateAsync(It.IsAny <string>(), true)) .Callback((string s, bool a) => callArgs = s) .Returns(() => { called = true; return(Task.FromResult(true)); } ); LocalAutoMock = AutoMock.GetLoose(cfg => cfg.RegisterMock(mockA).Keyed <INavigationService>(NavigationServiceType.ShellNavigation).SingleInstance()); SetMockContainer(); var token = new CancellationToken(false); var obj = new ZeroconfHost(new List <string>() { "local.net" }, new Dictionary <string, IService>() { { "", mockB.Object } }); Assert.IsNotNull(obj); obj.IPAddress = "myhost.net"; obj.GoToLoginCmd.Execute(null); mockA.Verify(x => x.NavigateAsync(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <bool>()), Times.Once); }
public async Task It_Should_Send_Message_To_The_Endpoint() { using (AutoMock mock = AutoMock.GetLoose(this.xUnitOutput.Capture())) { IOptions <TelegramOptions> options = Options.Create(new TelegramOptions { Endpoint = new Uri("https://api.telegram.org"), Channel = "abc", Token = "cde" }); mock.Provide(options); var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("some-response") }; var mockMessageHandler = new MockMessageHandler(response); mock.Mock <IHttpClientFactory>() .Setup(p => p.CreateClient(HttpClientFactoryExtensions.ClientName)) .Returns(new HttpClient(mockMessageHandler) { BaseAddress = options.Value.Endpoint }); var service = mock.Create <TelegramServiceImpl>(); await service.SendMessageAsync("some-message", CancellationToken.None); mock.Mock <IHttpClientFactory>() .Verify(p => p.CreateClient(HttpClientFactoryExtensions.ClientName), Times.Once); HttpRequestMessage request = mockMessageHandler.MessageSent; Assert.Equal(HttpMethod.Post, request.Method); // ReSharper disable once StringLiteralTypo Assert.Equal("/botcde/sendMessage", request.RequestUri.AbsolutePath); const string expectedContent = "{\"chat_id\":\"abc\",\"text\":\"some-message\",\"parse_mode\":\"Markdown\"}"; string content = await request.Content.ReadAsStringAsync(); Assert.Equal(expectedContent, content); } }
public void BrisanjeOsobe_KadOsobaKoristiUredjaj(long id) { Osoba osoba = new Osoba() { Ime = "mirsan", Prezime = "kajovic", Kancelarija = new Kancelarija() { Opis = "kuca" } }; using (var mock = AutoMock.GetLoose()) { mock.Mock <IOsobaRepository>().Setup(e => e.EntitetPoId(It.IsAny <long>())).Returns(osoba); List <OsobaUredjaj> osobaUredjaj = new List <OsobaUredjaj>() { new OsobaUredjaj() { Id = 16, Osoba = osoba }, new OsobaUredjaj() { Id = 4 } }; mock.Mock <IOsobaUredjajRepository>().Setup(e => e.DajSveEntitete()).Returns(osobaUredjaj); var obj = mock.Create <OsobaController>(); var dobijas = obj.BrisanjeOsobe(id); var ocekujes = "Osoba nije izbrisana iz baze zato sto je vec koristila/koristi neki od uredjaja."; var result = Assert.IsType <BadRequestObjectResult>(dobijas); Assert.Equal(ocekujes, result.Value); } }
public void DebitWallet_DuplicateDebit_ReturnsStatusCodeAcceptedAndBalance(int coins, string transactionId, HttpStatusCode expHttpCode, int expBalance) { using (var mock = AutoMock.GetLoose()) { Wallet credit = new Wallet { WalletId = new Guid("1d4e7d81-ce9d-457b-b056-0f883baa783d"), TransactionType = Const.Credit, Coins = 1000, TransactionId = "tx123", Version = 1 }; IEnumerable <Wallet> response = new List <Wallet>() { credit }; var walletRepo = new Mock <IWalletRepository>(); walletRepo.Setup(p => p.GetWalletById(It.IsAny <Guid>())).Returns(response); walletRepo.Setup(p => p.AddWalletData(credit)); WalletService walletService = new WalletService(walletRepo.Object); walletService.CreateAndCreditWallet(credit); Wallet debit = new Wallet { WalletId = new Guid("1d4e7d81-ce9d-457b-b056-0f883baa783d"), TransactionType = Const.Debit, Coins = coins, TransactionId = transactionId }; var actual = walletService.DebitWallet(debit); Assert.Equal(expHttpCode, actual.Item1); Assert.Equal(expBalance, actual.Item2); } }
public void ProcessOneDiscoveryWithDifferentDiscoverersFromExistingWhenExistingDisabled() { var fix = new Fixture(); var discoverer2 = DiscovererModelEx.CreateDiscovererId(fix.Create <string>(), fix.Create <string>()); // Readjust existing to be reported from different Discoverer... CreateFixtures(out var site, out var discoverer, out var supervisor, out var publisher, out var gateway, out var existing, out var found, out var registry, -1, x => { x.Application.DiscovererId = discoverer2; x.Endpoints.ForEach(e => e.DiscovererId = discoverer2); return(x); }, true); // Found one app and endpoint found = new List <DiscoveryEventModel> { found.First() }; var count = registry.Devices.Count(); // Assert disabled items are now enabled using (var mock = AutoMock.GetLoose()) { // Setup var service = Setup(mock, registry); // Run service.ProcessDiscoveryResultsAsync(discoverer, new DiscoveryResultModel(), found).Wait(); // Assert var inreg = ApplicationsIn(registry); Assert.Equal(count, registry.Devices.Count()); Assert.False(inreg.IsSameAs(existing)); Assert.Equal(discoverer, inreg.First().Application.DiscovererId); Assert.Null(inreg.First().Application.NotSeenSince); Assert.Equal(discoverer, inreg.First().Endpoints.First().DiscovererId); } }
public void CharacterCommons_spellCanBeCastByClass_returnTrue() { List <Spell_Class> spell_Classes = CreateTestData.GetListOfCastableByRecords(); List <Spell> spells = CreateTestData.GetListOfSpells(); var spellMockSet = new Mock <DbSet <Spell> >() .SetupData(spells, o => { return(spells.Single(x => x.Spell_id.CompareTo(o.First()) == 0)); }); var castableByMockSet = new Mock <DbSet <Spell_Class> >() .SetupData(spell_Classes, o => { return(spell_Classes.Single(x => x.Spell_id.CompareTo(o.First()) == 0)); }); var realSpell_Class = CreateTestData.GetSampleCastableBy(); using (var mockContext = AutoMock.GetLoose()) { mockContext.Mock <SpellsContext>() .Setup(x => x.Spells).Returns(spellMockSet.Object); mockContext.Mock <SpellsContext>() .Setup(x => x.Set <Spell>()).Returns(spellMockSet.Object); mockContext.Mock <SpellsContext>() .Setup(x => x.CastableByRecords).Returns(castableByMockSet.Object); mockContext.Mock <SpellsContext>() .Setup(x => x.Set <Spell_Class>()).Returns(castableByMockSet.Object); IUnitOfWork uow = UoW_Factory.getUnitofWork(mockContext); IBaseUserAccess access = UserAccessFactory.getBaseUserAccess(uow); //act ICharacterCommonFunctions toTest = ProcessorFactory.GetCharacterCommonFunctions(access); var actual = toTest.spellCanBeCastByClass(realSpell_Class.Spell_id, realSpell_Class.Class_id); //Assert actual.Should().BeTrue(); } }
public void SubclassRepo_CharacterOfClassForgetsSubclass_ValidCall() { //Arrange List <Character_Class_Subclass> knownClasses = CreateTestData.GetListOfCharacter_Class_Subclass(); var mockSet = new Mock <DbSet <Character_Class_Subclass> >() .SetupData(knownClasses, o => { return(knownClasses.Single(x => x.Character_id.CompareTo(o.First()) == 0)); }); Character_Class_Subclass expected = new Character_Class_Subclass { Character_id = Guid.Parse("11111111-2222-3333-4444-555555555555"), Class_id = Guid.Parse("4e82620a-0496-4ecc-b6d4-05faa064310b"), RemainingHitDice = 12, ClassLevel = 12 }; using (var mockContext = AutoMock.GetLoose()) { mockContext.Mock <PlayableClassContext>() .Setup(x => x.KnownClasses).Returns(mockSet.Object); //Act var toTest = mockContext.Create <SubclassRepository>(); toTest.CharacterOfClassForgetsSubclass( expected.Character_id, expected.Class_id, Guid.Parse("c8d2e23a-a193-4e06-8814-9180d4830732")); var actual = knownClasses.First(); actual.Should().NotBeNull(); expected.Should().NotBeNull(); actual.Should().BeOfType <Character_Class_Subclass>(); expected.Should().BeOfType <Character_Class_Subclass>(); actual.Should().BeEquivalentTo(expected); } }
public async Task TestDownloadToFileAsync() { using var mock = AutoMock.GetStrict(); mock.Mock <IFileDeployerProvider>().Setup(x => x.Dispose()); mock.Mock <IOutputWriter>().Setup(x => x.WriteLineAsync(It.IsAny <string>())).Returns(Task.CompletedTask); string expected = @"Hello World! Lets Check Text! "; mock.Mock <IFileDownloadProvider>().Setup(x => x.DownloadFileToStreamAsync(It.IsAny <string>(), It.IsAny <Stream>())).Returns <string, Stream>((x, y) => { StreamWriter writer = new StreamWriter(y); writer.Write(expected); writer.Flush(); return(Task.CompletedTask); }); var sut = mock.Create <MonoRuntimeProvider>(); string tempFile = Path.GetTempFileName(); try { await sut.DownloadToFileAsync("", tempFile); var result = File.ReadAllText(tempFile); Assert.Equal(expected, result); } finally { File.Delete(tempFile); } }
public async Task GetLogsAsyncHappyPath() { using (var autoMock = AutoMock.GetStrict()) { var responseRepository = DataTestHelper.GivenTheDefaultListProductLikeLogDto(); AndIMockDependencyMethod <IProductLikeRepository, List <ProductLikeLogDto> >(autoMock, m => m.GetLogsAsync(), responseRepository); var sut = GivenTheSystemUnderTest(autoMock); var response = await sut.GetLogsAsync(); for (int index = 0; index < responseRepository.Count; index++) { Assert.AreEqual(responseRepository[index].Id, response[index].Id, $"[{index}].Id is not correct"); Assert.AreEqual(responseRepository[index].Username, response[index].Username, $"[{index}].Username is not correct"); Assert.AreEqual(responseRepository[index].DateTime, response[index].DateTime, $"[{index}].DateTime is not correct"); CheckAllProperties(responseRepository[index].PreviousEntity, response[index].PreviousEntity); CheckAllProperties(responseRepository[index].NewEntity, response[index].NewEntity); } } }
public async Task Search_ValidCall() { var mock = AutoMock.GetLoose(); var orderListMock = TestData.OrderSample(); mock.Mock <IRepository <Order> >().Setup(x => x.GetAll()).Returns(orderListMock); var taskTrue = Task.FromResult(true); var taskFalse = Task.FromResult(false); mock.Mock <IRoleFilter>().Setup(x => x.IsInRolesAsync(TestData.UserSample()[0])).Returns(taskTrue); mock.Mock <IRoleFilter>().Setup(x => x.IsInRolesAsync(TestData.UserSample()[1])).Returns(taskFalse); var model = mock.Create <OrderListViewModel>(); await model.GetDataAsync().ConfigureAwait(true); await model.ResetFormAsync(); model.DateFrom = new DateTime(2019, 01, 01); model.DateTo = new DateTime(2019, 12, 31); model.SearchWord = "John"; await model.SearchAsync(mock.Create <IRoleFilter>()).ConfigureAwait(true); Assert.Empty(model.ViewList); }
public async Task DeleteAsyncHappyPath() { using (var autoMock = AutoMock.GetStrict(RegisterBasicDependency)) { AndIMockDependencyMethod <ITokenFunctions, string>(autoMock, t => t.GetUsername(), "Username"); var entities = DataTestHelper.GivenTheDefaultListImageLike(); AndIAddRangeTableData(entities); var deletedDto = DataTestHelper.GivenTheDefaultListImageLikeDto().First(); var deletedEntity = entities.First(e => e.Id == deletedDto.Id); entities.Remove(deletedEntity); var sut = GivenTheSystemUnderTest(autoMock); var response = await sut.DeleteAsync(deletedDto); CheckAllProperties(deletedDto, response); var tableData = AndIGetTableData <ImageLike>(); CheckAllProperties(entities, tableData); } }
public void SdkTypes(string sdk, ProjectComponents expected) { // Arrange using var mock = AutoMock.GetLoose(); var projectFile = mock.Mock <IProjectFile>(); projectFile.Setup(f => f.IsSdk).Returns(true); projectFile.Setup(f => f.Sdk).Returns(sdk); projectFile.Setup(f => f.GetPropertyValue(It.IsAny <string>())).Returns(string.Empty); var project = mock.Mock <IProject>(); project.Setup(p => p.GetFile()).Returns(projectFile.Object); var componentIdentifier = mock.Create <ComponentIdentifier>(); // Act var components = componentIdentifier.GetComponents(project.Object); // Assert Assert.Equal(expected, components); }
private static void AssertProperties(AutoMock mock) { Assert.IsNotNull(mock.Container); Assert.IsNotNull(mock.MockRepository); }
private static void SetUpVerifableSetupations(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()).Verifiable(); mock.Mock<IServiceA>().Setup(x => x.RunA()).Verifiable(); }
public void Setup() { _autoMock = new AutoMock(); _controller = _autoMock.Resolve<PersonController>(); _person.Id = 0; }
private static void RunTest(AutoMock mock) { SetUpSetupations(mock); var component = mock.Create<TestComponent>(); component.RunAll(); }
private static void SetUpSetupations(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()); mock.Mock<IServiceA>().Setup(x => x.RunA()); }
public void Init() { mocker = AutoMock.GetLoose(); banker = mocker.Create<Banker>(); player = mocker.Create<Player>(); }
private static void RunWithSingleSetupationTest(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()); var component = mock.Create<TestComponent>(); component.RunAll(); }