Moq a base class function from a derived class

懵懂的女人 提交于 2019-12-01 04:53:25

If you change

var MockSheet = new Moq<Page>();

into

var MockSheet = new Moq<Page> { CallBase = true, };

your mock (which you can think of as a derived class of Page) will call the implementation from Page in the mock's own override of CreateSheet.

The default behavior (if you do not change CallBase) is for Moq to override every method and property it can, and use an empty implementation. Setting CallBase to true makes Moq call the Page implementation instead, like I said.

(Of course, use MockSheet.Setup(x => x.CreateDocSheet()).Callback(() => { /* something */ }) if you want CreateDocSheet to do something non-trivial.)

In the case where you removed the virtual modifier from CreateSheet, Moq can no longer override or mock this member. Think of it: How could Moq "mock" a non-virtual method? Therefore, the call bypasses Moq's class completely.

Moq is for imitating a dependency or dependencies of your system under test so that you can isolate that from the rest of your application or externalities, not for replacing your system under test. It's not the right tool for what you are trying to do here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!