Using Moq to Stub an interface method

slandau picture slandau · May 8, 2012 · Viewed 16k times · Source

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.

Answer

Cristian Lupascu picture Cristian Lupascu · May 8, 2012

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.