Moq a base class function from a derived class

后端 未结 2 1765
南笙
南笙 2021-01-12 18:55

I am new to Moq and I just watched the pluralsight video on Moqing so I felt empowered to go and write some tests. I have a Base Class let’s say Sheet which implements an in

2条回答
  •  时光说笑
    2021-01-12 19:22

    If you change

    var MockSheet = new Moq();
    

    into

    var MockSheet = new Moq { 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.

提交回复
热议问题