Autofixture,创建一个带有交替键的字典列表<string, object>

rle*_*lee 4 c# dictionary autofixture

我需要一个字典列表,每个字典应包含已知数量的字符串、字符串对,键是确定性的,但值应该是随机字符串,并且列表中的每个字典必须具有相同的键。一些背景信息:字符串,字符串对表示包含产品实体的数据库表中的值,我使用字典向我的测试数据库添加新行。要创建两行,我需要两个字典,如下所示:

new Dictionary<string, string>() { { "productno", "1001" }, { "productname", "testproduct" } };
new Dictionary<string, string>() { { "productno", "1002" }, { "productname", "testproduct2" } };
Run Code Online (Sandbox Code Playgroud)

productno 和 productname 是列名和字典中的键。

var dicts = new Fixture().Create<List<IDictionary<string, string>>>(); 按照评论中的说明进行了尝试,它为我提供了三个字典的列表,每个字典都有一个 GUID 作为键,一个随机字符串作为值。当键是确定性的时,如何正确填充字典的键?

我当前的解决方案有点冗长,但有额外的好处,它生成任何类型的随机值(但未测试除字符串以外的其他类型)。它只使用 Autofixture 来填充随机值,但很想知道 Autofixture 中是否有内置的东西可以做同样的事情。我现在所拥有的:

public SqlReaderFixtureBuilder AddRows(string table, string[] columns, Type[] types, int no)
{
    var fixture = new Fixture();

    for (int rowno = 0; rowno < no; rowno++)
    {
        if (!tablerows.ContainsKey(table))
            tablerows[table] = new List<Dictionary<string, object>>();

        var values = new Dictionary<string, object>();
        for (int i = 0; i < columns.Length; i++)
        {
            values[columns[i]] = new SpecimenContext(fixture).Resolve(types[i]);
        }
        tablerows[table].Add(values);
    }
    return this;
}
Run Code Online (Sandbox Code Playgroud)

调用它: AddRows("products", new[] { "productno", "productname" }, new[] { typeof(string), typeof(string) }, 30)

Mar*_*ann 6

创建具有确定性键的字典相当容易。由于键不是匿名值,因此最好在 AutoFixture 之外创建它们并将它们与 AutoFixture 创建的值合并:

var fixture = new Fixture();
var columns = new[] { "productno", "productname" };
var values = fixture.Create<Generator<string>>();

var dict = columns
    .Zip(values, Tuple.Create)
    .ToDictionary(t => t.Item1, t => t.Item2);
Run Code Online (Sandbox Code Playgroud)

这将创建一个字典 ( dict),其中包含 中的两个键的值columns

您可以将类似的内容打包在ICustomizationfor 中Dictionary<string, string>,这意味着当您请求许多Dictionary<string, string>值时,您将获得多个都这样创建的字典。