Skip to content

Commit

Permalink
Adding tests for publish strategies
Browse files Browse the repository at this point in the history
  • Loading branch information
jbogard committed Feb 14, 2023
1 parent 40afa9f commit 9da86cd
Showing 1 changed file with 78 additions and 2 deletions.
80 changes: 78 additions & 2 deletions test/MediatR.Tests/NotificationPublisherTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,82 @@
namespace MediatR.Tests;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using MediatR.NotificationPublishers;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using Xunit.Abstractions;

namespace MediatR.Tests;

public class NotificationPublisherTests
{

private readonly ITestOutputHelper _output;

public NotificationPublisherTests(ITestOutputHelper output) => _output = output;

public class Notification : INotification
{
}

public class FirstHandler : INotificationHandler<Notification>
{
public async Task Handle(Notification notification, CancellationToken cancellationToken)
=> await Task.Delay(500, cancellationToken);
}
public class SecondHandler : INotificationHandler<Notification>
{
public async Task Handle(Notification notification, CancellationToken cancellationToken)
=> await Task.Delay(250, cancellationToken);
}

[Fact]
public async Task Should_handle_sequentially_by_default()
{
var services = new ServiceCollection();
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<Notification>();
});
var serviceProvider = services.BuildServiceProvider();

var mediator = serviceProvider.GetRequiredService<IMediator>();

var timer = new Stopwatch();
timer.Start();

await mediator.Publish(new Notification());

timer.Stop();

timer.ElapsedMilliseconds.ShouldBeGreaterThan(750);

_output.WriteLine(timer.ElapsedMilliseconds.ToString());
}


[Fact]
public async Task Should_handle_in_parallel_with_when_all()
{
var services = new ServiceCollection();
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<Notification>();
cfg.NotificationPublisherType = typeof(TaskWhenAllPublisher);
});
var serviceProvider = services.BuildServiceProvider();

var mediator = serviceProvider.GetRequiredService<IMediator>();

var timer = new Stopwatch();
timer.Start();

await mediator.Publish(new Notification());

timer.Stop();

timer.ElapsedMilliseconds.ShouldBeLessThan(750);

_output.WriteLine(timer.ElapsedMilliseconds.ToString());
}
}

0 comments on commit 9da86cd

Please sign in to comment.