c# - 在Bogus库中为Enum生成假数据

标签 c# bogus

我想使用 Bogus 库创建假数据来测试数据库性能。这是我的书示例:

    public class Book
    {
        public Guid Id { get; set; }

        public string Title { get; set; }

        public double Price { get; set; }

        public string ISBN { get; set; }

        public Genre Genre { get; set; }
    }

    public enum Genre
    {
        Poetry,
        Romance,
        Thriller,
        Travel
    }
}

此外,我还为 Book 类中的每个属性制定了生成虚假数据的规则。

        public static Faker<Book> Book = new Faker<Book>()
            .StrictMode(true)
            .RuleFor(x => x.Id, f => f.Random.Guid())
            .RuleFor(x => x.Title, f => f.Company.CompanyName())
            .RuleFor(x => x.Price, f => f.Random.Double())
            .RuleFor(x => x.ISBN, f => $"ISBN_{f.Random.Guid()}")
            .RuleFor(x => x.Genre, f => ???);

我的问题是 - 如何为枚举 Genre 生成随机值

提前致谢!

最佳答案

答案可以在 the documentation 中找到本身,

尝试使用

.RuleFor(x => x.Genre, f =>f.PickRandom<Genre>());

你的代码看起来像,

public static Faker<Book> Book = new Faker<Book>()
        .StrictMode(true)
        .RuleFor(x => x.Id, f => f.Random.Guid())
        .RuleFor(x => x.Title, f => f.Company.CompanyName())
        .RuleFor(x => x.Price, f => f.Random.Double())
        .RuleFor(x => x.ISBN, f => $"ISBN_{f.Random.Guid()}")
        .RuleFor(x => x.Genre, f => f.PickRandom<Genre>());

POC: .NET Fiddle

关于c# - 在Bogus库中为Enum生成假数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68168067/

相关文章:

c# - 伪造的伪造数据 : Conditional and random in the same field, 可能留下空的伪造数据

c# - javascript切换背景图片

c# - 在使用 TcpClient 和 TcpListener 发送的消息中获取垃圾数据

c# - ASP.net 链接按钮 PostBackUrl 不适用于 IIS 8

带有可视化编程编辑器的 C# 应用程序

c# - 从路线数据中获取操作名称

c# - 伪造的faker如何设置字符串数组列表

C# Faker Bogus 生成自有属性(property)