用于测试事件是否已订阅的单元测试的扩展方法

问题描述 投票:0回答:1

我正在使用C#和Microsoft Fakes编写单元测试。我想要测试的类订阅了服务中定义的大量事件。服务引用是私有的。 Fakes已生成服务类“接口”的Stub。我正在尝试为Stub编写一个扩展方法,这将允许我确定一个事件,我通过名称识别,是否有订阅者。

我搜索并找到了一些例子,但没有一个专门应用于我正在做的事情而且没有用。我想是因为Stub。

例如,此代码是从另一个StackOverflow帖子借来的,但不起作用,因为它没有按名称找到任何事件:

var rsEvent = relayService.GetType().GetEvent(eventName + "Event", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

部分原因是因为Fakes将Event附加到名称,但即使我将“Event”追加到名称GetEvent()仍然无法识别该事件。我可以检索它的唯一方法是使用GetMember()。好。这很好,但是如何将MemberInfo对象转换为Action<string>的事件,以便我可以确定该事件是否已被订阅?或者,还有更好的方法?我想知道的是命名事件是否有订阅者。

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;
    }
}

在扩展方法中,如何确定事件是否具有订户?我很难过。

TIA

c# unit-testing extension-methods system.reflection microsoft-fakes
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.