public void LoadSettings_SettingsAreSetNoError() { IStorage storage = Substitute.For <IStorage>(); var settings = new PdfCreatorSettings(storage); settings.ApplicationSettings.PrimaryPrinter = "primaryPrinter"; _simpleSettingsProvider.Settings.Returns(settings); _iniSettingsAssitant.LoadIniSettings().Returns(true); HandleMessageInteraction(interaction => interaction.Response = MessageResponse.Yes); var viewModel = BuildModel(); viewModel.LoadIniSettingsCommand.Execute(null); Received .InOrder(() => { _settingsManager.ApplyAndSaveSettings(Arg.Any <PdfCreatorSettings>()); _settingsManager.LoadAllSettings(); _settingsManager.SaveCurrentSettings(); }); }
public void Can_decode_frame_after_frame() { IByteBuffer buffer = Unpooled.Buffer(256); buffer.WriteBytes(_frame); buffer.WriteBytes(_shortFrame); UnderTest underTest = new UnderTest(_frameCipher, _macProcessor); underTest.Decode(buffer); underTest.Decode(buffer); Received.InOrder( () => { _macProcessor.Received().CheckMac(Arg.Any <byte[]>(), 0, LongFrameSize, false); _frameCipher.Received().Decrypt(Arg.Any <byte[]>(), 0, LongFrameSize, Arg.Any <byte[]>(), 0); _macProcessor.Received().CheckMac(Arg.Any <byte[]>(), 0, ShortFrameSize, false); _frameCipher.Received().Decrypt(Arg.Any <byte[]>(), 0, ShortFrameSize, Arg.Any <byte[]>(), 0); } ); }
public void Pass_Items_In_Sequence_Order() { var write = Substitute.For <Action <StreamWriter, string> >(); using var stream = fixture.Create( output => new StreamWriter(output, Encoding.UTF8), new[] { "Dog", "Cat", "Sparrow" }, write ); using var reader = new StreamReader(stream, Encoding.UTF8); reader.ReadToEnd(); Received.InOrder( () => { write(Arg.Any <StreamWriter>(), "Dog"); write(Arg.Any <StreamWriter>(), "Cat"); write(Arg.Any <StreamWriter>(), "Sparrow"); } ); }
public void Should_Execute_Tasks_In_Correct_Order() { // Given var fixture = new CakeHostBuilderFixture(); fixture.RegisterTask <BuildTask>(); fixture.RegisterTask <CleanTask>(); fixture.RegisterTask <UnitTestsTask>(); fixture.UseExecutionStrategySubstitute(); fixture.Options.Target = "Run-Unit-Tests"; // When fixture.Run(); // Then Received.InOrder(() => { fixture.Strategy.ExecuteAsync(Arg.Is <CakeTask>(t => t.Name == "Clean"), Arg.Any <ICakeContext>()); fixture.Strategy.ExecuteAsync(Arg.Is <CakeTask>(t => t.Name == "Build"), Arg.Any <ICakeContext>()); fixture.Strategy.ExecuteAsync(Arg.Is <CakeTask>(t => t.Name == "Run-Unit-Tests"), Arg.Any <ICakeContext>()); }); }
public void Given_PlayersData_When_ReportRequested_Then_ReturnReportWithTeamStatistics() { // Arrange var enricher1 = Substitute.For <IReportEnricher>(); var enricher2 = Substitute.For <IReportEnricher>(); var sut = new TeamStatisticsReporter(new List <IReportEnricher> { enricher1, enricher2 }); var players = new List <Player> { }; enricher1.EnrichReport(Arg.Any <IEnumerable <Player> >(), Arg.Any <IReportBuilder>()) .Returns(ci => ci.Arg <IReportBuilder>()); enricher2.EnrichReport(Arg.Any <IEnumerable <Player> >(), Arg.Any <IReportBuilder>()) .Returns(ci => ci.Arg <IReportBuilder>()); // Act var result = sut.GetReport(players); // Assert Assert.NotNull(result); Received.InOrder(() => { enricher1 .Received(1) .EnrichReport(Arg.Is <IEnumerable <Player> >(p => p.Equals(players)), Arg.Any <IReportBuilder>()); enricher2 .Received(1) .EnrichReport(Arg.Is <IEnumerable <Player> >(p => p.Equals(players)), Arg.Any <IReportBuilder>()); }); }
public void TestInputShouldBeValidatedAndCleanedBeforeDeleting() { var storeService = Substitute.For <IStoreService>(); var templateService = Substitute.For <ITemplateService>(); templateService.IsValid(Arg.Any <string>()).ReturnsForAnyArgs(true); templateService.Clean(Arg.Any <string>()).ReturnsForAnyArgs(""); storeService.DeleteTemplate(Arg.Any <string>()).Returns(true); var controller = new TemplatesController(storeService, templateService); controller.ControllerContext = new ControllerContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.Delete(); Received.InOrder(() => { templateService.IsValid(Arg.Any <string>()); templateService.Clean(Arg.Any <string>()); storeService.DeleteTemplate(Arg.Any <string>()); }); }
public void Should_Register_The_Context() { // Given var services = Substitute.For <ICakeServices>(); var builder = Substitute.For <ICakeRegistrationBuilder>(); services.RegisterType(Arg.Any <Type>()).Returns(builder); // Return a builder object when registering builder.AsSelf().Returns(builder); // Return same builder object when chaining builder.As(Arg.Any <Type>()).Returns(builder); // Return same builder object when chaining // When services.UseContext <FrostingContext>(); // Then Received.InOrder(() => { services.RegisterType <FrostingContext>(); builder.AsSelf(); builder.As <IFrostingContext>(); builder.Singleton(); }); }
public async Task GetTokenWithClaimsPrincipal_IncorrectPassword_ReturnsNull() { // Arrange var model = new LoginModel { Email = "*****@*****.**", Password = "******" }; var user = new JobApplicationUser(model.Email); _userManager.FindByEmailAsync(model.Email).Returns(Task.FromResult(user)); _userManager.CheckPasswordAsync(user, model.Password).Returns(Task.FromResult(false)); // Act var result = await _accountManagerService.GetTokenWithClaimsPrincipal(model).ConfigureAwait(false); // Assert Received.InOrder(async() => { await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false); await _userManager.CheckPasswordAsync(user, model.Password).ConfigureAwait(false); }); Assert.Null(result); }
public void ParseMultiple(string value) { syntaxParser.Parse(value); Received.InOrder(() => { foreach (char c in value) { if (c == 'M') { handler.HandleM(); } else if (c == 'L') { handler.HandleL(); } else if (c == 'R') { handler.HandleR(); } } }); }
public async Task GetAsyncInTwoBatchesAsync() { SetupActualNumberOfFrames(StackFramesProvider.FramesBatchSize + 5); IList <FRAMEINFO> frames = await _stackFramesProvider.GetAllAsync(_fieldSpec, _debugThread); Received.InOrder(() => { _remoteThread.GetFramesWithInfoAsync( (FrameInfoFlags)_fieldSpec, 0, StackFramesProvider.FramesBatchSize).Wait(); _remoteThread.GetFramesWithInfoAsync((FrameInfoFlags)_fieldSpec, StackFramesProvider.FramesBatchSize, StackFramesProvider.FramesBatchSize).Wait(); }); Assert.IsNotNull(frames); Assert.That(frames.Count, Is.EqualTo(205)); for (var i = 0; i < StackFramesProvider.FramesBatchSize + 5; ++i) { Assert.That(frames[i].m_bstrFuncName, Is.EqualTo($"Func{i}")); } }
public void DownloadFile_WhenInvoked_StatsDownloadIsPerformed() { InvokeDownloadFile(); Received.InOrder(async() => { loggingServiceMock.LogVerbose("DownloadStatsFile Invoked"); fileDownloadDatabaseServiceMock.IsAvailable(); fileDownloadDatabaseServiceMock.UpdateToLatest(); dateTimeServiceMock.DateTimeNow(); loggingServiceMock.LogVerbose($"Stats file download started: {dateTime}"); fileDownloadDatabaseServiceMock.FileDownloadStarted(Arg.Any <FilePayload>()); fileDownloadMinimumWaitTimeServiceMock.IsMinimumWaitTimeMet(Arg.Any <FilePayload>()); filePayloadSettingsServiceMock.SetFilePayloadDownloadDetails(Arg.Any <FilePayload>()); downloadServiceMock.DownloadFile(Arg.Any <FilePayload>()); dateTimeServiceMock.DateTimeNow(); loggingServiceMock.LogVerbose($"Stats file download completed: {dateTime}"); await filePayloadUploadServiceMock.UploadFile(Arg.Any <FilePayload>()); resourceCleanupServiceMock.Cleanup(Arg.Any <FileDownloadResult>()); loggingServiceMock.LogResult(Arg.Any <FileDownloadResult>()); }); }
public async Task OnWorkSucceededAsync_ProcessesAsyncAndSync() { var dispatchResult = new QueueDispatchResult() { EnqueuedEventsAsyncProcessed = new List <IAsyncEventQueueRecord>() { new FakeAsyncEventQueueRecord() { EventId = Guid.NewGuid(), EventMessage = messages[0], Id = Guid.NewGuid(), QueueName = "queue1", SequenceNumber = 1 } }, EnqueuedEventsSyncProcessed = new List <IAsyncEventQueueRecord>() { new FakeAsyncEventQueueRecord() { EventId = Guid.NewGuid(), EventMessage = messages[0], Id = Guid.NewGuid(), QueueName = "queue2", SequenceNumber = 1 } } }; asyncEventQueueDispatcher.DispatchToQueuesAsync(null, null, null).ReturnsForAnyArgs(dispatchResult); await sut.HandleAsync(messages[0], CancellationToken.None); await sut.OnWorkSucceededAsync(unitOfWork); Received.InOrder(() => { asyncEventProcessor.EnqueueForAsyncProcessingAsync( Arg.Is <IReadOnlyCollection <IAsyncEventQueueRecord> >(x => x.SequenceEqual(dispatchResult.EnqueuedEventsAsyncProcessed)), null); asyncEventProcessor.ProcessSynchronously( Arg.Is <IReadOnlyCollection <IAsyncEventQueueRecord> >(x => x.SequenceEqual(dispatchResult.EnqueuedEventsSyncProcessed))); }); }
public void InvokeMethod_Should_PerformTheExpectedCallsAndReturnFalse_GivenTheInvokedMethodHasANotReachedDelay() { GameObject gameObject = UnitTestUtility.CreateGameObject(); ExtensionRunnerBusinessLogic businessLogic = new ExtensionRunnerBusinessLogic(gameObject); Component component = Substitute.For <Component>(); MethodInfo mockedMethodInfo = Substitute.For <MethodInfo>(); object methodInvokeAssertionResult = new AssertionResultSuccessful(); object[] parameters = new object[0]; mockedMethodInfo.Invoke(component, parameters).Returns(methodInvokeAssertionResult); FullMethodDescription methodDescription = Substitute.For <FullMethodDescription>(); methodDescription.Method = mockedMethodInfo; methodDescription.GetFullName().Returns <string>("component.method"); methodDescription.Delay = 1000; ExtensionRunnerBusinessLogic mockedBusinessLogic = Substitute.For <ExtensionRunnerBusinessLogic>(gameObject); DateTime firstNowDatetime = new DateTime(2017, 05, 01, 00, 00, 00, 000); mockedBusinessLogic.StartDelayTime = firstNowDatetime; DateTime secondNowDatetime = new DateTime(2017, 05, 01, 00, 00, 00, 990); mockedBusinessLogic.DateTimeNow().Returns <DateTime>(secondNowDatetime); mockedBusinessLogic.GetParametersValues(methodDescription).Returns <object[]>(parameters); mockedMethodInfo.Invoke(component, parameters).Returns(methodInvokeAssertionResult); methodDescription.Method = mockedMethodInfo; bool result = businessLogic.InvokeMethod(mockedBusinessLogic, methodDescription, gameObject); Received.InOrder(() => { mockedBusinessLogic.DateTimeNow(); }); Assert.IsFalse(result, "The method InvokeMethod doesn't return the right state"); }
public void ContinueInBreakModeSignal() { var selectedThread = Substitute.For <RemoteThread>(); _process.GetSelectedThread().Returns(selectedThread); selectedThread.GetStopReason().Returns(StopReason.SIGNAL); selectedThread.GetStopReasonDataCount().Returns <uint>(1); ulong sigAbort = 6; selectedThread.GetStopReasonDataAtIndex(0).Returns(sigAbort); _attachedProgram.ContinueInBreakMode(); EXCEPTION_INFO[] info = null; Predicate <DebugEvent> matchExceptionEvent = e => { if (!(e is ExceptionEvent exceptionEvent)) { return(false); } info = new EXCEPTION_INFO[1]; exceptionEvent.GetException(info); return(true); }; Received.InOrder(() => { _debugEngineHandler.SendEvent(Arg.Is <DebugEvent>(e => matchExceptionEvent(e)), _debugProgram,selectedThread); _lldbShell.AddDebugger(_debugger); _debugProgram.Received().EnumModules(out _); }); Assert.That(info[0].dwState, Is.EqualTo(enum_EXCEPTION_STATE.EXCEPTION_STOP_ALL | enum_EXCEPTION_STATE.EXCEPTION_CANNOT_BE_CONTINUED)); Assert.That(info[0].bstrExceptionName,Is.EqualTo("SIGABRT")); }
public async Task PublishSubscribe_WhenHandlerReturnTask_ShouldWaitTillHandlerEnd() { // given var delivery = new CountdownEvent(2); var mockClass = Substitute.For <MockClass>(); var startValue = "start"; var endValue = "end"; _sut.Subscribe <TestMessage>(async m => { mockClass.Test(startValue); await Task.Delay(TimeSpan.FromMilliseconds(500)); mockClass.Test(endValue); delivery.Signal(); }, SubscribeOptions.NonExclusive()); await _sut.StartAsync(); // when await _sut.PublishAsync(new TestMessage()); await _sut.PublishAsync(new TestMessage()); delivery.Wait(TimeSpan.FromSeconds(15)); // then Received.InOrder(() => { // Проверяем, что перед началом обработки следующего сообщения заканчивается обработка первого mockClass.Test(startValue); mockClass.Test(endValue); mockClass.Test(startValue); mockClass.Test(endValue); }); }
public void Draw_Single_line() { var start = Substitute.For <ITextPosition>(); start.Bias.Returns(Bias.Forward); start.Offset.Returns(5); var end = Substitute.For <ITextPosition>(); end.Bias.Returns(Bias.Backward); end.Offset.Returns(10); var drawingService = Substitute.For <IBatchedDrawingService>(); var docView = Substitute.For <IDocumentView <ITextDocument> >(); docView.LayoutRect.Returns(new Rectangle(10, 20, 120, 200)); Rectangle rect; docView.ModelToView(5, out rect).Returns( x => { x[1] = new Rectangle(50, 20, 11, 15); return(true); }); docView.ModelToView(10, out rect).Returns( x => { x[1] = new Rectangle(80, 20, 11, 15); return(true); }); var style = LayoutTestStyle.Create(); var h = new Highlight <ITextDocument>(start, end, style.StyleSystem.CreatePresentationStyle()); h.Draw(drawingService, docView); Received.InOrder(() => { drawingService.FillRect(new Rectangle(50, 20, 30, 15), Arg.Any <Color>()); }); }
public void TestApply() { UrlDir.UrlFile file = UrlBuilder.CreateFile("abc/def.cfg"); UrlDir.UrlConfig urlConfig1 = UrlBuilder.CreateConfig(new ConfigNode("NODE"), file); UrlDir.UrlConfig urlConfig2 = UrlBuilder.CreateConfig(new ConfigNode("NODE"), file); UrlDir.UrlConfig urlConfig3 = UrlBuilder.CreateConfig(new ConfigNode("NODE"), file); UrlDir.UrlConfig urlConfig4 = UrlBuilder.CreateConfig(new ConfigNode("NODE"), file); INodeMatcher nodeMatcher = Substitute.For <INodeMatcher>(); nodeMatcher.IsMatch(urlConfig1.config).Returns(false); nodeMatcher.IsMatch(urlConfig2.config).Returns(true); nodeMatcher.IsMatch(urlConfig3.config).Returns(false); nodeMatcher.IsMatch(urlConfig4.config).Returns(true); DeletePatch patch = new DeletePatch(UrlBuilder.CreateConfig("ghi/jkl", new ConfigNode("!NODE")), nodeMatcher, Substitute.For <IPassSpecifier>()); IPatchProgress progress = Substitute.For <IPatchProgress>(); IBasicLogger logger = Substitute.For <IBasicLogger>(); patch.Apply(file, progress, logger); Assert.Equal(new[] { urlConfig1, urlConfig3 }, file.configs); Received.InOrder(delegate { progress.ApplyingDelete(urlConfig2, patch.UrlConfig); progress.ApplyingDelete(urlConfig4, patch.UrlConfig); }); progress.DidNotReceiveWithAnyArgs().ApplyingUpdate(null, null); progress.DidNotReceiveWithAnyArgs().ApplyingCopy(null, null); progress.DidNotReceiveWithAnyArgs().Error(null, null); progress.DidNotReceiveWithAnyArgs().Exception(null, null); progress.DidNotReceiveWithAnyArgs().Exception(null, null, null); }
public void Update_ShouldExecuteEngineSystemsInCorrectOrder() { // Arrange GameTime.FixedDeltaTime = TimeSpan.FromSeconds(0.1); var gameTime = new GameTime(TimeSpan.FromSeconds(0.15)); _gameTimeProvider.GetGameTime().Returns(gameTime); var scene = TestSceneFactory.Create(); _sceneManager.CurrentScene.Returns(scene); var gameLoop = GetGameLoop(); // Act gameLoop.Update(); // Assert Received.InOrder(() => { _inputSystem.Received(1).ProcessInput(scene); _behaviorSystem.Received(1).ProcessBehaviorFixedUpdate(scene); _customSystem1.Received(1).ProcessFixedUpdate(scene); _customSystem2.Received(1).ProcessFixedUpdate(scene); _customSystem3.Received(1).ProcessFixedUpdate(scene); _physicsSystem.Received(1).ProcessPhysics(scene); _entityDestructionSystem.Received(1).DestroyEntitiesAfterFixedTimeStep(scene); _behaviorSystem.Received(1).ProcessBehaviorUpdate(scene, gameTime); _customSystem1.Received(1).ProcessUpdate(scene, gameTime); _customSystem2.Received(1).ProcessUpdate(scene, gameTime); _customSystem3.Received(1).ProcessUpdate(scene, gameTime); _physicsSystem.Received(1).PreparePhysicsDebugInformation(); _audioSystem.Received(1).ProcessAudio(scene); _animationSystem.Received(1).ProcessAnimations(scene, gameTime); _renderingSystem.Received(1).RenderScene(scene); _entityDestructionSystem.Received(1).DestroyEntitiesAfterFullFrame(scene); }); }
public void VerifyPersistenceHappyPath() { // Arrange byte[] dummyData = Encoding.UTF8.GetBytes(Storage.PersistenceValidationDummyData); var actualLogger = new TraceSourceLogger(_logger); var cacheAccessor = Substitute.For <ICacheAccessor>(); cacheAccessor.CreateForPersistenceValidation().Returns(cacheAccessor); var storage = new Storage(s_storageCreationProperties, cacheAccessor, actualLogger); cacheAccessor.Read().Returns(dummyData); // Act storage.VerifyPersistence(); // Assert Received.InOrder(() => { cacheAccessor.CreateForPersistenceValidation(); cacheAccessor.Write(Arg.Any <byte[]>()); cacheAccessor.Read(); cacheAccessor.Clear(); }); }
public void DealShouldBeSavedInDatabase() { Client testSeller = new Client() { Stocks = new HashSet <Stock>() }; Client testBuyer = new Client() { Stocks = new HashSet <Stock>() }; Stock s = new Stock() { IsForSale = true }; testSeller.Stocks.Add(s); this.bussinesService.RegisterNewDeal(testSeller, testBuyer, s, 100); Received.InOrder(() => { this.dataContext.Add(Arg.Any <Deal>()); this.dataContext.SaveChanges(); }); }
public void Try_ExecutesRuleTypesInOrder() { var rule1 = GetTestRule(ruleType: EventRuleType.BeforeEvent, ruleOrder: 1); var rule2 = GetTestRule(ruleType: EventRuleType.EventResolution, ruleOrder: 2); var rule3 = GetTestRule(ruleType: EventRuleType.AfterSuccess, ruleOrder: 2); var rule4 = GetTestRule(ruleType: EventRuleType.Finally, ruleOrder: 2); var ruleOnFail = GetTestRule(ruleType: EventRuleType.AfterFailure, ruleOrder: 2); _eventSystem.RegisterRules(rule1, rule2, rule3, rule4, ruleOnFail); _eventSystem.Try(EventType.Action, _entity, null); Received.InOrder(() => { rule1.Apply(Arg.Any <EventType>(), Arg.Any <IEntity>(), Arg.Any <object>()); rule2.Apply(Arg.Any <EventType>(), Arg.Any <IEntity>(), Arg.Any <object>()); rule3.Apply(Arg.Any <EventType>(), Arg.Any <IEntity>(), Arg.Any <object>()); rule4.Apply(Arg.Any <EventType>(), Arg.Any <IEntity>(), Arg.Any <object>()); }); ruleOnFail.DidNotReceiveWithAnyArgs().Apply(Arg.Any <EventType>(), null, null); }
public async Task ShouldRetryWhenReceiveServerIdNegativeOne() { var conn = Substitute.For <IConnection>(); conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>(), Arg.Any <IRequestContext>()) .Returns(x => CreateMetadataResponse(-1, "123", 1), x => CreateMetadataResponse(ErrorCode.NONE)); var router = GetRouter(conn); var log = new MemoryLog(); router.Log.ReturnsForAnyArgs(log); var response = await router.GetMetadataAsync(new MetadataRequest("Test"), CancellationToken.None); Received.InOrder(() => { conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>()); //_log.OnLogged.Invoke(LogLevel.Warn, It.Is<LogEvent>(e => e.Message.StartsWith("Failed metadata request on attempt 0: Will retry in"))); conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>()); }); Assert.That(log.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Failed metadata request on attempt 0: Will retry in"))); Assert.That(log.LogEvents.Count(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Failed metadata request on attempt")), Is.EqualTo(1)); }
public void Test_Writing_An_Instance_Of_A_Tree_With_A_Node_At_Offset() { uint originalPosition = 43, offset = 15; IDataNode rootNode = TreeWithNodeAtOffset.Build(); TreeWithNodeAtOffset.Class value = new TreeWithNodeAtOffset.Class { ValueAtOffset = "value", ValueInline = 54 }; binaryWriter.GetPosition().Returns(originalPosition); (rootNode.Edges[0].ChildNode as IOffsetNode) .Write(binaryWriter, Arg.Any <object>()) .Returns(offset); treeWriter.Write(binaryWriter, value, rootNode) .Should() .Equal(offset); Received.InOrder(() => VerifyWriteTreeWithNodeAtOffset(rootNode, value, originalPosition, offset)); }
public void Consumed_MessageWithErrors_AfterSaveWasNotCalled() { //Arrange var correlationId = Guid.NewGuid(); repository.Save(new SagaWithErrors() { CorrelationId = correlationId, SagaData = new SagaWithErrorsData(), Headers = new Dictionary <string, string>() }); var message = new GetSomeConsumedErrorsForSagaWithErrors(correlationId); // Act sut.Consume(message); // Assert Received.InOrder(() => { pipelineHook.BeforeConsuming(Arg.Any <PipelineContext>()); pipelineHook.AfterConsuming(Arg.Any <PipelineContext>()); }); pipelineHook.DidNotReceive().AfterSave(Arg.Any <PipelineContext>()); }
public void Consumed_PipelineHooks_ExecutedInOrder() { //Arrange var correlationId = Guid.NewGuid(); repository.Save(new MySaga() { CorrelationId = correlationId }); var message = new MySagaConsumingMessage(correlationId); // Act sut.Consume(message); // Assert Received.InOrder(() => { pipelineHook.BeforeConsuming(Arg.Any <PipelineContext>()); pipelineHook.AfterConsuming(Arg.Any <PipelineContext>()); pipelineHook.AfterSave(Arg.Any <PipelineContext>()); }); }
public async Task CreateInviteAsync_ShouldCreateANewGroupInviteInDatabase() { const int groupId = 42; const int characterId = 24; var request = new CreateInviteRequest { CharacterId = characterId, FromGroup = true }; var group = new Group(); var character = new Character(); _unitOfWorkFactory.GetUnitOfWork().Groups.GetAsync(groupId) .Returns(group); _unitOfWorkFactory.GetUnitOfWork().Characters.GetWithOriginWithJobsAsync(characterId) .Returns(character); await _service.CreateInviteAsync(new NaheulbookExecutionContext(), groupId, request); Received.InOrder(() => { _unitOfWorkFactory.GetUnitOfWork().GroupInvites.Add(Arg.Is <GroupInvite>(gi => gi.FromGroup && gi.Group == group && gi.Character == character)); _unitOfWorkFactory.GetUnitOfWork().SaveChangesAsync(); }); }
public async Task AddItemToCharacterAsync_ShouldAddACharacterHistoryEntry() { const int characterId = 4; var item = new Item(); var expectedCharacterHistoryEntry = new CharacterHistoryEntry(); _unitOfWorkFactory.GetUnitOfWork().Characters.GetWithGroupAsync(Arg.Any <int>()) .Returns(new Character { Id = characterId }); _itemService.AddItemToAsync(Arg.Any <ItemOwnerType>(), Arg.Any <int>(), Arg.Any <CreateItemRequest>()) .Returns(item); _characterHistoryUtil.CreateLogAddItem(characterId, item) .Returns(expectedCharacterHistoryEntry); await _service.AddItemToCharacterAsync(new NaheulbookExecutionContext(), characterId, new CreateItemRequest()); Received.InOrder(() => { _unitOfWorkFactory.GetUnitOfWork(1).CharacterHistoryEntries.Add(expectedCharacterHistoryEntry); _unitOfWorkFactory.GetUnitOfWork(1).SaveChangesAsync(); }); }
public async Task CanBatchAdd() { List <object> list = new List <object> { new BatchAddItem { Id = "1", Name = "Foo 1" }, new BatchAddItem { Id = "2", Name = "Foo 2" }, new BatchAddItem { Id = "3", Name = "Foo 3" } }; var mock = Substitute.For <IGraphQlRepository>(); await mock.BatchAddAsync(typeof(BatchAddItem), list, null); Received.InOrder(async() => { await mock.BatchAddAsync(Arg.Is <List <BatchAddItem> >(x => x.Count == 3), null); }); }
public void EachWeaponShoots_WhenSpaceShipShootIsCalled2() { // Arrange. var weapon1 = Substitute.For <IWeapon>(); var weapon2 = Substitute.For <IWeapon>(); var spaceShip = new SpaceShip(2, 0); spaceShip.Equip(weapon1); spaceShip.Equip(weapon2); // Act. spaceShip.Shoot(); // Assert. Received.InOrder(() => { weapon1.Shoot(); weapon2.Shoot(); weapon1.Reload(); weapon2.Reload(); }); }
public void DoesNotEmitAnythingWhenSelectingAdditionalCalendars() { var observer = Substitute.For <IObserver <bool> >(); ViewModel.DoneAction.Enabled.Subscribe(observer); var selectedableUserCalendars = Enumerable .Range(0, 10) .Select(id => { var userCalendar = new UserCalendar(id.ToString(), id.ToString(), "Doenst matter"); return(new SelectableUserCalendarViewModel(userCalendar, false)); }); selectedableUserCalendars .ForEach(calendar => ViewModel.SelectCalendarAction.Execute(calendar).Wait()); SchedulerProvider.TestScheduler.AdvanceBy(2); Received.InOrder(() => { observer.OnNext(false); observer.OnNext(true); }); }