我是靠谱客的博主 大意唇膏,这篇文章主要介绍如何在C#中使用Bogus去创建模拟数据,现在分享给大家,希望可以做个参考。

生成模拟数据

为了生成模拟数据,我们首先需要针对模拟数据创建对应的实体类。这里我们可以创建一个命令行程序,并添加一下两个类。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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<Order> Orders { get; set; } }
登录后复制
复制代码
1
2
3
4
5
6
7
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库添加到你的项目中。

相关教程:C#视频教程

下面我们就可以来添加一个仓储类来获取模拟数据了。这里我们添加一个SampleCustomerRepository类,并加入以下方法。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public IEnumerable<Customer> GetCustomers() { Randomizer.Seed = new Random(123456); var ordergenerator = new Faker<Order>() .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<Customer>() .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); }
登录后复制

这里我们为订单和客户数据的生成定义了规则,然后我们调用了Generate方法来生成模拟数据。就是这么简单。

如上所见,Bogus提供了许多类来生成数据。例如Company类可以用来生成公司模拟数据,例如公司名称。你可以使用这些生成的数据作为你程序的模拟数据,这些数据有3种使用场景

  • 单元测试的模拟测试数据
  • 设计阶段的模拟数据
  • 原型的模拟数据

但是我确信,你能发现更多的使用场景。

这里为了使用这些数据,你可以在Main方法中加入以下代码

复制代码
1
2
3
4
5
6
7
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去创建模拟数据的全部内容,更多相关如何在C#中使用Bogus去创建模拟数据内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部