public void Test_Get() { using var moc = AutoMock.GetStrict(); var expectedResult = new List <string> { "Value1", "Value2" }; var mockValueService = moc.Mock <IValuesService>(); mockValueService.Setup(x => x.Get()).Returns(expectedResult); var valueService = moc.Create <IValuesService>(); var result = valueService.Get(); moc.Mock <IValuesService>().Verify(x => x.Get()); Assert.AreEqual(expectedResult, result); //Assert.Pass(); }
public void StationNotFound() { using var mocker = AutoMock.GetStrict(); var seatInfo = SeatInfo.Create(Enumerable.Range(1000, 4).ToList()); mocker.Mock <IClaptrapGrainCommonService>() .Setup(x => x.ClaptrapAccessor.Claptrap.State.Data) .Returns(seatInfo); var grain = mocker.Create <SeatGrain>(); grain.SeatId = 123; const string reqId1 = "newbe36524-1"; Assert.ThrowsAsync <StationNotFoundException>(() => grain.TakeSeatAsync(1000, 9999, reqId1)); Assert.ThrowsAsync <StationNotFoundException>(() => grain.TakeSeatAsync(1, 1000, reqId1)); }
public async Task GetCallsOneQueryTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new JsonElement())); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var onlineEventData = mock.Create <OnlineEventData>(); // act await onlineEventData.Get(1); // assert mock.Mock <ISqlDataAccess>().Verify(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()), Times.Once); }
public async Task GetCallsOneQueryTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(JsonDocument.Parse(JsonSerializer.Serialize(CreateEmailQueueMessage())).RootElement)); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var emailTemplatesData = mock.Create <EmailTemplatesData>(); // act await emailTemplatesData.Get <EmailQueueMessage>("testTemplate"); // assert mock.Mock <ISqlDataAccess>().Verify(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()), Times.Once); }
public async Task InsertCallOneQueryTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new JsonElement())); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var bcParametersData = mock.Create <BCParametersData>(); // act await bcParametersData.Insert(new BCParameter { Key = "Key", Value = "Value" }); // assert mock.Mock <ISqlDataAccess>().Verify(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()), Times.Once); }
public async Task UpdateCallOneQueryTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new JsonElement())); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var onlineEventData = mock.Create <OnlineEventData>(); // act await onlineEventData.Update(1, new OnlineEvent { Name = "", Description = "", ImageContent = new byte[1], Organizer = "" }); // assert mock.Mock <ISqlDataAccess>().Verify(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>()), Times.Once); }
public void TestWrite() { File.Delete(@"..\..\Test\exporter.xml"); using (var mock = AutoMock.GetStrict()) { var fileSystem = new MockFileSystem(); mock.Provide <IFileSystem>(fileSystem); var exporter = mock.Create <XmlExporter>(); exporter.Write( @"..\..\Test\exporter.xml", new Dummy { TestInt = 4, TestString = "bla" }); AssertSameFileContent(@"..\..\Test\exporter.xml", @"..\..\Test\exporter-expected.xml"); } }
public async Task InsertReturnsIdTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new JsonElement())); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var bcParametersData = mock.Create <BCParametersData>(); // act var actual = await bcParametersData.Insert(new BCParameter { Key = "Key", Value = "Value" }); // assert Assert.IsNotNull(actual.Id, "Returned id is null"); }
public async Task PutAsJsonAsyncCallsPutAsJsonAsyncOnIHttpClientHelperTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <IHttpClientHelper>() .Setup(x => x.PutAsJsonAsync(It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.NoContent })); var httpHelper = mock.Create <HttpHelper>(); // act await httpHelper.PutAsJsonAsync("", new object()); // assert mock.Mock <IHttpClientHelper>().Verify(x => x.PutAsJsonAsync(It.IsAny <string>(), It.IsAny <object>()), Times.Once); }
public async Task GetReturnsJsonElementTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new JsonElement())); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var onlineEventData = mock.Create <OnlineEventData>(); // act var actual = await onlineEventData.Get(1); // assert Assert.IsInstanceOf <JsonElement>(actual); }
public async Task RemoveSuccess() { using var mocker = AutoMock.GetStrict(); await using var handler = mocker.Create <RemoveAllItemsFromCartEventHandler>(); const string oldKey = "oneKey"; var state = new CartState { Items = new Dictionary <string, int> { { oldKey, 100 } } }; var evt = new RemoveAllItemsFromCartEvent(); await handler.HandleEvent(state, evt, default); state.Items.Should().BeNull(); }
public async Task UpdateAsyncHappyPath() { using (var autoMock = AutoMock.GetStrict()) { var request = DataTestHelper.GivenTheDefaultCategoryDto(); var responseRepository = DataTestHelper.GivenTheDefaultCategoryDto(); AndIMockDependencyMethod <ICategoryRepository, CategoryDto, CategoryDto>(autoMock, m => m.UpdateAsync(It.IsAny <CategoryDto>()), responseRepository, param => { CheckAllProperties(request, param); }); var sut = GivenTheSystemUnderTest(autoMock); var response = await sut.UpdateAsync(request); CheckAllProperties(responseRepository, response); } }
public async Task GetItemsAsync() { using var mocker = AutoMock.GetStrict(); var stateData = new SkuState { Inventory = 666 }; mocker.Mock <IClaptrapGrainCommonService>() .Setup(x => x.ClaptrapAccessor.Claptrap.State.Data) .Returns(stateData); var handler = mocker.Create <SkuGrain>(); var items = await handler.GetInventoryAsync(); items.Should().Be(stateData.Inventory); }
public async Task TestReadSettingsCatchesIoException() { using var mock = AutoMock.GetStrict(); mock.Mock <IProjectInformationProvider>().Setup(x => x.GetProjectRootDirectoryAsync()).Returns(() => { return(Task.FromResult(Path.GetTempPath())); }); mock.Mock <IExceptionThrowerProvider>().Setup(x => x.ThrowException(It.IsAny <string>())).Returns(new Exception()); mock.Mock <IBuildSettingsProvider>().SetupGet(x => x.Verbose).Returns(false); mock.Mock <IFileReaderProvider>().Setup(x => x.ReadFileAsStringAsync(It.IsAny <string>())).Throws(new IOException("Failed to read file")); var sut = mock.Create <JsonFrcSettingsProvider>(); var actual = await sut.GetFrcSettingsAsync().ConfigureAwait(false); Assert.Null(actual); }
public async Task InsertReturnsIdTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <ISqlDataAccess>() .Setup(x => x.ExecuteStoredProcedureAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(Task.FromResult(new JsonElement())); mock.Mock <IConfigProvider>() .Setup(x => x.GetConnectionString(Application.BandCamsDb)) .Returns("test"); var onlineEventData = mock.Create <OnlineEventData>(); // act var actual = await onlineEventData.Insert(new OnlineEvent { Name = "", Description = "", ImageContent = new byte[1], Organizer = "" }); // assert Assert.IsNotNull(actual.Id, "Returned id is null"); }
protected void TestViewModelProperties <T>(string propertyName, Action <T> action) where T : BaseViewModel { using (var mock = AutoMock.GetStrict()) { var called = false; var viewModel = mock.Create <T>(); viewModel.PropertyChanged += (sender, args) => { called = true; Assert.AreEqual(viewModel, sender); Assert.AreEqual(propertyName, args.PropertyName); }; action(viewModel); Assert.IsTrue(called); } }
public void TestStartWithSubFolderWithInvalidXmlFile() { 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.SetupGet(m => m.DataPath).Returns(@"C:\root"); settings.SetupGet(m => m.DataFilename).Returns("song.xml"); var importer = mock.Mock <IImporter>(); importer.Setup(m => m.Read <DirectoryData>(@"C:\root\bla\song.xml")).Returns(null as DirectoryData); var expectedDirectoryStatus = new DirectoryData { Status = DirectoryStatus.UNKNOWN, Song = null }; var exporter = mock.Mock <IExporter>(); exporter.Setup(m => m.Write(@"C:\root\bla\song.xml", expectedDirectoryStatus)); 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(); settings.VerifyGet(m => m.DataPath, Times.Once); settings.VerifyGet(m => m.DataFilename, Times.Once); importer.Verify(m => m.Read <DirectoryData>(@"C:\root\bla\song.xml"), Times.Once); exporter.Verify(m => m.Write(@"C:\root\bla\song.xml", expectedDirectoryStatus), Times.Once); directoriesService.Verify(m => m.AddTask(expectedTask), Times.Once); } }
public void TestDeleteByPath() { using (var mock = AutoMock.GetStrict()) { using (var mock2 = AutoMock.GetStrict()) { using (var mock3 = AutoMock.GetStrict()) { var songViewModel1 = mock.Mock <ISongViewModel>(); songViewModel1.SetupGet(m => m.Path).Returns("bla"); var songViewModel2 = mock2.Mock <ISongViewModel>(); songViewModel2.SetupGet(m => m.Path).Returns(@"bla\test"); var songViewModel3 = mock3.Mock <ISongViewModel>(); songViewModel3.SetupGet(m => m.Path).Returns(@"x\bla\test"); var collection = new ObservableCollection <IDirectoryListItem> { songViewModel1.Object, songViewModel2.Object, songViewModel3.Object }; var dispatcher = mock.Mock <IDispatcher>(); dispatcher.Setup(m => m.Invoke(It.IsAny <Action>())).Callback <Action>(action => action()); var model = mock.Mock <IDirectoryCollectionProperty>(); model.SetupGet(m => m.Directories).Returns(collection); var directoriesService = mock.Create <Directories>(); directoriesService.DeleteByPath("bla"); Assert.AreEqual(1, collection.Count); Assert.IsFalse(collection.Contains(songViewModel1.Object)); Assert.IsFalse(collection.Contains(songViewModel2.Object)); Assert.IsTrue(collection.Contains(songViewModel3.Object)); songViewModel1.VerifyGet(m => m.Path, Times.Once); songViewModel2.VerifyGet(m => m.Path, Times.Once); songViewModel3.VerifyGet(m => m.Path, Times.Once); dispatcher.Verify(m => m.Invoke(It.IsAny <Action>()), Times.Once); model.VerifyGet(m => m.Directories, Times.Exactly(3)); } } } }
public async Task GetByIdAsyncHappyPath() { using (var autoMock = AutoMock.GetStrict(RegisterBasicDependency)) { var entities = DataTestHelper.GivenTheDefaultListProductLike(); AndIAddRangeTableData(entities); var sut = GivenTheSystemUnderTest(autoMock); var entity = entities.First(); var idRequest = entity.Id; var response = await sut.GetByIdAsync(idRequest); CheckAllProperties(entity, response); var tableData = AndIGetTableData <ProductLike>(); CheckAllProperties(entities, tableData); } }
public async Task AddAsyncDuplicatePath() { using (var autoMock = AutoMock.GetStrict(RegisterBasicDependency)) { var request = DataTestHelper.GivenTheDefaultProductRequest(); AndIMockDependencyMethod <IProductBll, ProductDto, ProductDto>(autoMock, m => m.AddAsync(It.IsAny <ProductDto>()), null, param => { CheckAllProperties(request, param); }); var sut = GivenTheSystemUnderTest(autoMock); var response = await sut.AddAsync(request); Assert.AreEqual((int)HttpStatusCode.Conflict, response.StatusCode, "StatusCode is not correct"); Assert.AreEqual(BaseConstants.ERROR_MESSAGE_DUPLICATE, (string)response.Value, "Value is not correct"); } }
public async Task AddAsyncErrorPath() { using (var autoMock = AutoMock.GetStrict(RegisterBasicDependency)) { var request = DataTestHelper.GivenTheDefaultProductRequest(); var exception = new Exception("Bll throw Exception"); AndIMockDependencyMethod <IProductBll, ProductDto, Exception>(autoMock, m => m.AddAsync(It.IsAny <ProductDto>()), exception); AndIMockILogger(autoMock); var sut = GivenTheSystemUnderTest(autoMock); var response = await sut.AddAsync(request); Assert.AreEqual((int)HttpStatusCode.InternalServerError, response.StatusCode, "StatusCode is not correct"); Assert.AreEqual(BaseConstants.ERROR_MESSAGE, response.Value, "Message is not correct"); } }
public async Task RemoveSuccess() { using var mocker = AutoMock.GetStrict(); await using var handler = mocker.Create <InventoryUpdateEventHandler>(); var stateData = new SkuState { Inventory = 789 }; var inventoryUpdateEvent = new InventoryUpdateEvent { NewInventory = 666, Diff = -66 }; await handler.HandleEvent(stateData, inventoryUpdateEvent, default); stateData.Inventory.Should().Be(inventoryUpdateEvent.NewInventory); }
public void Test2() { using (var mocker = AutoMock.GetStrict()) { mocker.VerifyAll = true; // 因为我们确定不会调用IMahuaApi,所以不需要Mock // 这里使用的是V2 IPrivateMessageFromFriendReceivedMahuaEvent @event = mocker.Create <PrivateMessageFromFriendReceivedMahuaEventV2>(); @event.ProcessFriendMessage(new PrivateMessageFromFriendReceivedContext { FromQq = "472158246", Message = "呵呵哒", SendTime = DateTime.Now }); } }
public void Get_WhenCalled_ReturnsOkObjectResult() { using (var mock = AutoMock.GetStrict()) { // Arrange mock.Mock <IQueryAdapter <BookReadModel, int> >() .Setup(_ => _.GetAll()) .Returns(Task.FromResult(_fixture.ReadModels)); var controller = mock.Create <BooksController>(); // Act var response = controller.Get().Result as OkObjectResult; // Assert Assert.IsAssignableFrom <OkObjectResult>(response); Assert.IsAssignableFrom <IEnumerable <BookReadModel> >(response.Value); } }
public void Remove_ExistingGuidPassed_ReturnsOkResult() { using (var mock = AutoMock.GetStrict()) { // Arrange mock.Mock <IAzureServiceBusCommandAdapter>() .Setup(_ => _.Dispatch(It.IsAny <IDeleteBookCommand>())); var controller = mock.Create <BooksController>(); const int existingId = 1; // Act var response = controller.Delete(existingId); // Assert Assert.IsType <OkResult>(response); mock.Mock <IAzureServiceBusCommandAdapter>().VerifyAll(); } }
public void TestStart() { using (var mock = AutoMock.GetStrict()) { var fileSystem = new MockFileSystem( new Dictionary <string, MockFileData> { { @"C:\root\", new MockDirectoryData() } }); mock.Provide <IFileSystem>(fileSystem); var settings = mock.Mock <ISettings>(); settings.SetupGet(m => m.DataPath).Returns(@"C:\root"); var checker = mock.Create <Checker>(); checker.Start(); settings.VerifyGet(m => m.DataPath, Times.Once); } }
public async Task OnGetPreviousMonthReturnsCalendarTagHtmlTest() { // arrange var expected = "<div class=\"container-fluid\">"; using var mock = AutoMock.GetStrict(); mock.Mock <IHttpHelper>() .Setup(x => x.GetAsync <List <OnlineEvent> >(It.IsAny <string>())) .Returns(Task.FromResult(new List <OnlineEvent>())); var calendarModel = mock.Create <CalendarModel>(); // act var result = await calendarModel.OnGetPreviousMonth(2000, 1); var actual = result as ContentResult; // assert StringAssert.StartsWith(expected, actual?.Content); }
public void AllBooksQueryHandler_Should_ReturnAllItems() { using (var mock = AutoMock.GetStrict()) { // Arrange mock.Provide(_fixture.DbContextMock.Object); mock.Provide(_fixture.MapperMock.Object); var handler = mock.Create <AllBooksQueryHandler>(); // Act var result = handler.Handle(new AllBooksQuery()); // Assert Assert.NotNull(result); var bookCount = Assert.IsAssignableFrom <IEnumerable <BookReadModel> >(result); Assert.Equal(_fixture.BookDomainModels.Count(), bookCount.Count()); } }
public async Task GetAsyncCallsGetAsyncOnIHttpClientHelperTest() { // arrange using var mock = AutoMock.GetStrict(); mock.Mock <IHttpClientHelper>() .Setup(x => x.GetAsync(It.IsAny <string>())) .Returns(Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("") })); var httpHelper = mock.Create <HttpHelper>(); // act await httpHelper.GetAsync <string>(""); // assert mock.Mock <IHttpClientHelper>().Verify(x => x.GetAsync(It.IsAny <string>()), Times.Once); }
public Task UpdateInventoryFailed_Diff0() { using var mocker = AutoMock.GetStrict(); const int sourceInventory = 666; const int diff = 0; var stateData = new SkuState { Inventory = sourceInventory }; mocker.Mock <IClaptrapGrainCommonService>() .Setup(x => x.ClaptrapAccessor.Claptrap.State.Data) .Returns(stateData); var handler = mocker.Create <SkuGrain>(); Assert.ThrowsAsync <BizException>(() => handler.UpdateInventoryAsync(diff)); return(Task.CompletedTask); }