public void ActivateAd_ActivationTokenDoesNotWork_ReturnModelIsActivatedFalse() { // Given BaseAd ad = new Ad() { IsActivated = false, ActivationToken = "AAA" }; long adId = 78; var repoMock = new Moq.Mock<IRepository>(); repoMock.Setup(x => x.Get<BaseAd>(adId)).Returns(ad); AdActivationServices service = new AdActivationServices(repoMock.Object, null, null, null); // When AdActivationResultModel model = service.ActivateAd(adId, "BBB"); // Then Assert.IsFalse(model.IsActivated); Assert.AreEqual(78, model.AdId); Assert.AreEqual("Vous ne pouvez pas activer cette annonce.", model.InfoMessage); repoMock.Verify(x => x.Save(ad), Moq.Times.Never()); repoMock.Verify(x => x.Save(Moq.It.IsAny<SearchAdCache>()), Moq.Times.Never()); }
public void shouldHaveSynchronizeWithGoogleFunction() { var avegaContactServiceMock = new Moq.Mock<IAvegaContactService>(); avegaContactServiceMock.Setup(x => x.SynchronizeWithGoogleContact(It.IsAny<AvegaContact>())) .Returns(new SynchronizationStatus(true, false, false)); var avetaContactService = avegaContactServiceMock.Object; avetaContactService.SynchronizeWithGoogleContact(new AvegaContact("MyContact")); avegaContactServiceMock.Verify(); }
public void IObjectStateAsObjectReference() { IObjectState o = null; Assert.That(o.AsObjectReference(), Is.Null); var m = new Moq.Mock<IObjectState>(MockBehavior.Strict); m.Setup(x => x.ObjectId).Returns(1); m.Setup(x => x.Name).Returns("X"); var objRef = m.Object.AsObjectReference(); Assert.IsNotNull(objRef); Assert.That(objRef.Value.Id, Is.EqualTo(1)); Assert.That(objRef.Value.Name, Is.EqualTo("X")); }
public void An_invalid_server_path_is_treated_as_a_script_and_arguments_ignored_if_local_path_that_cannot_be_found() { // Arrange var fakeTfsProvider = new Moq.Mock<IUtilitiesForPowerShellActivity>(); fakeTfsProvider.Setup(f => f.IsServerItem(It.IsAny<string>())).Returns(false); fakeTfsProvider.Setup(f => f.FileExists(It.IsAny<string>())).Returns(false); var activity = new InvokePowerShellCommand(fakeTfsProvider.Object); // Act var actual = activity.ResolveScript(null, @"some powershell commands", "-myarg"); // assert Assert.AreEqual(@"some powershell commands", actual); }
public ContextMocks(Controller controller) { //define context objects HttpContext = new Moq.Mock<HttpContextBase>(); Request = new Mock<HttpRequestBase>(); User = new Mock<IPrincipal>(); HttpContext.Setup(x => x.Request).Returns(Request.Object); HttpContext.Setup(x => x.User).Returns(User.Object); //you would setup Response, Session, etc similarly with either mocks or fakes //apply context to controller RequestContext rc = new RequestContext(HttpContext.Object, new RouteData()); controller.ControllerContext = new ControllerContext(rc, controller); }
public void An_invalid_server_path_is_treated_as_a_filesystem_script_file_and_arguments_appended() { // Arrange var fakeTfsProvider = new Moq.Mock<IUtilitiesForPowerShellActivity>(); fakeTfsProvider.Setup(f => f.IsServerItem(It.IsAny<string>())).Returns(false); fakeTfsProvider.Setup(f => f.FileExists(It.IsAny<string>())).Returns(true); var activity = new InvokePowerShellCommand(fakeTfsProvider.Object); // Act var actual = activity.ResolveScript(null, @"c:\localscript.ps1", "-myarg"); // assert Assert.AreEqual(@"& 'c:\localscript.ps1' -myarg", actual); }
public void A_valid_server_path_generates_a_cmd_with_arguments() { // Arrange var fakeTfsProvider = new Moq.Mock<IUtilitiesForPowerShellActivity>(); fakeTfsProvider.Setup(f => f.IsServerItem(It.IsAny<string>())).Returns(true); fakeTfsProvider.Setup(f => f.GetLocalFilePathFromWorkspace(null, It.IsAny<string>())).Returns(@"c:\serverfile\script.ps1"); fakeTfsProvider.Setup(f => f.FileExists(It.IsAny<string>())).Returns(true); var activity = new InvokePowerShellCommand(fakeTfsProvider.Object); // Act var actual = activity.ResolveScript(null, "$/Test Path/Not A Real Path", "-myarg"); // assert Assert.AreEqual(@"& 'c:\serverfile\script.ps1' -myarg", actual); }
public void AdvancedSearchAds_SearchThroughAds_CallSearchRepoOnAds() { // Given Category cat = new Category { Id = 1, LabelUrlPart = "cat-url-label", Label = "Label", Type = AdTypeEnum.Ad }; AdSearchModel model = new AdSearchModel(); model.CategorySelectedId = 1; model.SearchString = "toto"; model.CitySelectedId = 12; IList<SearchAdCache> searchResult = new List<SearchAdCache>(); searchResult.Add(new SearchAdCache { Title = "ship", City = new City() { Label = "the city" }, Category = cat }); var repoMock = new Moq.Mock<IRepository>(); repoMock.Setup(r => r.Get<Category>(cat.Id)).Returns(cat); var searchRepoMock = new Moq.Mock<ISearchRepository>(); searchRepoMock.Setup(r => r.SearchAds(It.Is<String[]>(x => x[0] == "toto"), 12, It.Is<int[]>(x => x[0] == 1))).Returns(searchResult); SearchServices service = new SearchServices(repoMock.Object, null, searchRepoMock.Object, null, null, null); // When AdSearchResultModel result = service.LightSearchAds(model); // Then Assert.AreEqual(1, result.SearchResultTotalCount); }
public void If_a_valid_server_path_that_cannot_be_found_locally_throws_exception() { // Arrange var fakeTfsProvider = new Moq.Mock<IUtilitiesForPowerShellActivity>(); fakeTfsProvider.Setup(f => f.IsServerItem(It.IsAny<string>())).Returns(true); fakeTfsProvider.Setup(f => f.GetLocalFilePathFromWorkspace(null, It.IsAny<string>())).Returns(@"c:\serverfile\script.ps1"); fakeTfsProvider.Setup(f => f.FileExists(It.IsAny<string>())).Returns(false); var activity = new InvokePowerShellCommand(fakeTfsProvider.Object); // Act var actual = activity.ResolveScript(null, "$/Test Path/Not A Real Path", "-myarg"); // assert // checked with attribute }
public void AsteroidHasDifficulty() { var veldnium = new ItemInfo(ItemCode.Veldnium); var itemFactory = new Moq.Mock<IItemFactory>(MockBehavior.Strict); itemFactory.Setup(x => x.Build(ItemCode.Veldnium, It.IsAny<uint>())) .Returns<ItemCode, uint>((item, quantity) => new Item(veldnium, quantity)); var mining = new MiningTask(itemFactory.Object) { }; mining.SetParameters(new MineAsteroidParameters(_ship, _difficultAsteroid)); var result = mining.Mine(); Assert.That(result.Success, Is.True); Assert.That(result.StatusCode, Is.EqualTo(ShipTask.StatusCode.Pending)); Assert.That(_difficultAsteroid.AmountRemaining, Is.EqualTo(1000)); Assert.That(_ship.Tasks, Contains.Item(mining)); result = mining.Mine(); Assert.That(result.Success, Is.True); Assert.That(result.StatusCode, Is.EqualTo(ShipTask.StatusCode.Success)); Assert.That(result.Ore.Quantity, Is.EqualTo(2)); Assert.That(_difficultAsteroid.AmountRemaining, Is.EqualTo(998)); _ship.Tasks.ShouldNotContain(mining); }
public void SetUp() { var mock = new Moq.Mock<ILocationServices>(); mock.Setup(x => x.GetExitPosition(It.IsAny<ILocation>())).Returns<ILocation>(l => l.Position.LocalCoordinates); _task = new JumpShipTask(mock.Object); }
private static IDataService GetDataServiceMock(List<Product> products) { var dataServiceMock = new Moq.Mock<IDataService>(MockBehavior.Strict); dataServiceMock.Setup(s => s.GetProductsByProductCode(It.IsAny<int>())).Returns(products); return dataServiceMock.Object; }
public void ActivateAd_ActivationTokenWorks_ReturnModelIsActivatedTrueAndActivatesAd() { // Given BaseAd ad = new Ad() { IsActivated = false, ActivationToken = "AAA", City = new City(), Category = new Category() }; long adId = 78; var repoMock = new Moq.Mock<IRepository>(); repoMock.Setup(x => x.Get<BaseAd>(adId)).Returns(ad); AdActivationServices service = new AdActivationServices(repoMock.Object, null, null, null); // When AdActivationResultModel model = service.ActivateAd(78, "AAA"); // Then Assert.IsTrue(model.IsActivated); Assert.AreEqual(78, model.AdId); Assert.AreEqual("Merci d'avoir activé votre annonce.", model.InfoMessage); repoMock.Verify(x => x.Save(ad), Moq.Times.Once()); repoMock.Verify(x => x.Save(Moq.It.IsAny<SearchAdCache>()), Moq.Times.Once()); }
public void Test_NormalViewModel() { ClearAll(); IMvxViewModel outViewModel = new Test2ViewModel(); var mockLocator = new Mock<IMvxViewModelLocator>(); mockLocator.Setup( m => m.Load(It.IsAny<Type>(), It.IsAny<IMvxBundle>(), It.IsAny<IMvxBundle>())) .Returns(() => outViewModel); var mockCollection = new Moq.Mock<IMvxViewModelLocatorCollection>(); mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny<MvxViewModelRequest>())) .Returns(() => mockLocator.Object); Ioc.RegisterSingleton(mockCollection.Object); var parameters = new Dictionary<string, string> { { "foo", "bar" } }; var request = new MvxViewModelRequest<Test2ViewModel>(new MvxBundle(parameters), null, MvxRequestedBy.UserAction); var state = new MvxBundle(); var loader = new MvxViewModelLoader(); var viewModel = loader.LoadViewModel(request, state); Assert.AreSame(outViewModel, viewModel); Assert.AreEqual(MvxRequestedBy.UserAction, viewModel.RequestedBy); }
string GetOutboundUrl(object routeValues) { // Get route configuration and mock request context RouteCollection routes = new RouteCollection(); MvcApplication.RegisterRoutes(routes); var mockHttpContext = new Moq.Mock<HttpContextBase>(); var mockRequest = new Moq.Mock<HttpRequestBase>(); var fakeResponse = new FakeResponse(); mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object); mockHttpContext.Setup(x => x.Response).Returns(fakeResponse); mockRequest.Setup(x => x.ApplicationPath).Returns("/"); // Generate the outbound URL var ctx = new RequestContext(mockHttpContext.Object, new RouteData()); return routes.GetVirtualPath(ctx, new RouteValueDictionary(routeValues)) .VirtualPath; }
static IProductsRepository MockProductsRepository(params Product[] prods) { var mockProductsRepos = new Moq.Mock<IProductsRepository>(); mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable()); return mockProductsRepos.Object; }
private void GoalSetup() { AutoMapper.Mapper.CreateMap<ContestEventGoal, ContestEventGoalViewModel>() .ForMember(dest => dest.Result, opt => opt.ResolveUsing<GoalDataResolver>()); profileRepositoryMock = new Moq.Mock<IProfileRepository>(); profileRepositoryMock.Setup(t => t.RetrieveGoals()).Returns(goals); controller = new GoalController(profileRepositoryMock.Object); }
public OwinServerFixture() { var list = new List<TodoItem> { new TodoItem() { Id = 1, Completed = false, Title = "Test 1" }, new TodoItem() { Id = 2, Completed = true, Title = "Test 2" } }; ServiceMock = new Moq.Mock<ITodoService>(); ServiceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list); var notCompleted = list.Where(x => x.Completed == false).ToList(); ServiceMock.Setup(x => x.ClearCompleted()).ReturnsAsync(notCompleted); var newTask = new TodoItem() { Completed = false, Title = "Test 3" }; ServiceMock.Setup(x => x.AddAsync(It.IsAny<TodoItem>())).ReturnsAsync(newTask); const int taskId = 2; var existingTask = new TodoItem() { Id = 2, Completed = false, Title = "Test 3" }; ServiceMock.Setup(x => x.UpdateAsync(taskId, It.IsAny<TodoItem>())).ReturnsAsync(existingTask); ServiceMock.Setup(x => x.DeleteAsync(taskId)).ReturnsAsync(true); const int missingTaskId = 4; ServiceMock.Setup(x => x.UpdateAsync(missingTaskId, existingTask)).ReturnsAsync(null); ServiceMock.Setup(x => x.DeleteAsync(missingTaskId)).ReturnsAsync(false); TestServer = TestServer.Create(Configuration); }
IScriptModuleRepository GetMockedScriptModuleRepositoryForDependencyGraph(IEnumerable<string> dependencyGraph, out ModuleInfo mainModule) { var moduleRepo = new Moq.Mock<IScriptModuleRepository>(); foreach (var moduleInfo in GetModuleArrayFromDependencyGraph(dependencyGraph, out mainModule)) { moduleRepo.Setup((repo) => repo.GetModule(moduleInfo.Name)).Returns(moduleInfo); } return moduleRepo.Object; }
public void CanBuild() { var itemFactory = new Moq.Mock<IItemFactory>(MockBehavior.Strict); var expected = TestItems.BuildItem(_universe.BluePrint.Code, _universe.BluePrint.TargetQuantity); itemFactory.Setup(f => f.Build(_universe.BluePrint.Code, _universe.BluePrint.TargetQuantity)).Returns(expected); var item = BluePrint.Build(itemFactory.Object); item.ShouldBeSameAs(expected); }
public void shouldHaveGetAll() { var avegaContactRepositoryMock = new Moq.Mock<IAvegaClientRepository>(); avegaContactRepositoryMock.Setup(x=>x.GetAll()) .Returns(new List<AvegaContact>()); IAvegaClientRepository avegaContactRepository = avegaContactRepositoryMock.Object; avegaContactRepository.GetAll(); }
public void shouldBeAbleToValidateAuthentication() { var avegaClientRepositoryMock = new Moq.Mock<IAvegaClientRepository>(); avegaClientRepositoryMock.Setup(x => x.IsAuthenticationValid).Returns(true); Assert.IsTrue(avegaClientRepositoryMock.Object.IsAuthenticationValid); }
public void shouldBeAbleToGetAllAvegaContact() { var avegaContactServiceMock = new Moq.Mock<IAvegaContactService>(); avegaContactServiceMock.Setup(x => x.GetAllContacts()) .Returns(new List<AvegaContact>()); var avetaContactService = avegaContactServiceMock.Object; avetaContactService.GetAllContacts(); avegaContactServiceMock.Verify(); }
public void OpenTest() { var mock = new Moq.Mock<IMyDriver>(); var client = new MyWork.MyConnection(new[] {mock.Object}); mock.Setup(driver => driver.Connect()); client.Open(); mock.VerifyAll(); }
public void MigrateToShouldExecuteDownTwice() { var migrations = new List<Migration> { new Migration("2006", "asdf", ""), new Migration("2006-01", "98sd98", ""), new Migration("2007", "fdsa", "") }; var hash = new Dictionary<string, string>(); foreach (var mig in migrations) hash.Add(mig.Version, mig.Hash); var db = new MigrationTracker(migrations, hash); var repoMoq = new Moq.Mock<IDatabaseRepository>(); int y = 0; repoMoq.Setup(x => x.ExecuteDown(It.IsAny<Migration>())).Callback((Migration input) => { y++; }); repoMoq.Setup(x => x.Create()).Returns(db); var migrator = new Migrator(db, repoMoq.Object); migrator.MigrateTo("2006"); Assert.IsTrue(y== 2, "ExecuteDown should be called two times but is called " + y.ToString()); }
public void AggregateBus_RegisteredAggregateCachesShouldContainAtLeastTheConfiguredValue() { var eventBus = new Moq.Mock<IEventBus>(); eventBus.Setup(e => e.Subscribe<AggregateCacheCleared>(Moq.It.IsAny<Func<AggregateCacheCleared, Task>>())).Verifiable(); var aggregateCache = new Moq.Mock<IAggregateCache>(); AggregateBus.Instance.Configure(eventBus.Object, aggregateCache.Object); AggregateBus.Instance.RegisteredAggregateCaches.FirstOrDefault().Should().Be(aggregateCache.Object); }
public void CancelAsync() { var element = new ImportNetworkElement(); var mockMyFx = new Moq.Mock<IImportNetworkFx>(); mockMyFx.Setup(m => m.CancelAsync()); element.Fx = mockMyFx.Object; element.Cancel(); mockMyFx.Verify(m => m.CancelAsync(), Times.Exactly(1)); }
public void When() { var mock = new Moq.Mock<ITextInstructionFactory>(); mock.Setup( m => m.CreateInstruction(It.IsAny<string>())) .Returns((string s) => new StubInstruction(s)); _stringReader = new StringReader(StreamText); Instructions = new InstructionReader(_stringReader, mock.Object); }
public void HappyPath_NightWatchmanAnalysis_BuildMachineData() { const int DesktopCount = 50123; const int LaptopCount = 50321; const string companyName = "Nightwatchman Company, Ltd"; long totalMachine = 5000; long machinesOnForWeekdays = 3000; long machinesOnForWeekend = 2000; long noOfDays = 15; var machineData = BuildMachineData(DesktopCount, LaptopCount); DataTable machineActivityData; DataTable machineActivityValidationData; BuildMachineActivityData(totalMachine, machinesOnForWeekdays, machinesOnForWeekend, noOfDays, out machineActivityData, out machineActivityValidationData); Dictionary<string, DataTable> mockValues = new Dictionary<string, DataTable>() { {"MachineData",machineData}, {"MachineActivityData",machineActivityData}, {"Validate_MachineActivityData",machineActivityValidationData} }; var mockQueryExecutor = new Moq.Mock<IQueryExecutor>(); mockQueryExecutor.Setup( m => m.ExecuteQuery(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<SqlParameter[]>())) .Returns( (string a, string b, string tableName, SqlParameter[] p) => mockValues[tableName]); string assemblyPath; assemblyPath = Directory.GetCurrentDirectory(); Console.WriteLine("Working directory: " + assemblyPath); var context = new CommonExtractionContext() { CompanyName = companyName, BaseWorkDirectory = assemblyPath, PluginsDirectory = assemblyPath }; var factory = new DataExtractorFactory(context.PluginsDirectory); var nwmExtractor = factory.GetExtractor<NightWatchmanDataExtractor>(); Assert.NotNull(nwmExtractor, "DataExtractorFactory failed to load NightWatchmanDataExtractor"); var extractor = new DataExtractor(factory, mockQueryExecutor.Object); var zipFile = extractor.BuildPackage(context); Assert.IsTrue(File.Exists(zipFile), "Failed to create Zip file"); Assert.IsTrue((string.Compare(Path.GetFileNameWithoutExtension(zipFile), context.CompanyName) == 0), "Zip file is not correctly named"); // Need to add more code to test zip file paths }
public void InSuggester_PassSeveralSourcesAndSeveralStringKeywords_CheckThatReturnsCombinedReslt() { // Setup several returning values // HACK had to use Moq directly instead of mocking kernel because it returned the same object. In this case it is ok, but once know how to solve it better change code. var resultMock1 = new Moq.Mock<ISuggestionInstance>(); resultMock1.Setup(r => r.GetTextValue()).Returns("one"); resultMock1.Setup(r => r.Relevance).Returns(10); var resultMock2 = new Moq.Mock<ISuggestionInstance>(); resultMock2.Setup(r => r.GetTextValue()).Returns("two"); resultMock2.Setup(r => r.Relevance).Returns(10); var resultMock3 = new Moq.Mock<ISuggestionInstance>(); resultMock3.Setup(r => r.GetTextValue()).Returns("three"); resultMock3.Setup(r => r.Relevance).Returns(10); this.kernel.Bind<ISuggestionInstance>().ToMethod(s => resultMock1.Object); this.kernel.Bind<ISuggestionInstance>().ToMethod(s => resultMock2.Object); this.kernel.Bind<ISuggestionInstance>().ToMethod(s => resultMock3.Object); // Setup two sources var sourceMock2 = new Moq.Mock<ISuggestionSource>(); sourceMock2.Setup(m => m.GetSuggestions(It.IsAny<ISemanticObject>())).Returns(new ISuggestionInstance[] { resultMock1.Object, resultMock2.Object }); var sourceMock1 = new Moq.Mock<ISuggestionSource>(); sourceMock1.Setup(m => m.GetSuggestions(It.IsAny<ISemanticObject>())).Returns(new ISuggestionInstance[] { resultMock3.Object, resultMock2.Object }); this.kernel.Bind<ISuggestionSource>().ToMethod(s => sourceMock1.Object); this.kernel.Bind<ISuggestionSource>().ToMethod(s => sourceMock2.Object); // Run test var sut = this.kernel.Get<Suggester>(); var mockKeyword = this.kernel.GetMock<ISemanticObject>(); var result = sut.GetSuggestions(new ISemanticObject[] { mockKeyword.Object }); // verify CollectionAssert.AreEquivalent(result.Select(r => r.GetTextValue()).ToArray(), new string[] { resultMock2.Object.GetTextValue(), resultMock1.Object.GetTextValue(), resultMock3.Object.GetTextValue() }); sourceMock1.VerifyAll(); sourceMock2.VerifyAll(); }
public void Constructor_ShouldCreateATextboxForEachField() { var ServiceLocatorMock = new Mock <ISimpleServiceLocator>(); SimpleServiceLocator.SetServiceLocatorProvider(ServiceLocatorMock.Object); var headerTextBoxMock = new Mock <ITableHeaderTextBox>(); headerTextBoxMock.Setup(x => x.TextboxStyle.TextAlign).Returns("Right"); var headerTextBoxMockLeft = new Mock <ITableHeaderTextBox>(); headerTextBoxMockLeft.Setup(x => x.TextboxStyle.TextAlign).Returns(""); ServiceLocatorMock.Setup(x => x.Get <ITableHeaderTextBox> ("TableHeaderTextBoxRight", It.IsAny <Dictionary <string, object> >())).Returns(headerTextBoxMock.Object); ServiceLocatorMock.Setup(x => x.Get <ITableHeaderTextBox> ("TableHeaderTextBox", It.IsAny <Dictionary <string, object> >())).Returns(headerTextBoxMockLeft.Object); List <DataItem> fieldList = new List <DataItem> { new DataItem { Name = "Item1", Caption = "Cap1", DataType = "char" }, new DataItem { Name = "Item2", Caption = "Cap2", DataType = "int" } }; var mockRepository = new Moq.Mock <IDataTableRepository>(); mockRepository.Setup(x => x.GetByCode(It.IsAny <Guid>())).Returns(new DataTable { Name = "TestTable" }); //method under test TableHeader target = new TableHeader(fieldList, mockRepository.Object, new DataModel()); ServiceLocatorMock.Verify(x => x.Get <ITableHeaderTextBox> ("TableHeaderTextBox", It.IsAny <Dictionary <string, object> >()), Times.Once()); ServiceLocatorMock.Verify(x => x.Get <ITableHeaderTextBox> ("TableHeaderTextBoxRight", It.IsAny <Dictionary <string, object> >()), Times.Once()); Assert.IsTrue(target.TableHeaderTextBoxList.Count == 2); }
public async Task Get_shouldReturnBadRequestWhenPersonIdIsInvalid() { Customer customer = new Customer() { Cpf = "1", Name = "Ramires", State = "RJ" }; Moq.Mock <ICustomerService> mockCustomerService = new Moq.Mock <ICustomerService>(); mockCustomerService.Setup(customerService => customerService.GetAsync(It.IsAny <string>())).Returns(Task.FromResult(customer)); var customerController = new CustomersController(mockCustomerService.Object); var response = await customerController.GetById(customer.Cpf); Assert.IsType <BadRequestObjectResult>(response.Result); }
public void RestaurantReviewService_AddReview() { //arrange var review = new Review() { RatingScore = "1", ReviewDescription = "Delicious!", ReviewId = 1 }; var moq = new Moq.Mock <IRestaurantReviewService>(); object p = moq.Setup((a) => a.AddReview(review)).Returns(200); //act var controller = new RestaurantReviewsController(null, moq.Object); var result = controller.AddReview(review); //assert Assert.AreEqual(200, result); }
public void GetHashedValue_HandlesValidInput() { string pathToFile = @"C:\test-file.txt"; long filesize = 3L; string expectedResult = "80a751fde577028640c419000e33eba6"; var filesystemMock = new Moq.Mock <IFileSystem>(); FileHelpers sut = new FileHelpers(filesystemMock.Object); Stream mockStream = new MemoryStream(Encoding.UTF8.GetBytes("lorem ipsum")); filesystemMock.Setup(x => x.File.OpenRead(It.IsAny <string>())).Returns(mockStream); string result = sut.GetHashedValue(pathToFile, filesize); Assert.NotNull(result); Assert.AreEqual(expectedResult, result); }
public void RestaurantReviewService_AddRestaurant() { //arrange var restaurant = new Restaurant() { BusinessName = "Burgatory", PriceRatings = "2", RestaurantId = 2 }; var moq = new Moq.Mock <IRestaurantReviewService>(); object p = moq.Setup((a) => a.AddRestaurant(restaurant)).Returns(200); //act var controller = new RestaurantReviewsController(null, moq.Object); var result = controller.AddRestaurant(restaurant); //assert Assert.AreEqual(200, result); }
public void DOBUnitTest() { var mockRepo = new Moq.Mock <IRepository <Person> >(); mockRepo.Setup(aa => aa.AsQueryable()).Returns(PersonList().AsQueryable <Person>()); var controller = new RecordsController(mockRepo.Object); var result = controller.BirthDate(); Assert.That(result != null); Assert.That(CastIt(result) != null); Assert.That(CastIt(result).First().FirstName == "Lucille"); Assert.That(CastIt(result).Last().FirstName == "Lindsay Bluth"); }
public void GetExpenses_nullRepoObject_InternalServerError() { var fac = new Moq.Mock <ITransactionFactory>(); fac.Setup <DisplayExpensesTransaction>(m => m.CreateDisplayExpensesTransaction()) .Throws(new Exception("Server Exception")); var sut = new ExpensesController(fac.Object, _logger.Object); //act var actualResponse = sut.Get(); var contentResult = actualResponse as InternalServerErrorResult; //assert Assert.IsNotNull(contentResult, "Ok-500 status was not returned"); _logger.Verify(m => m.ErrorLog(Moq.It.IsAny <string>(), Moq.It.IsAny <Exception>()), Moq.Times.Exactly(1)); }
public void ReconciliationVendorsTest() { #region Data WBS_Deliverables wbs_deliverable = new WBS_Deliverables() { DeliverableId = 14000023, FullWBSNumber = "1147614.001.001", }; List <WBS_Deliverables> wbs_deliverables = new List <WBS_Deliverables>(); wbs_deliverables.Add(wbs_deliverable); wbs_deliverables.Add(new WBS_Deliverables { FullWBSNumber = "1147614.003.001", DeliverableId = 14000000, MasterVendorId = 1 }); wbs_deliverables.Add(new WBS_Deliverables { FullWBSNumber = "1147614.022.001", DeliverableId = 14000000, MasterVendorId = 2 }); wbs_deliverables.Add(new WBS_Deliverables { FullWBSNumber = "1147614.022.001", DeliverableId = 14000000, MasterVendorId = 3 }); #endregion #region Mock mockfinanceservice.Setup(x => x.ReconciliationVendors(It.IsAny <int>(), It.IsAny <string>())).Returns(wbs_deliverables); mockWBS_DeliverablesRepository.Setup(x => x.ReconciliationVendors(It.IsAny <int>(), It.IsAny <string>())).Returns(wbs_deliverables); //Finance Service Mock var financeservicemock = new FinanceServiceMock(_iWBS_DeliverablesRepository: mockWBS_DeliverablesRepository.Object); //Finance Controller Mock var FinanceController = new FinanceControllerMock(financeServicee: mockFinanceService.Object); #endregion #region service List <WBS_Deliverables> result = financeservicemock.ReconciliationVendors(wbs_deliverable.DeliverableId, wbs_deliverable.FullWBSNumber); #endregion #region Assertions mockWBS_DeliverablesRepository.Verify(); Assert.IsFalse(result == null); Assert.IsTrue(result.Count > 0); Assert.IsTrue(result.ElementAt(2).FullWBSNumber == "1147614.022.001"); Assert.IsTrue(result.ElementAt(2).DeliverableId == 14000000); Assert.IsTrue(result.ElementAt(2).MasterVendorId == 2); #endregion }
internal async Task TriggerEvents_ReturnsCurrentTrack() { var track = new Track() { Artist = "Artist", Title = "Title", TitleExtended = "Live", Playing = true, CurrentPosition = 10, Length = 230, }; var spotifyStatusMock = new Moq.Mock <ISpotifyStatus>(); spotifyStatusMock.Setup(x => x.CurrentTrack).Returns(track); spotifyStatusMock.Setup(x => x.GetTrack()).ReturnsAsync(track); var spotifyProcessMock = new Moq.Mock <ISpotifyProcess>(); spotifyProcessMock.Setup(x => x.GetSpotifyStatus()).ReturnsAsync(spotifyStatusMock.Object); var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object) { ListenForEvents = true }; var oldTrackStatus = track; oldTrackStatus.CurrentPosition = 9; spotifyHandler.Track = oldTrackStatus; int?eventTrackTime = null; spotifyHandler.OnTrackTimeChange += delegate(object sender, TrackTimeChangeEventArgs e) { eventTrackTime = e.TrackTime; Assert.Equal(track.CurrentPosition, eventTrackTime); }; await spotifyHandler.TriggerEvents(); spotifyProcessMock.Verify(n => n.GetSpotifyStatus(), Times.Once); spotifyHandler.Dispose(); }
public void Test_Rules_Are_Executed_From_Service() { ModelStateDictionary modelState = new ModelStateDictionary(); var MockRepos = new Mock <IRepository <TestEntity> >(); MockRepos.Setup(s => s.Add(It.IsAny <TestEntity>())); //MockRepos.Setup(s => // s.RunRules(It.IsAny<ServiceRuleFunc<bool>>() // , It.IsAny<ModelStateDictionary>() // , It.IsAny<object>())).Returns(true); var Mockedit = new Moq.Mock <TestDomainEdit>() { CallBase = true }; var MockRulesFactory = new Moq.Mock <IDomainRule>(); var _service = new Moq.Mock <TestServices <TestEntity> >( MockRepos.Object , Mockedit.Object , MockRulesFactory.Object ) { CallBase = true }; _service.Setup(s => s.RunRules(It.IsAny <ServiceRuleFunc <bool> >() , It.IsAny <ModelStateDictionary>() , It.IsAny <object>())).Returns(true); var tt = new TestEntity(); _service.Object.Add(tt); _service.Object.Verify(modelState); _service.Verify(mock => mock.RunRules(It.IsAny <ServiceRuleFunc <bool> >() , It.IsAny <ModelStateDictionary>() , It.IsAny <object>()), Times.Once, "Rules Didn't Run"); }
public void AdvancedSearchAds_SearchThroughWaterSportAds_CallSearchRepoOnWaterSportAds() { // Given Category cat = new Category { Id = 1, LabelUrlPart = "cat-url-label", Label = "Label", Type = AdTypeEnum.WaterSportAd }; AdvancedAdSearchModel model = new AdvancedAdSearchModel() { CategorySelectedId = 1, SearchString = "kite", SelectedWaterTypeId = 9 }; IList <SearchAdCache> searchResult = new List <SearchAdCache>(); searchResult.Add(new SearchAdCache { Title = "kite surf", City = new City() { Label = "the city" }, Category = cat }); var repoMock = new Moq.Mock <IRepository>(); repoMock.Setup(r => r.Get <Category>(cat.Id)).Returns(cat); var searchRepoMock = new Moq.Mock <ISearchRepository>(); searchRepoMock.Setup(r => r.AdvancedSearchAds <WaterSportAd>( It.Is <AdSearchParameters>(p => p.AndSearchStrings[0].Equals("kite") && p.WaterTypeId == 9))).Returns(searchResult); SearchServices service = new SearchServices(repoMock.Object, null, searchRepoMock.Object, null, null, null); // When AdSearchResultModel result = service.AdvancedSearchAds(model); // Then Assert.AreEqual(1, result.SearchResultTotalCount); }
public void GetHashedValueLimited_HandlesExceptions() { string pathToFile = @"C:\test-file.txt"; long filesize = 3L; long hashLimit = 1L; string expectedException = "surprise!"; var filesystemMock = new Moq.Mock <IFileSystem>(); FileHelpers sut = new FileHelpers(filesystemMock.Object); Stream mockStream = new MemoryStream(Encoding.UTF8.GetBytes(longText)); filesystemMock.Setup(x => x.FileStream.Create(It.IsAny <string>(), FileMode.Open)) .Throws(new Exception(expectedException)); string result = sut.GetHashedValue(pathToFile, filesize, hashLimit); Assert.IsEmpty(result); }
public void GetFileSize_ReturnsExpectedValue() { string pathToFile = @"C:\test-file.txt"; long expectedResult = 30679615L; var mockedFileInfo = new Mock <IFileInfo>(); mockedFileInfo.Setup(f => f.Length).Returns(31415926535L); var filesystemMock = new Moq.Mock <IFileSystem>(); FileHelpers sut = new FileHelpers(filesystemMock.Object); filesystemMock.Setup(x => x.FileInfo.FromFileName(It.IsAny <string>())) .Returns(mockedFileInfo.Object); long result = sut.GetFileSize(pathToFile); Assert.AreEqual(expectedResult, result); }
public void GetProduct_validId_returnProduct() { var reMoq = new Moq.Mock <IProductRepository>(); var cache = new Mock <IStoreCache>(); reMoq.Setup(r => r.GetById(It.IsAny <int>())).Returns((int id) => { return(new Product() { Id = id }); }); ProductService ps = new ProductService(reMoq.Object, cache.Object); var actual = ps.GetProduct(7); Assert.AreEqual(7, actual.Id); reMoq.Verify(r => r.GetById(It.IsAny <int>()), Times.Once); }
public async void CovidControllerGetTexasStats() { Mock <ICovidService> iCovidService = new Moq.Mock <ICovidService>(); iCovidService.Setup(s => s.GetTexasDailyStats()).Returns(Task.FromResult(new List <DailyStatus> { new DailyStatus { Positive = 12, DateChecked = DateTime.Now } })); CovidController covidController = new CovidController(iCovidService.Object); var stats = await covidController.GetTexasDailyStats(); Assert.NotNull(stats); }
public void ShouldThrowWhenRequired() { var request = new Mock <HttpRequestBase>(); request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { }); var httpContext = new Moq.Mock <HttpContextBase>(); httpContext.Setup(a => a.Request).Returns(request.Object); Assert.Throws(typeof(CompressR.Exceptions.CompressRException), () => { CompressR.MVC.CompressFactory.Compress(new System.Web.Mvc.ResultExecutedContext() { HttpContext = httpContext.Object }, true); }); }
public void Should_Receive_BeginScope() { var mockDisposable = new Mock <IDisposable>(); var logger = new Moq.Mock <ILogger>(); logger.Setup( tt => tt.BeginScope(It.IsAny <object>())).Returns(mockDisposable.Object); var sut = Sys.ActorOf(LoggingActor.CreateProps(logger.Object)); sut.Tell(new BeginScopeItem(LogLevel.Critical)); var result = ExpectMsg <IDisposable>(); result.ShouldBe(mockDisposable.Object); logger.Verify(tt => tt.BeginScope(It.IsAny <object>()), Times.AtLeastOnce); }
public async Task ValidateShipment_RuleSetStrict_Valid() { //Arrange var cartService = new Moq.Mock <ICartService>(); cartService.Setup(x => x.GetAvailableShippingMethodsAsync(It.IsAny <ShoppingCart>())).Returns(Task.FromResult(ShippingMethods)); var cart = GetValidCart(); //Act var validator = new CartShipmentValidator(cart, cartService.Object); var shipmentForValidation = cart.Shipments[0]; var result = await validator.ValidateAsync(shipmentForValidation, ruleSet : "strict"); //Assertion Assert.True(result.IsValid); Assert.Empty(result.Errors); Assert.Empty(shipmentForValidation.ValidationErrors); }
public void WhenCreateUser_ThenSuccess() { //Arrange User expected = this.CreateUser(); expected.Age = 30; Moq.Mock <IUserRepository> mockUserRepository = new Moq.Mock <IUserRepository>(); mockUserRepository.Setup(mock => mock.CreateUser(expected)).Returns(expected); UserService injectedClass = new UserService(mockUserRepository.Object); //Act User actual = injectedClass.CreateUser(expected); //Assert Assert.Equal(expected, actual); }
public async Task Post_shouldReturnBadRequestWhenPersonIdIsEmpty() { Bill bill = new Bill() { DueDate = DateTime.Now, Id = "anykey1", PersonId = String.Empty, Value = 22 }; Moq.Mock <IBillService> mockBillService = new Moq.Mock <IBillService>(); mockBillService.Setup(billService => billService.CreateAsync(It.IsAny <Bill>())).ReturnsAsync(bill); var billsController = new BillsController(mockBillService.Object); var response = await billsController.Create(bill.DueDate, bill.PersonId, bill.Value); Assert.IsType <BadRequestObjectResult>(response.Result); }
public void Test(MicrosoftLogLevel msLogLevel, Enyim.LogLevel enyimLevel, string message, Exception exception) { var mockLogger = new Moq.Mock <IMicrosoftLogger>(); var mockProvider = new Moq.Mock <IMicrosoftLoggerProvider>(); mockProvider.Setup(p => p.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object); LogManager.AssignFactory(new Enyim.Diagnostics.MicrosoftLoggerFactory(new LoggerFactory(new[] { mockProvider.Object }))); LogManager.Create(typeof(MicrosoftLoggingAdapterTests)).Log(enyimLevel, exception, message); // TODO capture state & formatter and validate the message mockLogger.Verify(sink => sink.Log( It.Is <MicrosoftLogLevel>(v => v == msLogLevel), It.IsAny <EventId>(), It.IsAny <object>(), It.Is <Exception>(v => v == exception), It.IsAny <Func <object, Exception, string> >())); }
public void GetHashedValue_RespectsLimitOption() { string pathToFile = @"C:\test-file.txt"; long filesize = 3L; long hashLimit = 1L; string expectedResult = "d20caec3b48a1eef164cb4ca81ba2587"; var filesystemMock = new Moq.Mock <IFileSystem>(); FileHelpers sut = new FileHelpers(filesystemMock.Object); Stream mockStream = new MemoryStream(Encoding.UTF8.GetBytes(longText)); filesystemMock.Setup(x => x.FileStream.Create(It.IsAny <string>(), FileMode.Open)).Returns(mockStream); string result = sut.GetHashedValue(pathToFile, filesize, hashLimit); Assert.NotNull(result); Assert.AreEqual(expectedResult, result); }
public async Task IncluirIndicacao_Indicacao_Success() { //Arrange var indicacao = new Indicacao() { CodigoAssociacao = 601, DataCriacao = DateTime.Parse("2016-10-30"), CpfAssociado = "123123", EmailAssociado = "alksjd", NomeAssociado = "Teste", TelefoneAssociado = "asd", PlacaVeiculoAssociado = "asd", NomeAmigo = "asd", TelefoneAmigo = "asd", EmailAmigo = "asd" }; var entradaIndicacao = new EntradaIndicacao() { Indicacao = indicacao, Remetente = "*****@*****.**", Copias = new string[0] }; var retornoIndicacaoExpected = new RetornoIndicacao() { Sucesso = "*****@*****.**", RetornoErro = new RetornoErro() { retornoErro = null } }; Moq.Mock <IHinovaAdapter> hinovaAdapterMoq = new Moq.Mock <IHinovaAdapter>(); hinovaAdapterMoq.Setup(x => x.IncluirIndicacao(It.IsAny <EntradaIndicacao>())).ReturnsAsync(retornoIndicacaoExpected); IIndicacaoService indicacaoService = new IndicacaoService(hinovaAdapterMoq.Object); //Act var result = await indicacaoService.IncluirIndicacao(entradaIndicacao); //Assert Assert.True(result.Equals(retornoIndicacaoExpected)); }
public void Setup() { var healthcheckbuildermock = new Moq.Mock <IHealthChecksBuilder>(); healthcheckbuildermock .Setup(m => m.Services) .Returns(new ServiceCollection()); healthChecksBuilder = healthcheckbuildermock.Object; httpendpointhealthcheck = new ServiceHealthCheck() { Name = "testhealthcheck", HealthCheckConditions = new HealthCheckConditions() { HttpBehaviour = new HttpBehaviour() { HttpExpectedCode = 200, HttpVerb = HttpVerb.Get }, }, AlertBehaviour = new List <AlertBehaviour>() { new AlertBehaviour() { AlertEvery = TimeSpan.FromSeconds(5), AlertOnServiceRecovered = true, TransportName = "Dummy", TransportMethod = AlertTransportMethod.Email } }, EndpointOrHost = "https://www.google.com", MonitoringInterval = TimeSpan.FromSeconds(1), ServiceType = ServiceType.Http, Alert = true }; alertTransportSettings = new DictionaryTransportSettings() { Name = "Dummy", }; alertPublisher = new DictionaryPublisher(healthChecksBuilder, httpendpointhealthcheck, alertTransportSettings); }
public void RequestHandlerRetriesTest() { //This statement will fail, then we will fake the syntax error as a ReadTimeout var statement = new SimpleStatement("SELECT WILL FAIL").SetRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); var request = Session.GetRequest(statement); //We will need a mock to fake the responses of Cassandra var mock = new Moq.Mock <RequestHandler <RowSet> >(Session, request, statement) { CallBase = true }; var requestHandler = mock.Object; //Expect Retry method to be called with a lower consistency level mock.Setup(r => r.Retry(It.Is <ConsistencyLevel?>(c => c == ConsistencyLevel.Two))).Verifiable(); //Fake a Error Result requestHandler.ResponseHandler(new ReadTimeoutException(ConsistencyLevel.Three, 2, 3, false), null); mock.Verify(); }
public async Task When_Filter_Does_Not_Match_Ignores_Block() { var nonMatchingFilter = new Moq.Mock <IBlockFilter>(); nonMatchingFilter.Setup(b => b.IsMatchAsync(_stubBlock)).ReturnsAsync(false); BlockFilters.Add(nonMatchingFilter.Object); //execute await BlockProcessor.ProcessBlockAsync(BlockNumber); //assert nonMatchingFilter.Verify(b => b.IsMatchAsync(_stubBlock), Times.Once); MockBlockHandler.Verify(b => b.HandleAsync(_stubBlock), Times.Never); MockTransactionProcessor .Verify(t => t.ProcessTransactionAsync( It.IsAny <Block>(), It.IsAny <Transaction>()), Times.Never); }
public void VolumeLabelShouldReturnDriveInfoVolumeLabel() { // Arrange var mockDriveInfo = new Moq.Mock <IDriveInfo>(); var label = "Hello"; mockDriveInfo.Setup(m => m.VolumeLabel).Returns(label); var driveInfo = mockDriveInfo.Object; var unitLetter = @"F:\"; var vcdMountPath = @"C:\tmp"; VirtualCloneDriveWrapper wrapper = new VirtualCloneDriveWrapper(unitLetter, vcdMountPath, 3, 1000, driveInfo, null, null); string volumeLabel; // Act volumeLabel = wrapper.VolumeLabel; // Assert Assert.AreEqual(label, volumeLabel); }
public void Test_FailedViewModelLocatorCollection() { var mockCollection = new Moq.Mock <IMvxViewModelLocatorCollection>(); mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny <MvxViewModelRequest>())) .Returns(() => null); Ioc.RegisterSingleton(mockCollection.Object); var parameters = new Dictionary <string, string> { { "foo", "bar" } }; var request = new MvxViewModelRequest <Test2ViewModel>(new MvxBundle(parameters), null, MvxRequestedBy.UserAction); var state = new MvxBundle(); var loader = new MvxViewModelLoader(); var viewModel = loader.LoadViewModel(request, state); Assert.Fail("We should never reach this line"); }
public void Should_Render_Evening_Message_View() { //Arrange //var fakeEveningDateTimeService = new FakeDateTimeClassForEvening(); var mock = new Moq.Mock <IDateTimeService>(); mock.Setup(s => s.GetCurrent()).Returns(new DateTime(2018, 02, 23, 17, 0, 0)); var greetController = new GreeterController(mock.Object); var dummyUserDetails = new UserDetails() { FirstName = "Dummy FN", LastName = "Dummy LN" }; //Act var result = greetController.Greet(dummyUserDetails); //Assert Assert.AreEqual("EveningMessage", result.ViewName); }
public async Task ShouldCreateNewUserInRepository() { var mock = new Moq.Mock <IUserRepository>(); mock.Setup(m => m.CreateUser(It.IsAny <string>())).ReturnsAsync("pass"); using (var testServer = new TestServerBuilder() .WithMock <IUserRepository>(typeof(IUserRepository), mock) .Build()) { var client = testServer.CreateClient(); var response = await client.PostAsync("/api/user/[email protected]", new StringContent("")); Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); var jsonString = await response.Content.ReadAsStringAsync(); var items = JsonConvert.DeserializeObject <UserCreatedResponse>(jsonString); Assert.Equal("pass", items.Password); } }