public async Task Reply_ShouldInvokeMessageInitializer() { var context = new TestableMessageHandlerContext(); await context.Reply<ITestMessage>(m => m.Value = "initialized value"); Assert.AreEqual("initialized value", context.RepliedMessages[0].Message<ITestMessage>().Value); }
public async Task ForwardCurrentMessageTo_ShouldContainDestinationsInForwardDestinations() { var context = new TestableMessageHandlerContext(); await context.ForwardCurrentMessageTo("destination1"); await context.ForwardCurrentMessageTo("destination2"); Assert.Contains("destination1", context.ForwardedMessages); Assert.Contains("destination2", context.ForwardedMessages); }
public async Task Given() { message = new OrderPlaced { OrderId = Guid.NewGuid() }; var sut = new OrderPlacedHandler(); context = new TestableMessageHandlerContext(); await sut.Handle(message, context); }
public async Task Should_have_passed_through_correct_context() { var cache = new MessageHandlerRegistry(); cache.RegisterHandler(typeof(StubHandler)); var handler = cache.GetCachedHandlerForMessage <StubMessage>(); var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(new StubMessage(), handlerContext); Assert.AreSame(handlerContext, ((StubHandler)handler.Instance).HandlerContext); }
public async Task Send_ShouldContainMessageInSentMessages() { var context = new TestableMessageHandlerContext(); var messageInstance = new TestMessage(); var sendOptions = new SendOptions(); await context.Send(messageInstance, sendOptions); Assert.AreEqual(1, context.SentMessages.Length); Assert.AreSame(messageInstance, context.SentMessages[0].Message); Assert.AreSame(sendOptions, context.SentMessages[0].Options); }
public async Task SendCachedEvent() { var handler = new Handlers.P2pReceivedHandler(string.Empty); var context = new TestableMessageHandlerContext(); var workflowId = Guid.NewGuid(); await handler.PublishP2pCached(context, null, workflowId); var publishedMessages = context.PublishedMessages; handler.ShouldSatisfyAllConditions(() => publishedMessages.Containing <P2pCached>().Any(t => t.Message.WorkflowId == workflowId && t.Message.InsertedItems == null).ShouldBe(true)); }
public async Task Reply_ShouldContainMessageInRepliedMessages() { var context = new TestableMessageHandlerContext(); var messageInstance = new TestMessage(); var publishOptions = new ReplyOptions(); await context.Reply(messageInstance, publishOptions); Assert.AreEqual(1, context.RepliedMessages.Length); Assert.AreSame(messageInstance, context.RepliedMessages[0].Message); Assert.AreSame(publishOptions, context.RepliedMessages[0].Options); }
public async Task Logging() { var handler = new MyHandlerWithLogging(); var context = new TestableMessageHandlerContext(); await handler.Handle(new MyMessage(), context); await Verify(new { context, LogCapture.LogMessages }); }
IBehaviorContext CreateContext <TContext>(IPipeline <TContext> pipeline) where TContext : IBehaviorContext { var pipelineCache = new FakePipelineCache(); pipelineCache.RegisterPipeline(pipeline); var context = new TestableMessageHandlerContext(); context.Builder.Register <IMessageMapper>(() => new MessageMapper()); context.Extensions.Set <IPipelineCache>(pipelineCache); return(context); }
public static T ExpectPublish <T>(this TestableMessageHandlerContext context, Func <T, bool> matching = null) where T : IMessage { var publishedMessages = GetPublishedMessages(context, matching); if (publishedMessages.Count < 1) { var eventsString = GetPublishedEvents(context); eventsString = !string.IsNullOrWhiteSpace(eventsString) ? $"Actual Events published: {eventsString}" : null; throw new Exception($"Expected 1 message of type {typeof(T)} but found {publishedMessages.Count}. {eventsString}"); } return(publishedMessages.First()); }
public async Task GetNativeMessageCustomization_when_no_customization_should_return_null() { var testableContext = new TestableMessageHandlerContext(); var handler = new MyHandlerWithoutCustomization(); await handler.Handle(new MyMessage(), testableContext); var publishedMessage = testableContext.PublishedMessages.Single(); var customization = publishedMessage.Options.GetNativeMessageCustomization(); Assert.IsNull(customization); }
public async Task Should_have_passed_through_correct_message() { var cache = new MessageHandlerRegistry(new Conventions()); cache.RegisterHandler(typeof(StubHandler)); var handler = cache.GetCachedHandlerForMessage <StubMessage>(); var stubMessage = new StubMessage(); var handlerContext = new TestableMessageHandlerContext(); await handler.Invoke(stubMessage, handlerContext); Assert.AreEqual(stubMessage, ((StubHandler)handler.Instance).HandledMessage); }
private static string GetPublishedEvents(TestableMessageHandlerContext context) { var eventType = typeof(IEvent); return(string.Join(Environment.NewLine, context.PublishedMessages .Select(x => x.Message) .Select(o => o.GetType().GetInterfaces() .Any(y => eventType.IsAssignableFrom(y)) ? o.ToString() : null) .Where(x => !string.IsNullOrWhiteSpace(x)))); }
public async Task ShouldReplyWithResponseMessage() { var handler = new MyReplyingHandler(); var context = new TestableMessageHandlerContext(); await handler.Handle(new MyRequest(), context) .ConfigureAwait(false); var repliedMessages = context.RepliedMessages; Assert.AreEqual(1, repliedMessages.Length); Assert.IsInstanceOf <MyResponse>(repliedMessages[0].Message); }
public TestableContext() { _ids = new IdRegistry(); _ctx = new TestableMessageHandlerContext(); UoW = new TestableDomain(_ids); App = new TestableApplication(_ids); Processor = new TestableProcessor(); _ctx.Extensions.Set <UnitOfWork.IDomain>(UoW); _ctx.Extensions.Set <UnitOfWork.IApplication>(App); _ctx.Extensions.Set <IProcessor>(Processor); _ctx.Extensions.Set <IContainer>(new TestableContainer()); }
public async Task HandleCreateOrderMessageCorrectly() { var context = new TestableMessageHandlerContext(); var message = new CreateOrder { OrderId = _orderId, UserId = UserId }; await _target.Handle(message, context); await _orderHubMessageDispatcher.Received().SendToGroupAsync(UserId, "StatusUpdated", Arg.Is <OrderStatus>(s => s.OrderId == message.OrderId && s.Status == "Pending")); }
public async Task Should_dispatch_edited_message_when_retrying() { var failedMessageId = Guid.NewGuid().ToString(); await CreateFailedMessage(failedMessageId); var handlerContext = new TestableMessageHandlerContext(); var message = CreateEditMessage(failedMessageId); await Handler.Handle(message, handlerContext); await Handler.Handle(message, handlerContext); Assert.AreEqual(2, Dispatcher.DispatchedMessages.Count); }
public async Task HandleOrderBilledMessageCorrectly() { AssumeSagaCanBeMatched(); var context = new TestableMessageHandlerContext(); var message = new OrderBilled { OrderId = _orderId, }; await _target.Handle(message, context); await _orderHubMessageDispatcher.Received().SendToGroupAsync(UserId, "StatusUpdated", Arg.Is <OrderStatus>(s => s.OrderId == message.OrderId && s.Status == "Order Billed")); }
public override void Validate(TestableMessageHandlerContext context) { if (saga.Completed == expectCompleted) { return; } if (saga.Completed) { Fail("Expected saga to not be completed but the saga was completed."); } Fail("Expected saga to be completed but the saga was not completed."); }
public async Task Should_dispatch_message_using_incoming_transaction() { var failedMessage = await CreateFailedMessage(); var message = CreateEditMessage(failedMessage.UniqueMessageId); var handlerContent = new TestableMessageHandlerContext(); var transportTransaction = new TransportTransaction(); handlerContent.Extensions.Set(transportTransaction); await Handler.Handle(message, handlerContent); Assert.AreSame(Dispatcher.DispatchedMessages.Single().Item2, transportTransaction); }
public async Task Handle_WhenHandlingCommand_ThenShouldAddMessageIdToDistributedCache( [Frozen] Mock <IDistributedCache> distributedCache, RunHealthCheckCommandHandler handler, RunHealthCheckCommand message, TestableMessageHandlerContext context) { //arrange var stringValue = System.Text.Encoding.UTF8.GetBytes("OK"); //act await handler.Handle(message, context); //assert distributedCache.Verify(c => c.SetAsync(context.MessageId, stringValue, It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()), Times.Once, "Cache Method not Called"); }
public void Setup() { saga = new BookingChangePolicy { Data = new BookingChangePolicyData() }; context = new TestableMessageHandlerContext(); bookedFlightWasChanged = new BookedFlightWasChanged { BookingReferenceId = bookingReferenceId, FlightNumber = "UA890", ReasonForChange = "Aircraft type was changed from Boeing 787 to Boeing 777" }; }
public async Task TestIncomingAttachment() { //Arrange var context = new TestableMessageHandlerContext(); var handler = new Handler(); var mockMessageAttachments = new CustomMockMessageAttachments(); context.InjectAttachmentsInstance(mockMessageAttachments); //Act await handler.Handle(new MyMessage(), context); //Assert Assert.True(mockMessageAttachments.GetBytesWasCalled); }
public async Task Shares_state_with_handler_context() { var handlerContext = new TestableMessageHandlerContext(); var uniformSession = new TestableUniformSession(handlerContext); var handler = new SendingHandler(uniformSession); await handler.Handle(new SomeCommand(), handlerContext); Assert.AreEqual(2, uniformSession.PublishedMessages.Length); Assert.AreEqual(2, uniformSession.SentMessages.Length); Assert.AreEqual(2, handlerContext.PublishedMessages.Length); Assert.AreEqual(2, handlerContext.SentMessages.Length); Assert.IsTrue(handlerContext.DoNotContinueDispatchingCurrentMessageToHandlersWasCalled); }
public async Task OutgoingAttachments() { var context = new TestableMessageHandlerContext(); var handler = new OutgoingAttachmentsHandler(); await handler.Handle(new AMessage(), context); var attachments = context.SentMessages .Single() .Options .Attachments(); var names = attachments.Names; Assert.Single(names); Assert.Contains("theName", names); Assert.True(attachments.HasPendingAttachments); }
public async Task ExpectTimeoutFails_WithNewTestingFramework() { var saga = new TestSaga { Data = new MySagaData { Id = new Guid("11111111-1111-1111-1111-111111111111") } }; var executeOn = 31.January(2019).At(10, 35).AsLocal(); var context = new TestableMessageHandlerContext(); await saga.Handle(new StartSagaCommand { Id = new Guid("22222222-2222-2222-2222-222222222222"), ExecutionTime = executeOn }, context).ConfigureAwait(false); var sentMessage = context.SentMessages.SingleOrDefault(); sentMessage.Message <TimeoutData>().Time.Should().Be(executeOn); }
public async Task Logging() { var handler = new MyHandlerWithLogging(); var context = new TestableMessageHandlerContext(); context.Extensions.Set("key", "value"); await handler.Handle(new(), context); await Verify( new { context, LogCapture.LogMessages }); }
public async Task Saga() { var saga = new MySaga { Data = new() }; var context = new TestableMessageHandlerContext(); await saga.Handle(new(), context); await Verify(new { context, saga.Data }); }
public async void Setup() { var dbContext = new OrderDbContext() { Orders = Aef.FakeDbSet(orders) }; placedAtDate = DateTime.UtcNow; orderId = new Guid("DE81F6B5-7F29-4AE7-A72B-023F6B58DE72"); var placeOrderCommand = new PlaceOrderCommand { OrderId = orderId, OrderNumber = 100, PlacedAtDate = placedAtDate }; var context = new TestableMessageHandlerContext(); //TODO: Question? How do you test this, since I cannot inject the OrderDbContext into the handler //In the handler there is the context.SynchronizedStorageSession.FromCurrentSession() that returns a new OrderDbContext //In V5 we did new PlaceOrderCommandHandler(OrderDbContext dbContext); and then we could use the FakeDbSet. //Since I could not use Moq to mock the return value of context.SynchronizedStorageSession.FromCurrentSession() since it is an extension method //so I created a OrderStorageContext instead //Then I realized that U guys have your own TestingFramework that I installed so that I could get a TestableMessageHandlerContext //but cannot find a way to set the session.SqlPersistenceSession(); var orderStorageContextMock = new Mock <IDbContextWrapper <OrderDbContext> >(); orderStorageContextMock.SetupIgnoreArgs(x => x.GetDbContext(null)).Returns(dbContext); handler = new PlaceOrderCommandHandler(orderStorageContextMock.Object); try { await handler.Handle(placeOrderCommand, context) .ConfigureAwait(false); await dbContext.SaveChangesAsync() .ConfigureAwait(false); } catch (Exception e) { Console.WriteLine(e); throw; } }
public void SetUp() { _messageHandlerContext = new TestableMessageHandlerContext(); _mediatorMock = new Mock <IMediator>(); _loggerMock = new Mock <ILog>(); Fixture.Customize <Account>(x => x.Without(s => s.AccountLegalEntities)); _mediatorMock.Setup(mock => mock.SendAsync(It.IsAny <GetAllEmployerAccountsRequest>())) .ReturnsAsync(new GetAllEmployerAccountsResponse { Accounts = new List <Account> { Fixture.Create <Account>() } }); _sut = new ProcessPeriodEndPaymentsCommandHandler(_mediatorMock.Object, _loggerMock.Object); }
public async Task Handle_WhenHandlingAddedPayeSchemeEvent_ThenShouldSendUpsertUserCommand( TestableMessageHandlerContext context, [Frozen] Mock <IMediator> mediator, AddedAccountProviderEventHandler handler, UpsertedUserEvent message) { //arrange //act await handler.Handle(message, context); //assert mediator.Verify(s => s.Send(It.Is <UpsertUserCommand>(c => c.Created == message.Created && c.CorrelationId == message.CorrelationId && c.UserRef == message.UserRef), It.IsAny <CancellationToken>())); }
public async Task CustomizationHandler() { var testableContext = new TestableMessageHandlerContext(); var handler = new MyHandlerUsingCustomizations(); await handler.Handle(new MyEvent(), testableContext); var publishedMessage = testableContext.PublishedMessages.Single(); var customization = publishedMessage.Options.GetNativeMessageCustomization(testableContext); var nativeMessage = new Message(); customization(nativeMessage); Assert.AreEqual("abc", nativeMessage.Label); }
public async Task HandleTest() { var handler = new Handlers.P2pWorkflowStartedHandler("Data Source=.;Initial Catalog=PdpDb;Integrated Security=True;"); var context = new TestableMessageHandlerContext(); var message = new P2pWorkflowStarted() { WorkflowId = Guid.NewGuid() }; await handler.Handle(message, context); var publishedMessages = context.PublishedMessages; handler.ShouldSatisfyAllConditions(() => { publishedMessages.Containing <P2pPolled>().Any(t => t.Message.WorkflowId == message.WorkflowId && t.Message.Customers != null).ShouldBe(true); }); }
public async Task GetNativeMessageCustomization_should_return_customization() { var testableContext = new TestableMessageHandlerContext(); var handler = new MyHandlerUsingCustomizations(); await handler.Handle(new MyMessage(), testableContext); var publishedMessage = testableContext.PublishedMessages.Single(); var customization = publishedMessage.Options.GetNativeMessageCustomization(); var nativeMessage = new ServiceBusMessage(); customization(nativeMessage); Assert.AreEqual("abc", nativeMessage.Subject); }
public void HandleCurrentMessageLater_WhenCalled_ShouldIndicateInvocation() { var context = new TestableMessageHandlerContext(); context.HandleCurrentMessageLater(); Assert.IsTrue(context.HandleCurrentMessageLaterWasCalled); }
public void ShouldAllowSettingMessageProperties() { var context = new TestableMessageHandlerContext(); context.MessageId = "custom message id"; context.ReplyToAddress = "custom reply address"; context.MessageHeaders = new Dictionary<string, string>(); context.MessageHeaders.Add("custom header", "custom value"); context.Extensions = new ContextBag(); }
public void DoNotContinueDispatchingCurrentMessageToHandlers_WhenNotCalled_ShouldNotIndicateInvocation() { var context = new TestableMessageHandlerContext(); Assert.IsFalse(context.DoNotContinueDispatchingCurrentMessageToHandlersWasCalled); }