使用 AutoFixture 使用一组有限的字符填充对象 属性

Populating an object property with one of a limited set of characters using AutoFixture

我正在使用 AutoFixture 生成用于测试的 ProblemClass 对象列表。 ProblemClass 定义为

public class ProblemClass
{
    int Id {get; set;}
    string ProblemField {get; set;}
}

ProblemField 可以包含 3 个值之一 "A"、"B" 或 "C"。我无法更改 ProblemClass,因此无法将 ProblemField 设为枚举。

如何让 AutoFixture 使用 "A"、"B" 或 "C" 随机填充列表中每个对象的 ProblemField 属性?

(例如 myList[0].ProblemField 是 "A",myList[1].ProblemField 是 "C",等等)

谢谢!

这样的事情对你有用吗?

public class ProblemClass
{
    static Random r = new Random();
    const string options = "ABC";

    public ProblemClass(int id)
    {
        Id = id;
        ProblemField = options[r.Next(options.Length)].ToString();
    }

    public int Id { get; }
    public string ProblemField { get; }
}

您可以自定义 ProblemClass 的生成方式。

这应该有效:

fixture
    .Customize<ProblemClass>(ob =>
        ob
            .With(
                x => x.ProblemField,
                (int i) => "ABC".Substring(i % 3, 1)));

更多信息:

From the cheatsheet

Marks blog