產生假資料的利器 ObjectFiller.NET

Posted by Ryan Tseng on 2017-12-07

緣起

在開發網站的時候,是不是常常會遇到後端有些功能還沒做完,但是要產生假資料顯示在畫面上。大部分的人會選擇自己簡單的建立幾筆資料,再不然就是寫個迴圈將資料後面串上索引,不過這些方法還是讓你的資料看起來沒有什麼真實的感覺,今天這篇文章要介紹這個套件 ObjectFiller.NET 讓你可以透過套件來產生更貼近真實資料的假資料來源,讓你不管是在畫面上還是做測試上,都能夠省去更多手動建立假資料的時間。

環境

  • LinqPad
    • Nuget (ObjectFiller.NET)

實際使用

測試用的物件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class User
{
public int Id { get; set; }

public int Age { get; set; }

public string Name { get; set; }

public string Email { get; set; }

public DateTime Birthday { get; set; }

public Address Address { get; set; }

public IEnumerable<string> BookNames { get; set; }

}

public class Address
{
public string City { get; set; }

public string Street { get; set; }

public string ZipCode { get; set; }
}

預設

預設完全不進行任何設定將會依照其型別自動塞入隨機的字串、數字等等

1
var filler = new Filler<User>();

針對型別設定

1
2
3
4
filler.Setup()
.OnType<string>().Use("使用自訂字串")
.OnType<int>().Use(199)
.OnType<DateTime>().Use(DateTime.Now);

針對屬性設定

1
2
3
filler.Setup()
.OnProperty(x => x.Age).Use(Enumerable.Range(10, 200))
.OnProperty(x => x.Birthday).Use(DateTime.Now);

多層巢狀物件

1
2
3
4
5
6
7
8
// 1 to 1
filler.Setup()
.OnProperty(x => x.Age).Use(10)
.OnProperty(x => x.Name).Use("Test")
.OnProperty(x => x.Email).Use("abc@aaa.bbb.ccc")
.SetupFor<Address>() // 從這裡開始設定子物件
.OnProperty(x => x.City).Use("Taipei")
.OnProperty(x => x.Street).Use("Test Street");

忽略指定屬性、型別

1
2
3
4
5
filler.Setup()
.OnProperty(x => x.Address).IgnoreIt()
.OnProperty(x => x.Name).IgnoreIt()
.OnProperty(x => x.Email).IgnoreIt()
.OnType<int>().IgnoreIt();

忽略繼承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Address
{
public string City { get; set; }

public string Street { get; set; }

public string ZipCode { get; set; }
}

public class CompanyAddress : Address
{
public string CompanyCity { get; set; }

public string CompanyStreet { get; set; }
}

// 父類別的屬性將不會被填值
filler.Setup()
.IgnoreInheritance();

Plugins

內建的 Plugin 支援相當多產生假資料的方式,這邊列出幾個比較常用的展示一下

1
2
3
4
5
6
7
8
9
10
filler.Setup()
.OnProperty(x => x.Age).Use(new IntRange(18, 25)) // IntRange Plugin
.OnProperty(x => x.Name).Use(new RealNames()) // RealNames Plugin
.OnProperty(x => x.Email).Use(new EmailAddresses()) // EmailAddresses Plugin
.OnProperty(x => x.BookNames)
.Use(new Collectionizer<string, RealNames>(new RealNames(NameStyle.FirstNameLastName), 10, 10)) // Collectionizer Plugin
.SetupFor<Address>()
.OnProperty(x=>x.City).Use(new CityName()) // CityName Plugin
.OnProperty(x => x.Street).Use(new StreetName()) // StreetName Plugin
.OnProperty(x => x.ZipCode).Use(new PatternGenerator("{C:10000}")); // PaternGenerator Plugin

以上大略的介紹一下 ObjectFiller.NET 這個套件要怎麼快速產生假資料,當然官方提供的文件還有蠻多組合變化可以玩的,讀者可以親自到官方文件中參考。

參考連結