断言模拟(MOQ因此DynamicProxy)事件没有附加处理程序

时间:2012-09-13 13:25:13

标签: events moq

这是非常直接的(ish)要做的是事件是'真实',就像现在由DynamicProxy创建的那样,但是我无法为模拟事件做任何事情。

解释我想要实现的目标的最好方法是使用代码,请参阅测试方法中的注释行:

using System;
using Moq;
using NUnit.Framework;

namespace MOQTest
{
 [TestFixture]
    public class EventsMoqTest
    {
        [Test]
        public void DetachTest()
        {
            var hasEventMock = new Mock<IHasEvent>();

            using (var observer = new Observer(hasEventMock.Object))
            {
                 //Assert that hasEventMock.Object has handler attached
            }

            //Assert that hasEventMock.Object DOES NOT have handler attached
        }
    }

    public interface IHasEvent
    {
        event EventHandler AnEvent;
    }

    public class Observer : IDisposable
    {
        private readonly IHasEvent _hasEvent;
        private readonly EventHandler _hasEventOnAnEvent;

        public Observer(IHasEvent hasEvent)
        {
            _hasEvent = hasEvent;

            _hasEventOnAnEvent = _hasEvent_AnEvent;
            _hasEvent.AnEvent += _hasEventOnAnEvent;
        }

        void _hasEvent_AnEvent(object sender, EventArgs e)
        {}

        public void Dispose()
        {
            _hasEvent.AnEvent -= _hasEventOnAnEvent;
        }
    }   
}

1 个答案:

答案 0 :(得分:1)

不幸的是,你做不到。这不是真正的moq问题,而是C#事件关键字与委托一起使用的方式。有关详细信息,请参阅this SO answer