faker-net

Generate fake testing data in C# with Faker.NET

  • 3 min

Faker .NET is a C# library used to generate random and fake data for testing and development purposes in .NET applications.

This type of library is very useful when we need to test applications or databases. For example, we can create a demo or a mockup without using real data or worrying about confidentiality issues.

The library is a port (one of many) of the popular Ruby library Faker https://github.com/faker-ruby/faker. Thus, it is an alternative to other similar libraries for .NET like the popular https://github.com/slashdotdash/faker-cs.

What I like most about this particular version of Faker, besides the large number of generators and options it has, are the localization options. Most libraries only generate data for US or UK. However, Faker .NET generates data in formats for more than 51 countries.

With Faker .NET we can generate random data of a wide variety of types such as names, addresses, phone numbers, email addresses, dates, and many, many others.

Of course, we have all kinds of options to customize the creation. In addition to being able to generate custom data through regular expressions, along with probability distributions to control the frequency of certain values.

It is compatible with .NET Standard 2.0 and 2.1, .NET Framework 4.6.2 or higher, and .NET 5.0 or higher.

How to Use Faker .NET

We can easily add the library to a .NET project through the corresponding NuGet package.

Install-Package Faker.Net

Here are some examples of how to use Faker .NET extracted from the library’s documentation

// Generates a random name
string name = RimuTec.Faker.Name.FullName();

// Generates a random address
string address = RimuTec.Faker.Address.FullAddress();

// Generates a random phone number
string phone = RimuTec.Faker.Phone.Number();

// Generates a random date in the range of the last 10 years
DateTime date = RimuTec.Faker.Date.Recent(10);

// Generates random Lorem Ipsum paragraphs
string paragraphs = RimuTec.Faker.Lorem.Paragraphs(4);
Copied!

As we can see, it is very easy to use; it’s simply a call to the desired generator method. The types of data available for use are:

  • Address
  • Business
  • Code
  • Color
  • Company
  • Date
  • Educator
  • Finance
  • IdNumber
  • Internet
  • Job
  • Lorem
  • Name
  • PhoneNumber
  • RandomNumber

Each with different generation options. In total, there are over 100 methods to generate fake data for your tests.

To use Faker Cs in a C# project, you must first install the library via NuGet. Once installed, you can start using it as follows:

using Faker;

Copied!

Faker Cs also allows generating data in different languages and localizations, which is useful for testing applications that must support different languages and regions.