首頁  >  文章  >  後端開發  >  如何在C#中使用Bogus去創建模擬數據

如何在C#中使用Bogus去創建模擬數據

little bottle
little bottle轉載
2019-04-29 11:36:413709瀏覽

Bogus, 一個基於C#的簡單資料產生器。使用Bogus產生模擬資料, 你只需要定義規則並產生資料即可,就是這麼簡單。而且Bogus可以產生固定數據或變化數據。這樣一旦你拿到了這些數據,你就可以把它們序列化成你想要的格式: json, xml,資料庫或文字檔。

產生模擬數據

為了產生模擬數據,我們首先需要針對模擬數據建立對應的實體類別。這裡我們可以建立一個命令列程序,並加入兩個類別。

public class Customer
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string ZipCode { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string ContactName { get; set; }
    public IEnumerable Orders { get; set; }
}
public class Order
{
    public Guid Id { get; set; }
    public DateTime Date { get; set; }
    public Decimal OrderValue { get; set; }
    public bool Shipped { get; set; }
}

在你創建好以上兩個實體類別之後,你就可以來新增倉儲來取得模擬資料了。為了使用Bogus, 你可以使用Nuget將Bogus庫添加到你的專案中。

Install-Package Bogus

相關教學:C#影片教學

下面我們就可以來新增一個倉儲類別來獲取模擬數據了。這裡我們加入一個SampleCustomerRepository類,並加入以下方法。

public IEnumerable GetCustomers()
{
    Randomizer.Seed = new Random(123456);
    var ordergenerator = new Faker()
        .RuleFor(o => o.Id, Guid.NewGuid)
        .RuleFor(o => o.Date, f => f.Date.Past(3))
        .RuleFor(o => o.OrderValue, f => f.Finance.Amount(0, 10000))
        .RuleFor(o => o.Shipped, f => f.Random.Bool(0.9f));
    var customerGenerator = new Faker()
        .RuleFor(c => c.Id, Guid.NewGuid())
        .RuleFor(c => c.Name, f => f.Company.CompanyName())
        .RuleFor(c => c.Address, f => f.Address.FullAddress())
        .RuleFor(c => c.City, f => f.Address.City())
        .RuleFor(c => c.Country, f => f.Address.Country())
        .RuleFor(c => c.ZipCode, f => f.Address.ZipCode())
        .RuleFor(c => c.Phone, f => f.Phone.PhoneNumber())
        .RuleFor(c => c.Email, f => f.Internet.Email())
        .RuleFor(c => c.ContactName, (f, c) => f.Name.FullName())
        .RuleFor(c => c.Orders, f => ordergenerator.Generate(f.Random.Number(10)).ToList());
    return customerGenerator.Generate(100);
}

這裡的第三行程式碼,我們為Randomizer.Seed屬性指定一個固定的隨機種子,因此每次產生的資料都是一樣的。如果你不希望每次都產生固定的數據,你可以去掉這行程式碼。

這裡我們為訂單和客戶資料的產生定義了規則,然後我們呼叫了Generate方法來產生模擬資料。就是這麼簡單。

如上所見,Bogus提供了許多類別來產生資料。例如Company類別可以用來產生公司模擬數據,例如公司名稱。你可以使用這些產生的數據作為你程式的模擬數據,這些數據有3種使用場景

  • 單元測試的模擬測試數據
  • 設計階段的模擬數據
  • 原型的模擬資料

但是我確信,你能發現更多的使用情境。

這裡為了使用這些數據,你可以在Main方法中加入以下程式碼

static void Main(string[] args)
{
    var repository = new SampleCustomerRepository();
    var customers = repository.GetCustomers();
    Console.WriteLine(JsonConvert.SerializeObject(customers, 
        Formatting.Indented));
}

這裡我們將模擬數據轉換成了Json字串,所以這裡你需要新增對Newtonsoft.Json函式庫的參考。當你運行程式之後,你會得要以下結果。

如何在C#中使用Bogus去創建模擬數據

如上所見,程式產生了一個顧客的資料集,並附帶了每位顧客的所有訂單資訊。

以上是如何在C#中使用Bogus去創建模擬數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除