Using Moq to override virtual methods in the same class

柔情痞子 提交于 2019-11-29 02:54:16

You can probably use partial mocking in this scenario, although all your methods would need to be virtual:

    var mock = new Moq.Mock<RenewalService>();
    mock.Setup(m => m.GetNextRenewalDate(It.IsAny<Guid>())).Returns(null);
    mock.CallBase = true;
    var results = mock.Object.IsLastRenewalOfYear(...);
var mock = new Moq.Mock<RenewalService> { CallBase = true };
mock.Setup(m => m.GetNextRenewalDate(It.IsAny<Guid>())).Returns(null);
var results = mock.Object.IsLastRenewalOfYear(...);

Edit: I now agree that this is not the right answer for Andrew's case. I want to leave this answer here for the comments thread. Please don't down vote any more :)

Before edit:

Generally mock object frameworks aren't designed to simplify the single class scenario, they're designed to isolate your code so you can test a single class.

If you try to use a mock object framework to solve this, the framework is just going to create a derived class and overload that method. The only thing different will be that you can do that in about 3 lines instead of 5, because you won't have to create the derived class definition.

If you'd like to use mock objects to isolate this behavior, then you should split up this class a bit. The GetNextRenewalDate logic could live outside the RenewalService object.

The fact that you're running into this problem may show that there is a simpler or more finely grained design yet to be discovered. Finding a class that is a bit less concrete, with a name like "manager" or "service" is often a hint that you could break up your design into smaller classes and get better reusability and maintainability out of it.

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