DEV Community

Praneet Nadkar
Praneet Nadkar

Posted on

Generating a fake data in .Net Core API

Well, the other day, I was working on something where I needed some fake data or some random data to be generated in my .net core web API. On searching I ran into many blogs and links and I am sure there are many who have run into this scenario where we have to generate a fake data for some or the other reason.

Well there is a simple and easy way to do it, add a loop, create a new object of a class and add it to a list. Return the list.

Well all of us are aware of this. However, it is was pain in the neck to add this new and loops every time. I searched and found Genfu which generates the test data. I am like wow! Most of my work is done now. If you look at it, I will have to call a method from this GenFu package which is

GenFu.GenFu.ListOf<T>()
Enter fullscreen mode Exit fullscreen mode

But again, I was thinking, I will have to write it at too many places. What else can be done here?

I was thinking to write a service for this, add it in the startup, and use it through DI in every controller. I somehow managed to do this. Here is my interface and the service that I am using for DI.

    public interface IDataGenerator<T> where T : class
    {
        /// <summary>
        /// Generates a collection of type T based on the properties in T
        /// </summary>
        /// <returns>List<T></returns>
        List<T> Collection();

        /// <summary>
        /// Generates the collection of type T of size = length 
        /// </summary>
        /// <param name="length">The size of the collection to be passed</param>
        /// <returns>A collection of type T based on the length passed</returns>
        List<T> Collection(int length);

        /// <summary>
        /// Generates an object of type T with data
        /// </summary>
        /// <returns>T with data based on the properties in T</returns>
        T Instance();
    }
Enter fullscreen mode Exit fullscreen mode

And here is my class inheriting the interface.

    public class DataGeneratorService<T> : IDataGenerator<T>
        where T : class, new()
    {
        /// <summary>
        /// Generates a collection of type T based on the properties in T
        /// </summary>
        /// <returns>List<T></returns>
        public List<T> Collection() => GenFu.GenFu.ListOf<T>();

        /// <summary>
        /// Generates the collection of type T of size = length 
        /// </summary>
        /// <param name="length">The size of the collection to be passed</param>
        /// <returns>A collection of type T based on the length passed</returns>
        public List<T> Collection(int length) => GenFu.GenFu.ListOf<T>(length);

        /// <summary>
        /// Generates an object of type T with data
        /// </summary>
        /// <returns>T with data based on the properties in T</returns>
        public T Instance() => GenFu.GenFu.New<T>();
    }
Enter fullscreen mode Exit fullscreen mode

Here, there can be many methods that can be added. GenFu gives way lot of things. I have shown a couple of them here. You can always try and play with them.

The method Collection will give me a list of type T and Collection(int length) will give me a list of size which is passed to the method.

Now here, don't forget to add the package Genfu. You can add it using package manager console like this:

install-package GenFu
Enter fullscreen mode Exit fullscreen mode

That's it, now the only thing that remains is adding this to the startup. Since this is a generic thing, I have added this to the startup like this:

In your ConfigureServices method:

services.AddSingleton(typeof(IDataGenerator<>), typeof(DataGeneratorService<>));
Enter fullscreen mode Exit fullscreen mode

Now before going to DI, consider a class like a Contact. This is a model class for which the data will be generated.

    public class Contact
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAdress { get; set; }
        public string PhoneNumber { get; set; }
    }
Enter fullscreen mode Exit fullscreen mode

Now, I have a values controller, in which there is a HttpGet, that will give me a fake data for these contacts.

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly IDataGenerator<Contact> _contactsGeneratorService;

    public ValuesController(IDataGenerator<Contact> dataGeneratorService)
    {
        _contactsGeneratorService = dataGeneratorService;
    }

    // GET: api/<controller>
    [HttpGet]
    public IEnumerable<Contact> Get()
    {
        var data = _contactsGeneratorService.Collection(100);
        return data;
    }
}
Enter fullscreen mode Exit fullscreen mode

That's it ! I have a service ready. Whenever I need any fake data, I will just inject into my controller and run it.

Top comments (6)

Collapse
 
rafalpienkowski profile image
Rafal Pienkowski

You could also take a closer look at the AutoFixture project. It's very well documented (Pluralsight course, ploeh blog or Nikos Baxevanis' blog) and working with it is easy and enjoyable.

More about Mark Seemann (aka ploeh), the author of AutoFixture you can find here.

Collapse
 
workcontrolgit profile image
Fuji Nguyen

Hi Mr. Nadkar,

I want to add async support. It gives the warning "the async lack await..."
Interface:
Task> Collection(int length);

Implementation:
public async Task> Collection(int length) => GenFu.GenFu.ListOf(length);

Any suggestion?

Collapse
 
ianrathbone profile image
Ian Rathbone

Very useful thank you

Collapse
 
praneetnadkar profile image
Praneet Nadkar

Thanks for going through. Glad it helps! :)

Collapse
 
chaluvadis profile image
Curious to learn new things

Very use full. thanks for sharing the idea.

Collapse
 
praneetnadkar profile image
Praneet Nadkar

I am glad it helps. Thanks for reading.