Using Moq to Stub an interface method [duplicate]

2020-08-17 06:42发布

Possible Duplicate:
How to mock a method that returns an int with MOQ

Here's my interface:

public interface ICalenderService
    {
        DateTime Adjust(DateTime dateToAdjust, BusinessDayConvention convention, List<HolidayCity> holidayCities);
    }

I've done some research and it seems you can mock this real easily, but I want to stub this out using Moq so that I can pass the stub into my other class constuctors and have the stub return whatever DateTime I want for its Adjust method.

What's the easiest way to do this?

Edit: I know I can create my own stub in my project, but I'd like to write less code, and I think Moq can let me do that, I just don't know what the syntax looks like.

1条回答
混吃等死
2楼-- · 2020-08-17 06:59

Set up the stub like this:

var calendarServiceStub = new Mock<ICalenderService>();

calendarServiceStub
    .Setup(c => c.Adjust(It.IsAny<DateTime>(), It.IsAny<BusinessDayConvention>(), It.IsAny<List<HolidayCity>>()))
    .Returns(theDateTimeResultYouWant);

Pass calendarServiceStub.Object to the other class's constructor.

查看更多
登录 后发表回答