Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate fake data using moq for unit test?

I need to generate some data to unit test my repositories. i was using a loop to generate a list of objects, see codes below. I learned moq is a great mocking library, Can I use moq to generate that and how do I do it?

public IQueryable<Category> GetCategories()
{
    IList<Category> result = new List<Category>();

    for (int i = 1; i <= 2; i++)
    {
        Category c = new Category();
        c.ID = i;
        c.Name = "Parent" + i.ToString();
        c.ParentID = 0;

        for (int x = i*10; x < i*10+5; x++)
        {
            Category sub = new Category();
            sub.ID = x;
            sub.Name = "Sub" + x.ToString();
            sub.ParentID = i;
            result.Add(sub);
        }

        result.Add(c);
    }

    return result.AsQueryable<Category>();
}
like image 508
qinking126 Avatar asked Sep 07 '25 02:09

qinking126


1 Answers

You can't use Moq to create the data, but you can use AutoFixture:

public IQueryable<Category> GetCategories()
{
    return fixture.CreateMany<Category>().AsQueryable();
}

However, this will not give you a hierarchical tree. It will return objects like this:

Object 1:
- ID = 0
- ParentID = 1
Object 2:
- ID = 2
- ParentID = 3

etc.

If you really need to have this hierarchical data, you would need to use the following code:

public IQueryable<Category> GetCategories()
{
    var result = new List<Category>();

    // Create the parents
    var parents = fixture.Build<Category>()
                         .Without(x => x.ParentID)
                         .CreateMany());
    result.AddRange(parents);

    result.AddRange(parents.SelectMany(p => fixture.Build<Category>()
                                                   .With(x => x.ParentID, p.ID)
                                                   .CreateMany())); 

    return result.AsQueryable();
}

This will add multiple parents with multiple subs for each parent.

like image 106
Daniel Hilgarth Avatar answered Sep 10 '25 02:09

Daniel Hilgarth