Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a list of fakes using Moq

Tags:

c#

moq

I want to generate a list of fakes without specify all the properties of the fake object using Moq :

var mock = Mock.Of<ICalendar>(x =>
    x.GetSchedules() == new List<ISchedule> 
    {
        // I don't want specify explicitly title and other properties
        Mock.Of<ISchedule>(y => y.Title == "fdfdf" && y.Start == DateTime.Today)
    });

List<ISchedule> s = mock.GetSchedules();

Is it possible to specify "rules" instead of hardcode properties ? And Is it possible to set the number of item I want ?

Thank you.

like image 600
Florian Avatar asked Mar 16 '12 09:03

Florian


3 Answers

Hope this helps:

int numberOfElements = 10;
var mock = Mock.Of<ICalendar>(x =>
           x.GetSchedules() == Enumerable.Repeat(Mock.Of<ISchedule>(), numberOfElements).ToList());
like image 168
Olek Avatar answered Oct 22 '22 06:10

Olek


Have a look at AutoMoq and see if that does what you want.

like image 28
Trevor Pilley Avatar answered Oct 22 '22 07:10

Trevor Pilley


You could create a ScheduleMockBuilder abstract class that builds a Mock of ISchedule with some random data. Then call this builder as many times as you need items in the list.

Check the Builder pattern for more information.

You can also use QuickGenerate; this is a library with a generic builder that a colleague of mine wrote. It can generate objects with random properties out of the box and you can even add constraints to the random data being generated.

like image 22
GuyVdN Avatar answered Oct 22 '22 05:10

GuyVdN