c# - Autofixture,创建一个字典列表<string, object> 交替键

标签 c# dictionary autofixture

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

new Dictionary<string, string>() { { "productno", "1001" }, { "productname", "testproduct" } };
new Dictionary<string, string>() { { "productno", "1002" }, { "productname", "testproduct2" } };

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;
}

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

最佳答案

创建具有确定性键的字典相当容易。由于键不是匿名值,因此最好在 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);

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

您可以将类似的东西打包在 ICustomization 中对于 Dictionary<string, string> ,这意味着当你请求很多 Dictionary<string, string>值,你会得到多个这样创建的字典。

关于c# - Autofixture,创建一个字典列表<string, object> 交替键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37511519/

相关文章:

Java数据结构,一个以value里面的对象为key的map

c# - AutoFixture CompositeDataAttribute 不适用于 PropertyDataAttribute

c# - 如何使用 autofixture 在子属性中自动设置父对象

c# - IRS ACA 提交 - 错误 TPE1122,消息中的 WS 安全 header 无效

c# - 如何获取 WPF 用户控件可见部分的大小?

c# 如果触发 DataError 则获取单元格文本值

python - 如何在 1 行代码中不使用 for 循环来创建字典?

c# - 如何知道给定的字体是否是 OpenType 字体

python - 用于在 Python 中解析复杂制表符分隔/csv 文件的循环

AutoFixture 和自定义数据注释