I'm writing unit tests using C# and Microsoft Fakes. The class I want to test subscribes to a sizable number of events defined in a service. The Service reference is private. Fakes has generated a Stub of the service class' Interface. I'm trying to write an extension method for the Stub that will allow me to determine whether an event, that I identify by name, has a subscriber or not.
I've searched for and found some examples but none have applied specifically to what I am doing and don't work. I think because of the Stub.
For example, this code is borrowed from another StackOverflow post but doesn't work because it doesn't find any event by name:
var rsEvent = relayService.GetType().GetEvent(eventName + "Event", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
Part of the reason is because Fakes appends Event to the name but even when I append "Event" to the name GetEvent()
still doesn't recognize the event. The ONLY way I can retrieve it is by using GetMember()
. OK. That's great but how do I convert a MemberInfo object to an Event of Action<string>
so that I can determine whether the event has been subscribed? Or is there a better way? All I want to know is whether the named event has a subscriber.
public interface IRelayService
{
...
event Action<string> DisplayHandoffConversationTextEvent;
...
}
public class MainWindowViewModel : ViewModelBase
{
...
private readonly IRelayService _relayService;
....
public MainWindowViewModel()
{
...
_relayService = SimpleIoc.Default.GetInstance<IRelayService>();
...
}
public void InitializeServices() // method to be tested
{
...
_relayService.DisplayHandoffConversationTextEvent += OnDisplayHandoffConversationText;
...
}
}
[TestClass]
public class MainWindowViewModelTests
{
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
...
_relayService = new StubIRelayService();
...
}
[TestMethod]
public void InitializeServices_Test()
{
// Arrange
var mwvm = new MainWindowViewModel();
// Act
mwvm.InitializeServices();
// Assert
Assert.IsTrue(_relayService.DoesEventHaveSubscriber("DisplayHandoffConversationTextEvent"));
Assert.IsFalse(_relayService.DoesEventHaveSubscriber("AdminCanceledCallEvent"));
}
}
public static class StubIRelayServiceExtensions
{
public static bool DoesEventHaveSubscriber(this IRelayService relayService, string eventName)
{
var rsEvent = relayService.GetType().GetMember(eventName + "Event",
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (rsEvent.Length > 0)
{
var member = rsEvent[0];
// What do I do here?
return true;
}
return false;
}
}
In the extension method, how do I determine whether the event has a subscriber? I'm stumped.
TIA