Tech Note

Azure, Office 365, Power Platform, etc... の勉強手記

テストデータを自動生成するライブラリ

データベースに投入するデータや、単体テスト時に利用するデータを作るのはとても面倒です。 今回紹介する Bogus というライブラリを使うと容易にデータが作れます。

動作環境

サンプルコード

github.com

単純なクラス

public class BillingDetails
{
    public string CustomerName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string AddressLine { get; set; }
    public string City { get; set; }
    public string PostCode { get; set; }
    public string Country { get; set; }
}

private static List<BillingDetails> GenerateRandomBillingDetails(int numberOfRecordsPerBatch)
{
    var faker = new Faker<BillingDetails>()
        // .StrictMode(true)
        .RuleFor(x => x.CustomerName, x => x.Person.FullName)
        .RuleFor(x => x.Email, x => x.Person.Email)
        .RuleFor(x => x.Phone, x => x.Person.Phone)
        .RuleFor(x => x.AddressLine, x => x.Address.StreetAddress())
        .RuleFor(x => x.City, x => x.Address.City())
        .RuleFor(x => x.PostCode, x => x.Address.ZipCode())
        .RuleFor(x => x.Country, x => x.Address.Country());

    var billingDetails = faker.Generate(numberOfRecordsPerBatch);

    return billingDetails;
}

人に関するプロパティは、Facker.Person クラスのプロパティを紐づけたり、住所に関するプロパティは、Facker.Address クラスのプロパティを紐づけると、イイ感じのデータを自動生成してくれます。

クラスが入れ子になってるクラス

public class Order
{
    public Guid Id { get; set; }
    public decimal Price { get; set; }
    public string Currency { get; set; }
    public BillingDetails BillingDetails { get; set; }
}

private static List<Order> GenerateRandomOrders(int numberOfRecordsPerBatch)
{
    var billingDetailsFaker = new Faker<BillingDetails>()
        .RuleFor(x => x.CustomerName, x => x.Person.FullName)
        .RuleFor(x => x.Email, x => x.Person.Email)
        .RuleFor(x => x.Phone, x => x.Person.Phone)
        .RuleFor(x => x.AddressLine, x => x.Address.StreetAddress())
        .RuleFor(x => x.City, x => x.Address.City())
        .RuleFor(x => x.PostCode, x => x.Address.ZipCode())
        .RuleFor(x => x.Country, x => x.Address.Country());

    var orderFaker = new Faker<Order>()
        .RuleFor(x => x.Id, Guid.NewGuid)
        .RuleFor(x => x.Currency, x => x.Finance.Currency().Code)
        .RuleFor(x => x.Price, x => x.Finance.Amount(5, 100))
        .RuleFor(x => x.BillingDetails, x => billingDetailsFaker);

    var orders = orderFaker.Generate(numberOfRecordsPerBatch);

    return orders;
}

入れ子になってるクラスの Facker オブジェクトをまずは作っておいてから、親クラスのプロパティに Facker オブジェクトを割り当てる感じに書きます。

実行する度に生成されるデータを変えさせない方法

既定では、実行するたびに自動生成されるデータの中身はランダムに変わりますが、下記のようにあらかじめ Seed 値を設定することで生成されるデータを固定することができます。

Randomizer.Seed = new Random(123456789);