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 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 IncludesActualValuesFromVerifyNotVariableNames() { var expectedArg = "lorem,ipsum"; var mock = new Moq.Mock <IFoo>(); var mex = Assert.Throws <MockException>(() => mock.Verify(f => f.Execute(expectedArg.Substring(0, 5)))); Assert.Contains("f.Execute(\"lorem\")", mex.Message); }
public void DoesNotDisposeVaryHeaderStoreIfPassedToIt() { var mockcs = new Moq.Mock <ICacheStore>(); var mockvh = new Moq.Mock <IVaryHeaderStore>(MockBehavior.Strict); var handler = new CachingHandler(mockcs.Object, mockvh.Object); handler.Dispose(); mockvh.Verify(); }
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 }
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 ImportedAllBuilds_FromTheBeginning_SaveInBuildRepository() { ///Arrange var fakeProject = new Project { Name = "fakeProject", Id = 1 }; var fakeGatewayBuildsList = new List <Build> { new Build { BuildNumber = "1231", Name = "foo", CreatedAt = new DateTime(2015, 3, 8), Project = fakeProject }, new Build { BuildNumber = "1241", Name = "foa", CreatedAt = new DateTime(2015, 3, 7), Project = fakeProject } }; var fakeMetricList = new List <Metric> { new Metric { Code = "XPTO", Description = "For testing purposes", Id = 1, Weight = 5 }, new Metric { Code = "XPTA", Description = "For testing purposes", Id = 1, Weight = 5 }, }; var fakeBuildScoreDetailsList = new List <BuildScoreDetail> { new BuildScoreDetail { Id = 1, Score = 1 }, new BuildScoreDetail { Id = 2, Score = 2 } }; var loadHistorySince = new DateTime(2015, 1, 1); var buildRepositoryMoq = new Moq.Mock <IBuildRepository>(); var metricRepositoryMoq = new Moq.Mock <IMetricRepository>(); var projectRepositoryMoq = new Moq.Mock <IProjectRepository>(); var buildGatewayMoq = new Moq.Mock <IBuildGateway>(); var scoreServiceMoq = new Moq.Mock <IScoreService>(); buildRepositoryMoq.Setup(x => x.Add(It.IsAny <Build>())).Verifiable(); metricRepositoryMoq.Setup(x => x.GetAll()).Returns(fakeMetricList); projectRepositoryMoq.Setup(x => x.Find(It.IsAny <Expression <Func <Project, bool> > >(), null)).Returns(fakeProject); buildGatewayMoq.Setup(x => x.GetBuilds(It.IsAny <DateTime>())).Returns(fakeGatewayBuildsList); scoreServiceMoq.Setup(x => x.CalculateScoreDetail(It.IsAny <Build>(), It.IsAny <List <Metric> >())).Returns(fakeBuildScoreDetailsList); var importBuildServices = new ImportBuildServices(buildGatewayMoq.Object, buildRepositoryMoq.Object, scoreServiceMoq.Object, metricRepositoryMoq.Object, projectRepositoryMoq.Object, loadHistorySince); ///Act importBuildServices.ImportBuilds(); ///Assert buildRepositoryMoq.Verify(); }
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 AddTest_Spaces() { var fp = new Moq.Mock <IFileProvider>(); fp.Setup(aa => aa.AppendLineToFile(It.Is <string>(bb => bb == "Bob"))); var sut = new SpaceDelimitedDataRepository <Person>(fp.Object); sut.Insert(new Person() { FirstName = "Bob", LastName = "Loblaw", Gender = "male", FavoriteColor = "indigo", DateOfBirth = new DateTime(2016, 10, 22) }); fp.Verify(aa => aa.AppendLineToFile(It.IsAny <string>()), Times.Once); fp.Verify(aa => aa.AppendLineToFile(It.Is <string>(bb => bb == "\"Loblaw\" \"Bob\" \"male\" \"indigo\" \"10/22/2016\""))); }
public void IncludesActualValuesFromSetups() { var expectedArg = "lorem,ipsum"; var mock = new Moq.Mock <IFoo>(); mock.Setup(f => f.Save(expectedArg.Substring(0, 5))); var mex = Assert.Throws <MockException>(() => mock.Verify(foo => foo.Save("never"))); Assert.Contains("f.Save(\"lorem\")", mex.Message); }
public void Verify(Expression <Action <IBaseMessageContext> > expression, Times times, string failMessage) { // intercept and rewrite IBaseMessage Verify calls against IBaseMessageContext var methodCallExpression = expression.Body as MethodCallExpression; if (methodCallExpression != null && methodCallExpression.Method.DeclaringType.IsTypeOf(typeof(BaseMessageContext))) { // rewrite expression to let base Moq class handle It.Is<> and It.IsAny<> expressions should there be any var rewrittenExpression = RewriteExpression(methodCallExpression); //var mock = Get(Object); //mock.Verify(rewrittenExpression, times, failMessage); BaseMock.Verify(rewrittenExpression, times, failMessage); } else { // let base Moq class handle all other Verify calls //Verify((Expression<Action<TMock>>)(Expression)expression, times, failMessage); BaseMock.Verify((Expression <Action <TMock> >)(Expression) expression, times, failMessage); } }
public void EventAggregatorSimpleTest() { var eventAggregator = new EventAggregator.Simple.EventAggregator(); var mockSubscriberAlpha = new Moq.Mock <ISubscriberAlpha>(); var mockSubscriberBeta = new Moq.Mock <ISubscriberBeta>(); var subscriberAlpha = mockSubscriberAlpha.Object; var subscriberBeta = mockSubscriberBeta.Object; eventAggregator.Subscribe <UserLoggedInMessage>(subscriberAlpha, subscriberAlpha.Invoke); eventAggregator.Subscribe <UserLoggedInMessage>(subscriberBeta, subscriberBeta.InvokeBetaHandler); eventAggregator.Subscribe <UserLoggedOutMessage>(subscriberAlpha, subscriberAlpha.Invoke); eventAggregator.Subscribe <UserLoggedOutMessage>(subscriberBeta, subscriberBeta.InvokeBetaHandler); Assert.AreEqual(2, eventAggregator.SubscriptionCount <UserLoggedInMessage>()); Assert.AreEqual(2, eventAggregator.SubscriptionCount <UserLoggedOutMessage>()); var loggedInMessage = new UserLoggedInMessage("Tom", this); eventAggregator.Publish(loggedInMessage); mockSubscriberAlpha.Verify(x => x.Invoke(loggedInMessage), Times.Once); mockSubscriberBeta.Verify(x => x.InvokeBetaHandler(loggedInMessage), Times.Once); mockSubscriberAlpha.Invocations.Clear(); mockSubscriberBeta.Invocations.Clear(); eventAggregator.Unsubscribe <UserLoggedInMessage>(subscriberAlpha); Assert.AreEqual(1, eventAggregator.SubscriptionCount <UserLoggedInMessage>()); Assert.AreEqual(2, eventAggregator.SubscriptionCount <UserLoggedOutMessage>()); eventAggregator.Publish(loggedInMessage); mockSubscriberAlpha.Verify(x => x.Invoke(loggedInMessage), Times.Never); mockSubscriberBeta.Verify(x => x.InvokeBetaHandler(loggedInMessage), Times.Once); eventAggregator.Unsubscribe(subscriberAlpha); eventAggregator.Unsubscribe(subscriberBeta); Assert.AreEqual(0, eventAggregator.SubscriptionCount <UserLoggedInMessage>()); Assert.AreEqual(0, eventAggregator.SubscriptionCount <UserLoggedOutMessage>()); }
public async Task GetLocationByIp_Null_Test() { var clientMoq = new Moq.Mock <IInMemoryGeoDataBase>(); var ipToSearch = "12"; clientMoq.Setup(p => p.SearchFirstItemByValue <IPRange>(ipToSearch)).Returns(Task.FromResult <IPRange>(null)); var query = new GeoDataBaseQuery(clientMoq.Object); var res = await query.GetLocationByIp(ipToSearch); Assert.IsNull(res); clientMoq.Verify(p => p.SearchFirstItemByValue <IPRange>(ipToSearch), Times.Once); }
public void ReadTransactionsFromFile_Valid_ObserverNeverCalled() { var mockObserver = new Moq.Mock<Observer>(); List<Observer> ol = new List<Observer>(); ol.Add(mockObserver.Object); List<Product> listOfProducts = new List<Product>(); TransactionManager tm = new TransactionManager(ol, listOfProducts); tm.ReadTransactionsFromFile(new StreamReader(@"C:\Users\vbhujan\Documents\Cart.txt")); mockObserver.Verify(o => o.update(), Times.Never); }
public void ExecuteTest() { // mock task manager var mockTaskManager = new Moq.Mock <ITaskManager>(); mockTaskManager.Setup(manager => manager.RequestTasks()).Returns("xml"); var target = new RequestTask(); target.TaskManager = mockTaskManager.Object; target.Execute(); mockTaskManager.Verify(manager => manager.ParseTasks("xml"), Times.Once); }
public void TestConfigureLogic() { var reducer = new ReducerComposer <AppState>(); var loginActionLogicMock = new Moq.Mock <ILogic <AppState, LoginAction> >(); loginActionLogicMock.Setup(x => x.IsLongRunning).Returns(false); loginActionLogicMock.Setup(x => x.Priority).Returns(1); var loginResult = new PreProcessResult(true, new LoginAction("", "", true)); loginActionLogicMock.Setup(x => x.PreProcess(It.IsAny <IStore <AppState> >(), It.IsAny <LoginAction>())).ReturnsAsync(loginResult); loginActionLogicMock.Setup(x => x.Process(It.IsAny <Func <AppState> >(), It.IsAny <LoginAction>(), It.IsAny <IMultiDispatcher>())); IStore <AppState> store = new Store <AppState>(reducer, AppState.InitialState).ConfigureLogic(config => { config.AddLogics(loginActionLogicMock.Object); }); store.Dispatch(new LoginAction("Bob", "pwd", true)); loginActionLogicMock.Verify(x => x.PreProcess(It.IsAny <IStore <AppState> >(), It.IsAny <LoginAction>()), Times.Once()); loginActionLogicMock.Verify(x => x.Process(It.IsAny <Func <AppState> >(), It.IsAny <LoginAction>(), It.IsAny <IMultiDispatcher>()), Times.Once()); }
public async Task TestSaveCallsDbService() { var db = new Moq.Mock <IOrdersService>(); var ordersController = new OrdersController(db.Object); var order = new Order() { OrderId = Guid.NewGuid() }; await ordersController.PlaceOrder(order); db.Verify(foo => foo.SaveOrder(order)); }
public void TestValidationSuccess() { LogicImpl logic = new LogicImpl(); Moq.Mock <IStore <AppState> > store = new Moq.Mock <IStore <AppState> >(); store.Setup(s => s.Dispatch(It.IsAny <ValidationException>())); logic.OnValidation = (s, a, d) => Task.FromResult(ValidationResult.Success()); var result = ((ILogic <AppState, string>)logic).PreProcess(store.Object, "Hello"); Assert.AreEqual(true, result.Result.ContinueToNextStep); store.Verify(s => s.Dispatch(It.IsAny <ValidationException>()), Times.Never()); }
public void ActivateAd_AdDoesNotExist_ReturnModelIsActivatedFalse() { // Given BaseAd ad = null; var repoMock = new Moq.Mock <IRepository>(); repoMock.Setup(x => x.Get <BaseAd>(78)).Returns(ad); AdActivationServices service = new AdActivationServices(repoMock.Object, null, null, null); // When AdActivationResultModel model = service.ActivateAd(78, null); // Then Assert.IsFalse(model.IsActivated); Assert.AreEqual(78, model.AdId); Assert.AreEqual("Cette annonce n'existe pas ou a expiré.", 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 Test(Serilog.Events.LogEventLevel serilogLevel, Enyim.LogLevel enyimLevel, string message, Exception exception) { var mock = new Moq.Mock <ILogEventSink>(); var root = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Sink(mock.Object) .CreateLogger(); Enyim.LogManager.AssignFactory(new Enyim.Diagnostics.SerilogLoggerFactory(root)); LogManager.Create(typeof(SerilogLoggerAdapterTests)).Log(enyimLevel, exception, message); mock.Verify(sink => sink.Emit(It.Is <LogEvent>(e => e.Level == serilogLevel && e.MessageTemplate.Text == message && e.Exception == exception))); }
public void Test_EmployeeInOfficeGetsNotified() { // // Create mocks: // var loggerMock = new Moq.Mock <ILogger>(); var bobMock = new Moq.Mock <IEmployee>(); bobMock.Setup(x => x.IsWorkingOnDate(It.IsAny <DateTime>())) .Returns(true); bobMock.Setup(x => x.GetNotificationPreference()) .Returns(LunchNotifier.NotificationType.Email); var employeeServiceMock = new Moq.Mock <IEmployeeService>(); employeeServiceMock.Setup(x => x.GetEmployeesInNewYorkOffice()) .Returns(new[] { bobMock.Object }); var notificationServiceMock = new Moq.Mock <INotificationService>(); notificationServiceMock.Setup(x => x.SendEmail(bobMock.Object, It.IsAny <string>())); // // Create instance of class I'm testing: // var classUnderTest = new LunchNotifier(notificationServiceMock.Object, employeeServiceMock.Object, loggerMock.Object); // // Run some logic to test: // classUnderTest.SendLunchtimeNotifications(); // // Check the results: // notificationServiceMock.Verify(x => x.SendEmail(bobMock.Object, It.IsAny <string>()), Times.Once); notificationServiceMock.Verify(x => x.SendSlackMessage(bobMock.Object, It.IsAny <string>()), Times.Never); }
public async Task GetLocationTest() { var locationsList = new List <LocationModel>() { new LocationModel() { City = "1", Latitude = 1, Longitude = 1.2344f }, new LocationModel() { City = "2", Latitude = 2, Longitude = 2.2344f } }; var ip = "123.123.123.123"; queryMoq.Setup(p => p.GetLocationByIp(ip)).Returns(Task.FromResult(locationsList[0])); var controller = new IpController(queryMoq.Object); var res = await controller.GetLocationByIp(ip); queryMoq.Verify(p => p.GetLocationByIp(ip), Times.Once); Assert.AreEqual(locationsList[0], (res as OkObjectResult).Value);; }
public void TestValidationFailure() { LogicImpl logic = new LogicImpl(); Moq.Mock <IStore <AppState> > store = new Moq.Mock <IStore <AppState> >(); store.Setup(s => s.Dispatch(It.IsAny <ValidationException>())); logic.OnValidation = (s, a, d) => Task.FromResult(ValidationResult.Failure(new ValidationException("", new[] { new ValidationDetails("", "") }))); var result = ((ILogic <AppState, string>)logic).PreProcess(store.Object, "Hello"); Assert.AreEqual(false, result.Result.ContinueToNextStep); store.Verify(s => s.Dispatch(It.IsAny <ValidationException>()), Times.Once()); }
public void SafeDisposal() { var exceptionHandler = new Moq.Mock<IExceptionHandler>(MockBehavior.Strict); exceptionHandler.Setup(x => x.Warn(It.IsAny<Exception>())).Returns<Exception>(x => x).Verifiable(); ExceptionHandler.Initialise(exceptionHandler.Object); var t = new ThrowingDisposableObject(); t.Dispose(); Assert.That(t.DisposeUnmanagedResourcesCount, Is.EqualTo(1)); Assert.That(t.DisposeManagedResourcesCount, Is.EqualTo(1)); exceptionHandler.Verify(x => x.Warn(It.IsAny<Exception>()), Times.Once()); }
public void AggregateBus_ShouldSubscribeWhenConfigured() { 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>(); //aggregateCache.Setup(x => x.Clear(Moq.It.IsAny<Guid>(), Moq.It.IsAny<Type>())).Verifiable(); AggregateBus.Instance.Configure(eventBus.Object, aggregateCache.Object); AggregateBus.Instance.RegisteredAggregateCaches.Should().NotBeNull(); AggregateBus.Instance.RegisteredAggregateCaches.Contains(aggregateCache.Object).Should().BeTrue(); eventBus.Verify(e => e.Subscribe<AggregateCacheCleared>(Moq.It.IsAny<Func<AggregateCacheCleared, Task>>()), Moq.Times.Once); }
public void Should_print_statement() { var consoleMoq = new Moq.Mock <IConsole>(); var clockMoq = new Mock <IClock>(); clockMoq.SetupSequence(clock => clock.TodayToString()) .Returns("10/01/2012") .Returns("13/01/2012") .Returns("14/01/2012"); var repository = new TransactionRepository(clockMoq.Object); var statement = new StatementPrinter(consoleMoq.Object); var account = new Account(repository, statement); account.Deposit(1000); account.Deposit(2000); account.Withdraw(500); account.PrintStatement(); consoleMoq.Verify(console => console.print("date || credit || debit || balance")); consoleMoq.Verify(console => console.print("14/01/2012 || || 500.00 || 2,500.00")); consoleMoq.Verify(console => console.print("13/01/2012 || 2,000.00 || || 3,000.00")); consoleMoq.Verify(console => console.print("10/01/2012 || 1,000.00 || || 1,000.00")); }
public void PayInstallment() { //arrange the MockObject var logMock = new Moq.Mock <ILogger>(); //arrange the SUT var client = new ClientDummy(); var credit_card = new AccountForLogSpy(500, client, logMock.Object); credit_card.Grant(1000); credit_card.WithdrawFromCreditCard(200); //act credit_card.PayInstallment(); //assert Assert.AreEqual(826F, credit_card.CreditBalance); //mock object verify logMock.Verify(_ => _.Log("method Log was called with message: Raw Installment = 26"), Times.Exactly(3)); logMock.Verify(_ => _.Log("method Log was called with message: Full Installment = 26.78"), Times.Exactly(2)); logMock.Verify(_ => _.Log("method Log was called with message: credit balance after payment = 826"), Times.Once); }
public void CreateContact_ImplementsIRepository() { var repoMock = new Moq.Mock <IContactStateRepository>(); var sut = new ContactService(repoMock.Object, new DateTimeProvider()); var stateMock = new Mock <IContactState>(); repoMock.Setup(t => t.CreateContactState(It.IsAny <Guid>(), It.IsAny <string>())).Returns(stateMock.Object); var guid = Guid.NewGuid(); var name = "New Contact"; sut.CreateContact(guid, name); repoMock.Verify(s => s.CreateContactState(guid, name), Times.Once); }
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); 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(); }
//[Test] public void rules_are_executed_with_not_vaild_rules() { ModelStateDictionary modelState = new ModelStateDictionary(); var _edit = new Moq.Mock <SubCategoryEdits>(_Context.Object); var x_scRepos = new Mock <EfRepository <SubCategory> >(_Context.Object) { CallBase = true }; x_scRepos.Setup(s => s.Add(It.IsAny <SubCategory>())); x_scRepos.Setup(s => s.ModifiedEntities).Returns(It.IsAny <EntityRules>()); //x_scRepos.Setup(s => // s.RunRules(It.IsAny<ServiceRuleFunc<bool>>(), It.IsAny<ModelStateDictionary>(), It.IsAny<object>())).Returns(true); var subCategoryEntity = new TestSubCategory { Id = 1 , SubCategoryName = new DomainEntityTypeString { Value = "Default" } }; subCategoryEntity.SubCategoryName.Value = "dd"; var _service = new Moq.Mock <SubCategoriesService>(); var testRulesFactory = new TestRulesFactory(); _service = new Moq.Mock <SubCategoriesService>(x_scRepos.Object , _edit.Object, testRulesFactory) { CallBase = true }; _service.Object.Add(subCategoryEntity); _service.Object.Verify(modelState); //SetEntitiesDefaults(It.IsAny<SubCategory>() _service.Verify(mock => _service.Object.RunRules(It.IsAny <ServiceRuleFunc <bool> >(), It.IsAny <ModelStateDictionary>(), It.IsAny <object>()), Times.Once); // SubCategoryRules // MockSubCategoryEdits.Verify(mock => mock.SetEntitiesDefaults(It.IsAny<SubCategory>()), Times.Once); // Assert.IsTrue(modelState.Count == 1, "Model Validation Rule didn't Failed."); }
public async Task Add_new_task() { // arrange var newTask = new TodoItem() { Completed = false, Title = "Test 3" }; var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.AddAsync(newTask)).ReturnsAsync(newTask); var controller = new TodoController(serviceMock.Object); // act var result = await controller.AddTodo(newTask); // assert serviceMock.Verify(x => x.AddAsync(newTask), Times.Once); Assert.NotNull(result); Assert.Equal(newTask, result); }
public void Should_Receive_IsEnabled() { var logger = new Moq.Mock <ILogger>(); logger.Setup( tt => tt.IsEnabled(It.IsAny <LogLevel>())).Returns(true); var sut = Sys.ActorOf(LoggingActor.CreateProps(logger.Object)); sut.Tell(new LogEnabledItem(LogLevel.Critical)); var result = ExpectMsg <bool>(); result.ShouldBeTrue(); logger.Verify(tt => tt.IsEnabled(It.IsAny <LogLevel>()), Times.AtLeastOnce); }
public async Task Delete_task() { // arrange var taskId = 1; var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.DeleteAsync(taskId)).ReturnsAsync(true); var controller = new TodoController(serviceMock.Object); // act var result = await controller.DeleteTodo(taskId); // assert serviceMock.Verify(x => x.DeleteAsync(taskId), Times.Once); Assert.NotNull(result); Assert.Equal(HttpStatusCode.OK, result.StatusCode); }
public async Task Status_not_found_when_deleting_task_that_does_not_exist() { // arrange var taskId = 1; var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.DeleteAsync(taskId)).ReturnsAsync(false); var controller = new TodoController(serviceMock.Object); // act var result = await controller.DeleteTodo(taskId); // assert serviceMock.Verify(x => x.DeleteAsync(taskId), Times.Once); Assert.NotNull(result); Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); }
public void TestMethod1() { var mockRepo = new Moq.Mock <ITaskRepository>(); var mockEmail = new Moq.Mock <IEmailService>(); mockRepo.Setup(repo => repo.DeleteTask(It.IsAny <int>())).Returns(new Task()); mockEmail.Setup(client => client.Send(It.IsAny <string>())).Verifiable(); var Controller = new TaskController(mockRepo.Object, mockEmail.Object); Controller.DeleteTasks(323); mockRepo.Verify(repo => repo.DeleteTask(323), Times.Once); mockEmail.Verify(email => email.Send(It.IsAny <string>()), Times.Once); }
public async Task Change_completeness_of_task() { // arrange var existingTask = new TodoItem() { Id = 2, Completed = true, Title = "Test 1" }; var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.UpdateAsync(existingTask.Id, existingTask)).ReturnsAsync(existingTask); var controller = new TodoController(serviceMock.Object); // act var result = await controller.UpdateTodo(existingTask.Id, existingTask); // assert serviceMock.Verify(x => x.UpdateAsync(existingTask.Id, existingTask), Times.Once); Assert.NotNull(result); Assert.Equal(existingTask, result); }
public void given_automapped_model_and_mapped_actions_then_apply() { var mappedItem = new Moq.Mock <IMapperAddItem>(); mapperAddItems.Add(mappedItem.Object); svc = new Moq.Mock <YuzuDefinitionTemplates>(MockBehavior.Loose, mapper.Object, config.Object, mapperAddItems.ToArray(), typeFactoryRunner.Object) { CallBase = true }; StubRenderMethod(); svc.Object.Render <vmPage_ExampleViewModel>(exampleModel, false, settings, null, inputMappingItems); mappedItem.Verify(x => x.Add(inputMappingItems)); }
public async Task GetStatusUsesIStatusReader() { var logger = new Moq.Mock <ILogger <StatusController> >().Object; var mapper = new Moq.Mock <IMapper>().Object; var statusReaderMock = new Moq.Mock <IStatusReader>(); statusReaderMock.Setup(x => x.GetStatus()).Returns(Task.FromResult(new Monitoring() { Status = Status.warning })).Verifiable(); var controller = new StatusController(statusReaderMock.Object, logger, mapper); var result = (Monitoring)(await controller.GetMonitoring() as OkObjectResult).Value; statusReaderMock.Verify(x => x.GetStatus(), Times.Once()); }
public void ShouldSendGCodeToJogToSecondExpectedFiducialLocation() { SetupFiducials(5, 5, 35, 35); HasPointStabilized = true; MachineLocation = new Point2D <double>(10, 10); StabilizedPoint = new Point2D <double>(0.5, 0.5); _boardAlignmentManager.State = BoardAlignmentManagerStates.StabilzingAfterFirstFiducialMove; _machine.Setup(mac => mac.SendCommand(It.IsAny <string>())); CircleCaptured(new Point2D <double>(5, 5)); var secondFiducialX = MachineLocation.X + (_pcbManager.Object.SecondFiducial.X - _pcbManager.Object.FirstFiducial.X); var secondFiducialY = MachineLocation.Y + (_pcbManager.Object.SecondFiducial.Y - _pcbManager.Object.FirstFiducial.Y); _machine.Verify(mac => mac.SendCommand($"G0 X{secondFiducialX.ToDim()} Y{secondFiducialY.ToDim()}"), Moq.Times.Once); }
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 Can_use_Dsl_to_increment_build_argument() { // arrange var buildUri = new Uri("vstfs:///Build/Build/123"); var buildDefUri = new Uri("vstfs:///Build/Build/XYZ"); var emailProvider = new Moq.Mock <IEmailProvider>(); var build = new Moq.Mock <IBuildDetail>(); build.Setup(b => b.Uri).Returns(buildUri); build.Setup(b => b.Quality).Returns("Released"); build.Setup(b => b.BuildDefinitionUri).Returns(buildDefUri); build.Setup(b => b.BuildDefinition.Name).Returns("Build Def"); var tfsProvider = new Moq.Mock <ITfsProvider>(); tfsProvider.Setup(t => t.GetBuildDetails(It.IsAny <Uri>())).Returns(build.Object); tfsProvider.Setup(t => t.GetBuildArgument(It.IsAny <Uri>(), "MajorVersion")).Returns(1); tfsProvider.Setup(t => t.GetBuildArgument(It.IsAny <Uri>(), "MinorVersion")).Returns(6); tfsProvider.Setup(t => t.GetBuildArgument(It.IsAny <Uri>(), "MinorVersion")).Returns(7); // used for the second call tfsProvider.Setup(t => t.GetBuildArgument(It.IsAny <Uri>(), "VersionStartDate")).Returns("1 Jan 2012"); var engine = new TFSEventsProcessor.Dsl.DslProcessor(); var args = new Dictionary <string, object> { { "Arguments", new[] { "BuildEvent", "vstfs:///Build/Build/123" } }, }; // act engine.RunScript(@"dsl\tfs\incrementbuildargument.py", args, tfsProvider.Object, emailProvider.Object); // assert emailProvider.Verify( e => e.SendEmailAlert( "richard@typhoontfs", "Build Def version incremented", "'Build Def' version incremented to 1.7.[days since 1 Jan 2012].[build count] as last build quality set to 'Released'")); }
public void Status_not_found_when_changing_task_that_does_not_exist() { // arrange var taskId = 4; var existingTask = new TodoItem() { Id = 2, Completed = false, Title = "Test 3" }; var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.UpdateAsync(taskId, existingTask)).ReturnsAsync(null); var controller = new TodoController(serviceMock.Object); // act var exc = Assert.Throws<AggregateException>(() => controller.UpdateTodo(taskId, existingTask).Result); var result = exc.InnerExceptions.Cast<HttpResponseException>().FirstOrDefault(); // assert serviceMock.Verify(x => x.UpdateAsync(taskId, existingTask), Times.Once); Assert.NotNull(result); Assert.Equal(HttpStatusCode.NotFound, result.Response.StatusCode); }
public void shouldReportBackContactFetchProgress() { var avegaClientRepositoryMock = new Moq.Mock<IAvegaClientRepository>(); avegaClientRepositoryMock.Setup(x => x.GetAll()) .Returns(new List<AvegaContact>(new[] { new AvegaContact("DisplayName"), new AvegaContact("DisplayName") })); var avegaClientRepository = avegaClientRepositoryMock.Object; avegaClientRepository.ContactDataFetched += (sender, ev) => { Console.WriteLine(ev.TotalContacts); Console.WriteLine(ev.CurrentContactIndex); switch (ev.DataFetched) { case DataFetchedType.Image: break; case DataFetchedType.ContactInformation: break; } }; avegaClientRepository.GetAll(); avegaClientRepositoryMock.Verify(); }
public void WritesCorrectly() { // arrange var converter = new BoolConverter(); var writer1 = new Moq.Mock<JsonWriter>(); writer1.Setup(x => x.WriteValue("0")).Verifiable(); var writer2 = new Moq.Mock<JsonWriter>(); writer2.Setup(x => x.WriteValue("1")).Verifiable(); var writer3 = new Moq.Mock<JsonWriter>(); // act converter.WriteJson(writer1.Object, false, null); converter.WriteJson(writer2.Object, true, null); converter.WriteJson(writer3.Object, null, null); // assert writer1.Verify(); writer2.Verify(); writer3.Verify(x => x.WriteValue(It.IsAny<string>()), Times.Never()); }
public async Task Get_all_tasks() { // arrange var list = new List<TodoItem> { new TodoItem() { Id = 1, Completed = false, Title = "Test 1" }, new TodoItem() { Id = 2, Completed = true, Title = "Test 2" } }; var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list); var controller = new TodoController(serviceMock.Object); // act var result = await controller.GetAll(); // assert serviceMock.Verify(x => x.GetAllAsync(), Times.Once); Assert.NotEmpty(result); Assert.Equal(2, result.Count); Assert.Equal(list, result); }
public void WritesCorrectly() { // arrange var converter = new EnumConverter(); var writer1 = new Moq.Mock<JsonWriter>(); writer1.Setup(x => x.WriteValue(0)).Verifiable(); var writer2 = new Moq.Mock<JsonWriter>(); writer2.Setup(x => x.WriteValue(1)).Verifiable(); var writer3 = new Moq.Mock<JsonWriter>(); // act converter.WriteJson(writer1.Object, System.ConsoleColor.Black, null); converter.WriteJson(writer2.Object, System.ConsoleColor.DarkBlue, null); converter.WriteJson(writer3.Object, null, null); // assert writer1.Verify(); writer2.Verify(); writer3.Verify(x => x.WriteValue(It.IsAny<int>()), Times.Never()); }
public async Task Clear_all_completed_tasks() { // arrange var list = new List<TodoItem> { new TodoItem() { Id = 1, Completed = false, Title = "Test 1" }, new TodoItem() { Id = 2, Completed = true, Title = "Test 2" } }; var notCompleted = list.Where(x => x.Completed == false).ToList(); var serviceMock = new Moq.Mock<ITodoService>(); serviceMock.Setup(x => x.ClearCompleted()).ReturnsAsync(notCompleted); var controller = new TodoController(serviceMock.Object); // act var result = await controller.ClearCompleted(); // assert serviceMock.Verify(x => x.ClearCompleted(), Times.Once); Assert.NotEmpty(result); Assert.Equal(1, result.Count); Assert.Equal(notCompleted, result); }
public void ActivateAd_AdDoesNotExist_ReturnModelIsActivatedFalse() { // Given BaseAd ad = null; var repoMock = new Moq.Mock<IRepository>(); repoMock.Setup(x => x.Get<BaseAd>(78)).Returns(ad); AdActivationServices service = new AdActivationServices(repoMock.Object, null, null, null); // When AdActivationResultModel model = service.ActivateAd(78, null); // Then Assert.IsFalse(model.IsActivated); Assert.AreEqual(78, model.AdId); Assert.AreEqual("Cette annonce n'existe pas ou a expiré.", 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 ActivateAd_AdIsAlreadyActivated_ReturnModelIsActivatedTrue() { // Given BaseAd ad = new Ad() { IsActivated = true }; 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, null); // Then Assert.IsTrue(model.IsActivated); Assert.AreEqual(78, model.AdId); Assert.AreEqual("Cette annonce a déjà été activée.", 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 ProcessLimitsTest( string configurationName, SLimits limits, bool logStatistic, int apiUsageThreshold, int dataStorageThreshold, Times[] result) { var mockedApiDailyRequestsLoger = new Moq.Mock<ILimitLoger>(); if (limits != null) { var apiDailyRequestsLoger = new ApiDailyRequestsLoger(configurationName, limits.DailyApiRequests); mockedApiDailyRequestsLoger.SetupGet(p => p.UsedAmount).Returns(apiDailyRequestsLoger.UsedAmount); mockedApiDailyRequestsLoger.SetupGet(p => p.UsedPercents).Returns(apiDailyRequestsLoger.UsedPercents); } mockedApiDailyRequestsLoger.Setup(m => m.LogPointWarning()).Verifiable(); mockedApiDailyRequestsLoger.Setup(m => m.LogHasReachedError()).Verifiable(); var mockedDataStorageLoger = new Moq.Mock<ILimitLoger>(); if (limits != null) { var dataStorageLoger = new ApiDailyRequestsLoger(configurationName, limits.DataStorageMb); mockedDataStorageLoger.SetupGet(p => p.UsedAmount).Returns(dataStorageLoger.UsedAmount); mockedDataStorageLoger.SetupGet(p => p.UsedPercents).Returns(dataStorageLoger.UsedPercents); } mockedDataStorageLoger.Setup(m => m.LogPointWarning()).Verifiable(); mockedDataStorageLoger.Setup(m => m.LogHasReachedError()).Verifiable(); var mockedLoger = new Moq.Mock<ILimitsLoger>(); mockedLoger.SetupGet(p => p.ApiDailyRequestsLoger).Returns(mockedApiDailyRequestsLoger.Object); mockedLoger.SetupGet(p => p.DataStorageLoger).Returns(mockedDataStorageLoger.Object); mockedLoger.Setup(m => m.LogStatisticInfo()).Verifiable(); mockedLoger.Setup(m => m.LogInformationAreNotAvailableWarning()).Verifiable(); var agent = new LimitsAgent(); agent.LogStatistic = logStatistic; agent.ApiUsageThreshold = apiUsageThreshold; agent.DataStorageThreshold = dataStorageThreshold; var logerField = typeof(LimitsAgent).GetField("loger", BindingFlags.Instance | BindingFlags.NonPublic); if (logerField != null) { logerField.SetValue(agent, mockedLoger.Object); } agent.ProcessLimits(limits); mockedLoger.Verify(m => m.LogStatisticInfo(), result[0]); mockedLoger.Verify(m => m.LogInformationAreNotAvailableWarning(), result[1]); mockedApiDailyRequestsLoger.Verify(m => m.LogPointWarning(), result[2]); mockedApiDailyRequestsLoger.Verify(m => m.LogHasReachedError(), result[3]); mockedDataStorageLoger.Verify(m => m.LogPointWarning(), result[4]); mockedDataStorageLoger.Verify(m => m.LogHasReachedError(), result[5]); }
public void IncludesActualCallsWithExplicitArraysInFailureMessage() { var mock = new Moq.Mock<IFoo>(); mock.Object.ParamsArray("first", "a", new Object(), null, new object[] { "e", "f" }, "d"); mock.Object.Array("first", new object[] { "a", new Object(), null, new object[] { "e", "f" }, "d" }); mock.Object.ParamsArray("first"); mock.Object.Array("first", null); var mex = Assert.Throws<MockException>(() => mock.Verify(f => f.Execute("pong"))); Assert.Contains( Environment.NewLine + "Performed invocations:" + Environment.NewLine + "IFoo.ParamsArray(\"first\", \"a\", System.Object, null, [ \"e\", \"f\" ], \"d\")" + Environment.NewLine + "IFoo.Array(\"first\", [ \"a\", System.Object, null, [ \"e\", \"f\" ], \"d\" ])" + Environment.NewLine + "IFoo.ParamsArray(\"first\")" + Environment.NewLine + "IFoo.Array(\"first\", null)", mex.Message); }
public void IncludesMessageAboutNoActualCallsInFailureMessage() { var mock = new Moq.Mock<IFoo>(); MockException mex = AssertHelper.Throws<MockException>(() => mock.Verify(f => f.Execute("pong"))); AssertHelper.Contains(Environment.NewLine + "No invocations performed.", mex.Message); }
public void IncludesActualCallsInFailureMessage() { var mock = new Moq.Mock<IFoo>(); mock.Object.Execute("ping"); mock.Object.Echo(42); mock.Object.Submit(); var mex = AssertHelper.Throws<MockException>(() => mock.Verify(f => f.Execute("pong"))); AssertHelper.Contains( Environment.NewLine + "Performed invocations:" + Environment.NewLine + "IFoo.Execute(\"ping\")" + Environment.NewLine + "IFoo.Echo(42)" + Environment.NewLine + "IFoo.Submit()", mex.Message); }
public void DoesNotDisposeCacheStoreIfPassedToIt() { var mock = new Moq.Mock<ICacheStore>(MockBehavior.Strict); var handler = new CachingHandler(mock.Object); handler.Dispose(); mock.Verify(); }
public void DoesNotDisposeVaryHeaderStoreIfPassedToIt() { var mockcs = new Moq.Mock<ICacheStore>(); var mockvh = new Moq.Mock<IVaryHeaderStore>(MockBehavior.Strict); var handler = new CachingHandler(mockcs.Object, mockvh.Object); handler.Dispose(); mockvh.Verify(); }
public void SendActivationEmail_FillInTemplateAndCallEmailService() { // Given String templatedMail = "plouf"; String toAddress = "@@"; BaseAd ad = new Ad() { Title = "ss", CreatedBy = new Bea.Domain.User() { Email = toAddress } }; var templatingMock = new Moq.Mock<ITemplatingService>(); templatingMock.Setup(x => x.GetTemplatedDocument("ActivationEmail.vm", Moq.It.IsAny<IDictionary<String, String>>(), null)).Returns(templatedMail); var appSettingsMock = new Moq.Mock<IApplicationSettingsProvider>(); appSettingsMock.Setup(x => x.WebsiteAddress).Returns("beaproject.com"); appSettingsMock.Setup(x => x.WebsiteName).Returns("BEA"); var emailMock = new Moq.Mock<IEmailServices>(); emailMock.Setup(x => x.SendEmail("BEA Activez votre annonce \"ss\"", "plouf", "@@", "*****@*****.**")).Verifiable(); AdActivationServices service = new AdActivationServices(null, templatingMock.Object, emailMock.Object, appSettingsMock.Object); // When service.SendActivationEmail(ad); // Then emailMock.Verify(x => x.SendEmail("BEA Activez votre annonce \"ss\"", "plouf", "@@", "*****@*****.**"), Times.Once()); }
public void PerformDeleteAd_AdExists_PasswordMatches_MarkAdAsDeletedAndRemoveFromSearchAdCache() { // Given DeleteAdModel model = new DeleteAdModel { AdId = 56, Password = "******", NbTry = 1, SelectedDeletionReasonId = 7 }; DeletionReason dr = new DeletionReason() { Id = 7 }; SearchAdCache adc = new SearchAdCache() { AdId = 56 }; User creator = new User() { Password = "******" }; BaseAd ad = new Ad() { Id = 56, CreatedBy = creator }; var adRepoMock = new Moq.Mock<IAdRepository>(); adRepoMock.Setup(r => r.GetAdById<BaseAd>(model.AdId)).Returns(ad); var repoMock = new Moq.Mock<IRepository>(); repoMock.Setup(x => x.Get<DeletionReason>(7)).Returns(dr); repoMock.Setup(x => x.Get<SearchAdCache>(model.AdId)).Returns(adc); repoMock.Setup(x => x.Save<BaseAd>(ad)); repoMock.Setup(x => x.Delete<SearchAdCache>(adc)); var helperMock = new Moq.Mock<IHelperService>(); helperMock.Setup(x => x.GetCurrentDateTime()).Returns(new DateTime(2013, 01, 26)); AdDeletionServices service = new AdDeletionServices(adRepoMock.Object, repoMock.Object, helperMock.Object); // When DeleteAdModel result = service.DeleteAd(model); // Then Assert.AreEqual(model.AdId, result.AdId); Assert.IsNull(result.Password); Assert.IsNull(result.SelectedDeletionReasonId); Assert.AreEqual(0, result.NbTry); Assert.AreEqual("Votre annonce a correctement été supprimée. Elle n'est plus disponible à la recherche.", result.InfoMessage); Assert.IsFalse(result.CanDeleteAd); Assert.IsTrue(result.IsDeleted); Assert.AreEqual(new DateTime(2013, 01, 26), ad.DeletionDate); Assert.IsTrue(ad.IsDeleted); Assert.AreEqual(dr, ad.DeletedReason); repoMock.Verify(x => x.Save<BaseAd>(ad), Times.Once()); repoMock.Verify(x => x.Delete<SearchAdCache>(adc), Times.Once()); }
public void AggregateBus_PublishWillPassToTheEventBus() { var guid = Guid.NewGuid(); var @event = new TestEvent(); var eventBus = new Moq.Mock<IEventBus>(); eventBus.Setup(m => m.PublishAsync<TestAggregate, TestEvent>(guid, @event)) .Returns(Task.FromResult<object>(null)).Verifiable(); var aggregateCache = new Moq.Mock<IAggregateCache>(); aggregateCache.Setup(x => x.HandleAsync<TestAggregate, TestEvent>(guid, @event)) .Returns(Task.FromResult<object>(null)).Verifiable(); AggregateBus.Instance.Configure(eventBus.Object, aggregateCache.Object); AggregateBus.Instance.Awaiting(m => m.PublishAsync<TestAggregate, TestEvent>(guid, @event)) .ShouldNotThrow(); eventBus.Verify(m => m.PublishAsync<TestAggregate, TestEvent>(guid, @event), Moq.Times.Once); aggregateCache.Verify(m => m.HandleAsync<TestAggregate, TestEvent>(guid, @event), Moq.Times.Once); }