Reputation: 14886
I am trying to add an extension method that generates a random HashSet of ints for use with NBuilder mocking library.
This is the method I would like to shorten into a simple extension method:
using System;
using FizzWare.NBuilder;
using System.Collections.Generic;
using System.Linq;
namespace FakeData
{
public class Person
{
public string Name { get; set; }
public HashSet<int> AssociatedIds { get; set; }
}
class Program
{
static void Main(string[] args)
{
var people = Builder<Person>.CreateListOfSize(50)
.All()
.With(p => p.AssociatedIds =
Enumerable.Range(0, 50)
.Select(x => new Tuple<int, int>(new Random().Next(1, 1000), x))
.OrderBy(x => x.Item1)
.Take(new Random().Next(1, 50))
.Select(x => x.Item2)
.ToHashSet())
.Build();
}
}
}
I want to replace the With()
so it would instead look like:
var people = Builder<Person>.CreateListOfSize(50)
.All()
.RandomHashInt(p => p.AssociatedIds, 1, 50)
.Build();
Something like this:
public static IOperable<T> RandonHashInt<T>(this IOperable<T> record, Expression<Func<T, HashSet<int>>> property, int min, int max)
{
//add hashset
return record;
}
Can someone point me in right direction please
Upvotes: 1
Views: 400
Reputation: 14886
I looked inside source code on NBuilder With()
method and copied the way it was done there:
public static IOperable<T> WithRandonHashInt<T>(this IOperable<T> record, Expression<Func<T, HashSet<int>>> property, int min, int max)
{
var declaration = record as IDeclaration<T>;
var rand = new Random();
declaration.ObjectBuilder.With(property,
Enumerable.Range(min, max)
.OrderBy(e => Guid.NewGuid().GetHashCode())
.Take(rand.Next(min, max))
.ToHashSet());
return (IOperable<T>)declaration;
}
Upvotes: 1