Esempio n. 1
0
        public async Task ShouldSendResponseToBrokerWhenUserJwtIsValid()
        {
            object expectedErrors = null;
            Guid   expectedBody   = Guid.Empty;

            await harness.Start();

            try
            {
                var requestClient = await harness.ConnectRequestClient <ICheckTokenRequest>();

                var response = await requestClient.GetResponse <IOperationResult <Guid> >(new
                {
                    UserJwt = userJwt
                });

                Assert.IsTrue(response.Message.IsSuccess);
                Assert.AreEqual(expectedErrors, response.Message.Errors);
                Assert.AreEqual(expectedBody, response.Message.Body);
                Assert.IsTrue(consumerTestHarness.Consumed.Select <ICheckTokenRequest>().Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task ShouldRetry_WhenMessageRetryIsUsed()
        {
            try
            {
                var testActivity = new ActivityTestContext <FirstFaultyActivity, FaultyArguments, FaultyLog>(
                    harness,
                    () => new FirstFaultyActivity(),
                    null,
                    null);
                harness.OnConfigureBus += bus => bus.UseMessageRetry(r => r.Immediate(2));

                await harness.Start();

                var routingSlipCompletedHandler = ConnectPublishHandler <RoutingSlipCompleted>(harness);

                var builder = new RoutingSlipBuilder(Guid.NewGuid());
                builder.AddActivity(testActivity.Name, testActivity.ExecuteUri, new { });
                await harness.Bus.Execute(builder.Build());

                await routingSlipCompletedHandler;
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_respond_with_rejected_if_customer_is_test()
        {
            var harness = new InMemoryTestHarness();
            ConsumerTestHarness <SubmitOrderConsumer> consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                Guid orderId = NewId.NextGuid();

                IRequestClient <SubmitOrder> requestClient = await harness.ConnectRequestClient <SubmitOrder>();

                Response <OrderSubmissionRejected> response = await requestClient.GetResponse <OrderSubmissionRejected>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "TEST12345"
                });

                // assert
                response.Message.OrderId.Should().Be(orderId);
                consumer.Consumed.Select <SubmitOrder>().Should().NotBeNullOrEmpty();
                harness.Sent.Select <OrderSubmissionRejected>().Should().NotBeNullOrEmpty();
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_publish_order_submitted_event()
        {
            var harness = new InMemoryTestHarness();
            ConsumerTestHarness <SubmitOrderConsumer> consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                Guid orderId = NewId.NextGuid();

                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                harness.Published.Select <OrderSubmitted>().Should().NotBeNullOrEmpty();
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 5
0
        public async Task Should_generate_a_graph_of_the_message_flow()
        {
            var harness = new InMemoryTestHarness
            {
                TestTimeout           = TimeSpan.FromSeconds(2),
                TestInactivityTimeout = TimeSpan.FromSeconds(2)
            };

            harness.Consumer(() => new AFooConsumer());
            harness.Consumer(() => new BFooConsumer());
            harness.Consumer(() => new CFooConsumer());
            harness.Consumer(() => new DFooConsumer());
            harness.Consumer(() => new EFooConsumer());

            EndpointConvention.Map <EFoo>(harness.InputQueueAddress);

            await harness.Start();

            await harness.Bus.Publish <AFoo>(new { InVar.CorrelationId });

            await harness.Bus.Publish <BFoo>(new { InVar.CorrelationId });

            await harness.OutputTimeline(TestContext.Out, options => options.IncludeAddress());

            await harness.Stop();
        }
        public async Task Test_thing()
        {
            var harness = new InMemoryTestHarness();

            harness.OnConfigureInMemoryBus += Harness_OnConfigureInMemoryBus;
            var saga     = harness.StateMachineSaga(new TestSagaStateMachine(), new InMemorySagaRepository <TestSagaState>(), "saga");
            var consumer = harness.Consumer <TestConsumer>("consumer");

            await harness.Start();

            try
            {
                var values   = Enumerable.Range(0, 16).Select(i => Guid.NewGuid()).ToArray();
                var response = await harness.Bus.Request <TestSagaRequest, TestSagaResponse>(new TestSagaRequest()
                {
                    CorrelationId = Guid.NewGuid(), Values = values
                });

                response.Message.Values.Should().HaveCount(16);
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task CreateAsync_Should_Publish_Event_Successfully()
        {
            //Arrange
            var context = Context;

            var harness = new InMemoryTestHarness();

            await harness.Start();

            IOfficeBusiness officeBusiness = new OfficeBusiness(context,
                                                                _mapper,
                                                                _cache,
                                                                harness.Bus);

            CreateOfficeCommand command = new CreateOfficeCommand
            {
                Location  = "Amsterdam",
                OpenTime  = DateTime.Now.TimeOfDay,
                CloseTime = DateTime.Now.AddHours(1).TimeOfDay
            };

            //Act
            await officeBusiness.CreateAsync(command);

            //Assert
            try
            {
                Assert.True(await harness.Published.Any <OfficeCreated>());
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 8
0
        public async Task BuildingFlowGraph_ShouldBuild()
        {
            EndpointConvention.Map <EFoo>(new Uri("queue:input-queue"));

            var harness = new InMemoryTestHarness()
            {
                TestTimeout = TimeSpan.FromSeconds(1)
            };

            harness.Consumer(() => new AFooConsumer());
            harness.Consumer(() => new BFooConsumer());
            harness.Consumer(() => new CFooConsumer());
            harness.Consumer(() => new DFooConsumer());
            harness.Consumer(() => new EFooConsumer());

            await harness.Start();

            await harness.Bus.Publish <AFoo>(new {
                CorrelationId = Guid.NewGuid()
            });

            await harness.Bus.Publish <BFoo>(new {
                CorrelationId = Guid.NewGuid()
            });

            var graph = await GraphGenerator.Generate(harness);

            var converstationGraphs = string.Join(Environment.NewLine,
                                                  graph.Select(StringGraphRenderer.Render));

            await harness.Stop();

            this.Assent(converstationGraphs);
        }
Esempio n. 9
0
        public async Task Should_handle_the_stop_state()
        {
            var harness = new InMemoryTestHarness();
            StateMachineSagaTestHarness <Instance, TestStateMachine> saga = harness.StateMachineSaga <Instance, TestStateMachine>(_machine);

            var sagaId = Guid.NewGuid();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send(new Start { CorrelationId = sagaId });

                await harness.InputQueueSendEndpoint.Send(new Stop { CorrelationId = sagaId });

                Assert.IsTrue(harness.Consumed.Select <Start>().Any(), "Start not received");
                Assert.IsTrue(harness.Consumed.Select <Stop>().Any(), "Stop not received");

                var instance = saga.Created.ContainsInState(sagaId, _machine, _machine.Final);
                Assert.IsNotNull(instance, "Saga instance not found");
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 10
0
        public async Task Should_publish_the_completed_event()
        {
            _harness = new InMemoryTestHarness();

            _activity = _harness.Activity <TestActivity, TestArguments, TestLog>();

            await _harness.Start();

            _completed         = _harness.SubscribeHandler <RoutingSlipCompleted>();
            _activityCompleted = _harness.SubscribeHandler <RoutingSlipActivityCompleted>();

            _trackingNumber = NewId.NextGuid();
            var builder = new RoutingSlipBuilder(_trackingNumber);

            builder.AddSubscription(_harness.BusAddress, RoutingSlipEvents.All);

            builder.AddActivity(_activity.Name, _activity.ExecuteAddress, new
            {
                Value = "Hello"
            });

            builder.AddVariable("Variable", "Knife");

            await _harness.Bus.Execute(builder.Build());

            await _completed;
        }
Esempio n. 11
0
        public async Task Should_insert_new_state_instance_on_submitted()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            var saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <IOrderSubmitted>(new
                {
                    OrderId         = orderId,
                    ExternalOrderId = "00000001"
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                var instance = saga.Sagas.Contains(instanceId.Value);
                Assert.That(instance.ExternalOrderId, Is.EqualTo("00000001"));
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_create_a_state_instance()
        {
            var harness = new InMemoryTestHarness();
            StateMachineSagaTestHarness <OrderState, OrderStateMachine> saga = harness.StateMachineSaga <OrderState, OrderStateMachine>(new OrderStateMachine());

            await harness.Start();

            try
            {
                Guid orderId = NewId.NextGuid();

                await harness.Bus.Publish <OrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Guid?instanceId = await saga.Exists(orderId, x => x.Submitted);

                instanceId.Should().Be(orderId);

                OrderState instance = saga.Sagas.Contains(instanceId.Value);
                instance.CustomerNumber.Should().Be("12345");
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_Test_ExecutePubmedSearchConsumer()
        {
            //Arrange
            var pubmedWebClient = new Mock <IPubmedWebClient>();
            var mockFileService = new Mock <IFileService>();
            var mockUnitOfWork  = new Mock <ILsUnitOfWork>();
            var pubmedService   = new PubmedService(pubmedWebClient.Object, mockFileService.Object, mockUnitOfWork.Object);

            var harness         = new InMemoryTestHarness();
            var consumerHarness =
                harness.Consumer(() => new ExecutePubmedSearchConsumer(pubmedService));

            //Act
            await harness.Start();

            //Assert
            try
            {
                await harness.InputQueueSendEndpoint.Send <IExecutePubmedSearchCommand>(new
                {
                    ProjectId      = default(Guid),
                    LivingSearchId = default(Guid),
                    SearchTerm     = default(String),
                    BatchSize      = default(Int32)
                });

                Assert.True(harness.Consumed.Select <IExecutePubmedSearchCommand>().Any());
                Assert.True(consumerHarness.Consumed.Select <IExecutePubmedSearchCommand>().Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_Test_ExecuteBioRxivSearchConsumer()
        {
            //Arrange
            var mockBiorxivService = new Mock <IBiorxivService>();

            var harness         = new InMemoryTestHarness();
            var consumerHarness =
                harness.Consumer(() => new ExecuteBiorxivSearchConsumer(mockBiorxivService.Object));

            //Act
            await harness.Start();

            //Assert
            try
            {
                await harness.InputQueueSendEndpoint.Send <IExecuteBiorxivCovidFeedSearchCommand>(new
                {
                    ProjectId       = default(Guid),
                    BiorxivSearchId = default(Guid),
                    BatchSize       = default(Int32),
                    FileUri         = default(string)
                });

                Assert.True(harness.Consumed.Select <IExecuteBiorxivCovidFeedSearchCommand>().Any());
                Assert.True(consumerHarness.Consumed.Select <IExecuteBiorxivCovidFeedSearchCommand>().Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task FixtureSetUp()
        {
            _fixture         = new Fixture();
            _repoMock        = new Mock <ISightingRepository <StubReportedSighting> >();
            _protoTranslator = new Mock <IProtocolTranslator>();
            _repertoir       = new Mock <ISightingAnalyzerRepertoire>();
            _routeRegistry   = new Mock <IRouteRegistry>();
            _harness         = new InMemoryTestHarness();
            _consumer        = _harness.Consumer(() => new SightingInvestigationConsumer <StubReportedSighting>(
                                                     _repoMock.Object, _protoTranslator.Object,
                                                     _repertoir.Object, _routeRegistry.Object));

            var ev = _fixture.Create <NewSightingReported>();
            var chiefInvestigatorQ = new Uri("mq://chiefInspectorJapp");
            var dbRecord           = new StubReportedSighting();
            var investigateCommand = new InvestigateSighting {
                Origin = "meh"
            };

            _repertoir.Setup(e => e.All()).Returns(new[] { new RiggedAnalyzer(true), new RiggedAnalyzer(false) });

            _routeRegistry.Setup(e => e.For <InvestigateSighting>()).Returns(chiefInvestigatorQ);
            _protoTranslator.Setup(e => e.TranslateToRecord <StubReportedSighting>(It.IsAny <NewSightingReported>(), It.Is <IAnalysisResults[]>(p => p.Length == 2)))
            .Returns(dbRecord);
            _protoTranslator.Setup(e => e.Translate(It.IsAny <NewSightingReported>(), It.Is <IAnalysisResults[]>(p => p.All(x => x.IsSuspicious))))
            .Returns(investigateCommand);
            _repoMock.Setup(e => e.Add(dbRecord)).Returns(dbRecord);

            await _harness.Start();

            await _harness.InputQueueSendEndpoint.Send(ev);
        }
        public async Task Should_create_a_state_instance()
        {
            var orderStateMachine = new OrderStateMachine();

            var harness = new InMemoryTestHarness();
            var saga    = harness.StateMachineSaga <OrderState, OrderStateMachine>(orderStateMachine);

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.Bus.Publish <IOrderSubmitted>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                Assert.That(saga.Created.Select(x => x.CorrelationId == orderId).Any(), Is.True);

                var instanceId = await saga.Exists(orderId, x => x.Submitted);

                Assert.That(instanceId, Is.Not.Null);

                var instance = saga.Sagas.Contains(instanceId.Value);
                Assert.That(instance.CustomerNumber, Is.EqualTo("12345"));
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 17
0
        public async Task Should_test_the_consumer()
        {
            var harness             = new InMemoryTestHarness("amqp://rabbitmq");
            var consumerTestHarness = harness.Consumer <EventCreatedConsumer>();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send <EventCreated>(new
                {
                    Id   = "1234",
                    Name = "Testing EventConsumer"
                });

                // did the endpoint consume the message
                Assert.IsTrue(harness.Consumed.Select <EventCreated>().Any());

                // did the actual consumer consume the message
                Assert.IsTrue(consumerTestHarness.Consumed.Select <EventCreated>().Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 18
0
        public async Task InitializeAsync()
        {
            InterceptQuartzSystemTime();

            var collection = new ServiceCollection()
                             .AddMassTransitInMemoryTestHarness(cfg =>
            {
                cfg.AddSagaStateMachine <TStateMachine, TInstance>().InMemoryRepository();
                cfg.AddPublishMessageScheduler();
                cfg.AddSagaStateMachineTestHarness <TStateMachine, TInstance>();

                ConfigureMassTransit(cfg);
            });

            Provider = collection.BuildServiceProvider(true);
            ConfigureService(collection);

            TestHarness = Provider.GetRequiredService <InMemoryTestHarness>();
            TestHarness.OnConfigureInMemoryBus += configurator =>
            {
                var nvc = new NameValueCollection {
                    ["quartz.scheduler.instanceName"] = Guid.NewGuid().ToString()
                };
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory(nvc);
                configurator.UseInMemoryScheduler(schedulerFactory, out _scheduler);

                // Use only this cause Exception: Scheduler with name 'DefaultQuartzScheduler' already exists!
                //configurator.UseInMemoryScheduler(out _scheduler);
            };
            await TestHarness.Start();

            SagaHarness = Provider.GetRequiredService <IStateMachineSagaTestHarness <TInstance, TStateMachine> >();
            Machine     = Provider.GetRequiredService <TStateMachine>();
        }
        public async Task A_consumer_is_being_tested()
        {
            _harness = new InMemoryTestHarness();
            _fakeConsumerTestHarness = _harness.Consumer(() => new FakeFailureConsumer());

            _personSearchObserver       = new Mock <ILogger <PersonSearchObserver> >();
            _providerProfileOptiosnMock = new Mock <IOptions <ProviderProfileOptions> >();

            _providerProfileOptiosnMock.Setup(x => x.Value).Returns(new ProviderProfileOptions()
            {
                Name = "Adapter Tester"
            });

            await _harness.Start();

            _harness.Bus.ConnectConsumeMessageObserver(new PersonSearchObserver(_providerProfileOptiosnMock.Object,
                                                                                _personSearchObserver.Object));

            await _harness.BusControl.Publish <PersonSearchOrdered>(new PersonSearchOrderedTest()
            {
                SearchRequestId = Guid.NewGuid(),
                TimeStamp       = DateTime.Now,
                Person          = new Person()
                {
                    FirstName   = "",
                    LastName    = "lastName",
                    DateOfBirth = new DateTime(2001, 1, 1)
                }
            });
        }
        public async Task Should_publish_the_order_submitted_event()
        {
            var harness         = new InMemoryTestHarness();
            var consumerHarness = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId = InVar.Id
                });

                // did the endpoint consume the message
                Assert.That(await harness.Consumed.Any <SubmitOrder>());

                // did the actual consumer consume the message
                Assert.That(await consumerHarness.Consumed.Any <SubmitOrder>());

                // the consumer publish the event
                Assert.That(await harness.Published.Any <OrderSubmitted>());

                // ensure that no faults were published by the consumer
                Assert.That(await harness.Published.Any <Fault <SubmitOrder> >(), Is.False);
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 21
0
        public async Task should_handle_the_initial_state()
        {
            var harness = new InMemoryTestHarness();

            _machine = new InvestigationStateMachine(new List <Provider>());

            StateMachineSagaTestHarness <Investigation, InvestigationStateMachine> saga = harness.StateMachineSaga <Investigation, InvestigationStateMachine>(_machine);


            await harness.Start();

            var searchRequestedEvent = SearchRequested.Create(new PeopleSearchRequest("test", "test", "test"));

            try
            {
                await harness.InputQueueSendEndpoint.Send(searchRequestedEvent);

                Assert.IsTrue(harness.Consumed.Select <SearchRequested>().Any(), "Message not received");

                Investigation instance = saga.Created.Select(x => x.CorrelationId == searchRequestedEvent.CorrelationId)
                                         .FirstOrDefault()
                                         ?.Saga;
                Assert.IsNotNull(instance, "Saga instance not found");

                Assert.AreEqual(instance.CurrentState, nameof(_machine.Started));
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 22
0
        public async Task Should_create_a_state_instance()
        {
            // Arrange (Given)
            var harness = new InMemoryTestHarness();
            var fileHandlerStateMachine = new FileHandlerStateMachine();
            var saga = harness.StateMachineSaga <FileHandlerState, FileHandlerStateMachine>(fileHandlerStateMachine);

            await harness.Start();

            try
            {
                var fileId = NewId.NextGuid();

                await harness.Bus.Publish <FileInfoSubmitted>(new
                {
                    FileId    = fileId,
                    Timestamp = InVar.Timestamp,
                    FileName  = "filename.file",
                    Folder    = "c:/folder/"
                });

                var instanceID = await saga.Exists(fileId, x => x.Submitted);

                var instance = saga.Sagas.Contains(instanceID.Value);

                Assert.NotNull(instanceID);
                Assert.True(saga.Created.Select(x => x.CorrelationId == fileId).Any());
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 23
0
        public async Task Send_message_to_test_consumer()
        {
            // add migrations by calling
            // dotnet ef migrations add --context auditdbcontext --output-dir Migrations\\Audit audit_init
            DbContextOptionsBuilder <AuditDbContext> optionsBuilder = new DbContextOptionsBuilder <AuditDbContext>().
                                                                      UseSqlServer(LocalDbConnectionStringProvider.GetLocalDbConnectionString(),
                                                                                   m =>
            {
                var executingAssembly = typeof(ContextFactory).GetTypeInfo().Assembly;

                m.MigrationsAssembly(executingAssembly.GetName().Name);
                m.MigrationsHistoryTable("__AuditEFMigrationHistoryAudit");
            });

            _store = new EntityFrameworkAuditStore(optionsBuilder.Options, "EfCoreAudit");
            using (var dbContext = _store.AuditContext)
            {
                await dbContext.Database.MigrateAsync();

                await dbContext.Database.ExecuteSqlCommandAsync("TRUNCATE TABLE EfCoreAudit");
            }

            _harness = new InMemoryTestHarness();
            _harness.OnConnectObservers += bus =>
            {
                bus.ConnectSendAuditObservers(_store);
                bus.ConnectConsumeAuditObserver(_store);
            };
            _harness.Consumer <TestConsumer>();

            await _harness.Start();

            await _harness.InputQueueSendEndpoint.Send(new A());
        }
Esempio n. 24
0
        public async Task Setup()
        {
            var collection = new ServiceCollection()
                             .AddSingleton <ILoggerFactory>(_ => new TestOutputLoggerFactory(true))
                             .AddSingleton(typeof(ILogger <>), typeof(Logger <>))
                             .AddMassTransitInMemoryTestHarness(cfg =>
            {
                cfg.AddSagaRepository <FutureState>()
                .InMemoryRepository();

                cfg.ApplyCustomMassTransitConfiguration();

                ConfigureMassTransit(cfg);
            });

            ConfigureServices(collection);

            Provider = collection.BuildServiceProvider(true);

            ConfigureLogging();

            TestHarness = Provider.GetRequiredService <InMemoryTestHarness>();
            TestHarness.OnConfigureInMemoryBus += configurator =>
            {
                configurator.ApplyCustomBusConfiguration();

                ConfigureInMemoryBus(configurator);
            };

            await TestHarness.Start();
        }
Esempio n. 25
0
        public async Task Should_Consume_TransactionCheckCommand()
        {
            var harness         = new InMemoryTestHarness();
            var consumerHarness = harness.Consumer <BillingsSubscriptionsHandler>();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send(new TransactionCheckCommand
                {
                    Id        = Guid.NewGuid().ToString(),
                    ProfileId = Guid.NewGuid().ToString()
                });

                // did the endpoint consume the message
                Assert.True(await harness.Consumed.Any <TransactionCheckCommand>());

                // did the actual consumer consume the message
                Assert.True(await consumerHarness.Consumed.Any <TransactionCheckCommand>());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public void Register(IObjectContainer objectContainer)
        {
            objectContainer.RegisterInstanceAs(Mock.Of <IServiceProvider>());
            objectContainer.RegisterInstanceAs(Mock.Of <IObjectStorage>());
            objectContainer.RegisterTypeAs <JsonObjectSerializer, IObjectSerializer>();
            objectContainer.RegisterTypeAs <GroupTransactionExecutionService, IGroupTransactionExecutionService>();
            RegisterHandlers(objectContainer);

            objectContainer.RegisterInstanceAs <ICache>(new InMemoryCache());
            objectContainer.RegisterTypeAs <MessageTypeService, IMessageTypeService>();

            InMemoryTestHarness bus = new InMemoryTestHarness();

            bus.AddConsumer <IGroupTransactionEvent>(objectContainer);
            bus.AddConsumer <IMockEventOne>(objectContainer);
            bus.AddConsumer <IMockEventTwo>(objectContainer);
            bus.AddConsumer <IMockEventThree>(objectContainer);
            bus.AddConsumer <IMockEventFour>(objectContainer);

            bus.Start().GetAwaiter().GetResult();
            objectContainer.RegisterInstanceAs <InMemoryTestHarness>(bus);
            objectContainer.RegisterInstanceAs <IServiceBus>(new ServiceBus(
                                                                 bus.BusControl,
                                                                 Mock.Of <IContractValidatorService>(),
                                                                 objectContainer.Resolve <IBigMessageService>(),
                                                                 objectContainer.Resolve <ObjectStorageConfiguration>()));
        }
        public async Task Should_not_publish_order_submitted_event_when_rejected()
        {
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            ConsumerTestHarness <SubmitOrderConsumer> consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "TEST12345"
                });

                harness.Published.Select <OrderSubmitted>().Should().BeEmpty();
            }
            finally
            {
                await harness.Stop();
            }
        }
Esempio n. 28
0
        public async Task Should_keep_em_separated()
        {
            var internalHarness = new InMemoryTestHarness("internal");
            var externalHarness = new InMemoryTestHarness("external");

            ConsumerTestHarness <RelayConsumer> internalConsumer = internalHarness.Consumer(() => new RelayConsumer(externalHarness.Bus));
            ConsumerTestHarness <RelayConsumer> externalConsumer = externalHarness.Consumer(() => new RelayConsumer(internalHarness.Bus));

            ConsumerTestHarness <RealConsumer> realConsumer = internalHarness.Consumer <RealConsumer>();

            await internalHarness.Start();

            try
            {
                await externalHarness.Start();

                try
                {
                    await externalHarness.Bus.Publish(new A());

                    realConsumer.Consumed.Select <A>().Any().ShouldBeTrue();
                }
                finally
                {
                    await externalHarness.Stop();
                }
            }
            finally
            {
                await internalHarness.Stop();
            }
        }
        public async Task Should_consume_submit_order_commands()
        {
            var harness = new InMemoryTestHarness {
                TestTimeout = TimeSpan.FromSeconds(5)
            };
            ConsumerTestHarness <SubmitOrderConsumer> consumer = harness.Consumer <SubmitOrderConsumer>();

            await harness.Start();

            try
            {
                var orderId = NewId.NextGuid();

                await harness.InputQueueSendEndpoint.Send <SubmitOrder>(new
                {
                    OrderId = orderId,
                    InVar.Timestamp,
                    CustomerNumber = "12345"
                });

                consumer.Consumed.Select <SubmitOrder>().Should().NotBeNullOrEmpty();
                harness.Sent.Select <OrderSubmissionAccepted>().Should().BeEmpty(); // because we do not set a RequestId when not using a request client
                harness.Sent.Select <OrderSubmissionRejected>().Should().BeEmpty();
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_Consume_AccountIsCheckedEvent()
        {
            var harness         = new InMemoryTestHarness();
            var consumerHarness = harness.Consumer <AccountsSubscriptionsHandler>();

            await harness.Start();

            try
            {
                await harness.InputQueueSendEndpoint.Send(new AccountIsCheckedEvent
                {
                    ProfileId = Guid.NewGuid().ToString()
                });

                // did the endpoint consume the message
                Assert.True(await harness.Consumed.Any <AccountIsCheckedEvent>());

                // did the actual consumer consume the message
                Assert.True(await consumerHarness.Consumed.Any <AccountIsCheckedEvent>());
            }
            finally
            {
                await harness.Stop();
            }
        }