How do you mock a Sealed class?

前端 未结 10 2282
鱼传尺愫
鱼传尺愫 2020-11-27 15:27

Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird.

So, What is t

10条回答
  •  遥遥无期
    2020-11-27 15:44

    It is perfectly reasonable to mock a sealed class because many framework classes are sealed.

    In my case I'm trying to mock .Net's MessageQueue class so that I can TDD my graceful exception handling logic.

    If anyone has ideas on how to overcome Moq's error regarding "Invalid setup on a non-overridable member", please let me know.

    code:

        [TestMethod]
        public void Test()
        {
            Queue messages = new Queue();
            Action sendDelegate = msg => messages.Enqueue(msg);
            Func receiveDelegate =
                (v1, v2) =>
                {
                    throw new Exception("Test Exception to simulate a failed queue read.");
                };
    
            MessageQueue mockQueue = QueueMonitorHelper.MockQueue(sendDelegate, receiveDelegate).Object;
        }
        public static Mock MockQueue
                    (Action sendDelegate, Func receiveDelegate)
        {
            Mock mockQueue = new Mock(MockBehavior.Strict);
    
            Expression> sendMock = (msmq) => msmq.Send(It.IsAny()); //message => messages.Enqueue(message);
            mockQueue.Setup(sendMock).Callback(sendDelegate);
    
            Expression> receiveMock = (msmq) => msmq.Receive(It.IsAny(), It.IsAny());
            mockQueue.Setup(receiveMock).Returns(receiveDelegate);
    
            return mockQueue;
        }
    

提交回复
热议问题