0

这是非常直接的(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;
        }
    }   
}
4

1 回答 1

1

不幸的是,你不能。这不是真正的起订量问题,而是 C# event 关键字与委托一起工作的方式。有关更多信息,请参阅此 SO 答案

于 2012-09-13T16:54:22.213 回答