mocking collection behavior with Moq

Posted by Stephen Patten on Stack Overflow See other posts from Stack Overflow or by Stephen Patten
Published on 2010-06-15T23:05:56Z Indexed on 2010/06/15 23:12 UTC
Read the original article Hit count: 411

Filed under:
|
|

Hello,

I've read through some of the discussions on the Moq user group and have failed to find an example and have been so far unable to find the scenario that I have. Here is my question and code:

// 6 periods
var schedule = new List<PaymentPlanPeriod>()
{
    new PaymentPlanPeriod(1000m, args.MinDate.ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(1).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(2).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(3).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(4).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(5).ToString())
};

// Now the proxy is correct with the schedule
helper.Setup(h => h.GetPlanPeriods(It.IsAny<String>(), schedule));

Then in my tests I use Periods but the Mocked _PaymentPlanHelper never populates the collection, see below for usage:

public IEnumerable<PaymentPlanPeriod> Periods
{
 get
 {
  if (CanCalculateExpression())
     _PaymentPlanHelper.GetPlanPeriods(this.ToString(), _PaymentSchedule);

  return _PaymentSchedule;
 }
}

Now if I change the mocked object to use another overloaded method of GetPlanPeriods that returns a List like so :

var schedule = new List<PaymentPlanPeriod>()
{
    new PaymentPlanPeriod(1000m, args.MinDate.ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(1).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(2).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(3).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(4).ToString()),
    new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(5).ToString())
};

helper.Setup(h => h.GetPlanPeriods(It.IsAny<String>())).Returns(new List<PaymentPlanPeriod>(schedule));

List<PaymentPlanPeriod> result = new _PaymentPlanHelper.GetPlanPeriods(this.ToString());

This works as expected. Any pointers would be awesome, as long as you don't bash my architecture... :)

Thank you, Stephen

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing