Skip to content

Instantly share code, notes, and snippets.

@mikebridge
Created June 7, 2017 19:39
Show Gist options
  • Save mikebridge/a468735c966ea062487199cded301d1c to your computer and use it in GitHub Desktop.
Save mikebridge/a468735c966ea062487199cded301d1c to your computer and use it in GitHub Desktop.
xUnit tests for EventAggregator.cs
using System;
using System.Collections.Generic;
using Xunit;
// Tests for EventAggregator.cs (https://gist.github.com/mikebridge/f6799ebed20160f72a3daf62f584d2ff)
namespace Messaging.Tests.Unit
{
public class EventAggregatorTests : IDisposable
{
readonly IEventAggregator _hub;
readonly List<TestEvent> _receivedEvents1;
readonly List<TestEvent> _receivedEvents2;
public EventHubTests()
{
_hub = new EventAggregator();
_receivedEvents1 = new List<TestEvent>();
_receivedEvents2 = new List<TestEvent>();
}
public void Dispose()
{
}
[Fact]
public void It_Should_Publish_An_Event_To_A_Subscriber()
{
// Arrange
TestEvent receivedEvent = null;
void Handler(TestEvent e) => receivedEvent = e;
// Act
_hub.Subscribe((Action<TestEvent>)Handler); // C# 7
_hub.Publish(new TestEvent("hello"));
// Assert
Assert.NotNull(receivedEvent);
}
[Fact]
public void It_Should_Publish_To_Multiple_Subscribers()
{
// Arrange
_hub.Subscribe((TestEvent e) => _receivedEvents1.Add(e));
// Act
_hub.Publish(new TestEvent("hello 1"));
_hub.Publish(new TestEvent("hello 2"));
// Assert
Assert.Equal(2, _receivedEvents1.Count);
}
[Fact]
public void A_Subscriber_Should_Not_Receive_Events_Of_A_Different_Type()
{
// Arrange
_hub.Subscribe((TestEvent e) => _receivedEvents1.Add(e));
_hub.Subscribe((String e) => { });
// Act
_hub.Publish("hello 1");
_hub.Publish(new TestEvent("hello 2"));
// Assert
Assert.Equal(1, _receivedEvents1.Count);
}
[Fact]
public void Multiple_Subscribers_Can_Receive_One_Published_Event()
{
// Arrange
_hub.Subscribe((TestEvent e) => _receivedEvents1.Add(e));
_hub.Subscribe((TestEvent e) => _receivedEvents2.Add(e));
// Act
_hub.Publish(new TestEvent("hello 1"));
_hub.Publish(new TestEvent("hello 2"));
// Assert
Assert.Equal(2, _receivedEvents1.Count);
Assert.Equal(2, _receivedEvents2.Count);
}
[Fact]
public void A_Subscription_Can_Be_Cancelled()
{
// Act
using (_hub.Subscribe((TestEvent e) => _receivedEvents1.Add(e)))
{
_hub.Publish(new TestEvent("hello 1"));
}
_hub.Publish(new TestEvent("hello 2"));
// Assert
Assert.Equal(1, _receivedEvents1.Count);
}
private class TestEvent
{
public TestEvent(string message)
{
Message = message;
}
private String Message { get; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment