【问题标题】:Autofixture, create a list of dictionary<string, object> with alternating keyAutofixture,使用交替键创建字典<string, object> 列表
【发布时间】:2016-09-27 10:45:55
【问题描述】:

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

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

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

我尝试了var dicts = new Fixture().Create&lt;List&lt;IDictionary&lt;string, string&gt;&gt;&gt;();,正如 cmets 中指出的那样,它给了我一个包含三个字典的列表,每个字典都有一个 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)

【问题讨论】:

  • var dicts = new Fixture().Create&lt;List&lt;IDictionary&lt;string, string&gt;&gt;&gt;(); 怎么样?
  • 解决了值部分,但是是否可以自动生成具有两个键值对的字典,第一个键是“productno”,第二个键是“productname”?
  • 第一个键是什么意思?字典没有排序...
  • 在上面的示例中,我在字典中使用了两个键/值对,这两个需要将“productno”和“productname”作为键,将字符串作为值。顺序无关紧要
  • 所以你需要确定性的键,但需要随机值?

标签: c# dictionary autofixture


【解决方案1】:

使用确定性键创建字典相当容易。由于键不是匿名值,因此最好在 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&lt;string, string&gt; 打包类似的内容,这意味着当您请求许多 Dictionary&lt;string, string&gt; 值时,您将获得多个这样创建的字典。

【讨论】:

  • 我最终得到的确切解决方案是(例如创建 100 个字典)var list = Enumerable.Repeat(0, 100).Select(s =&gt; columns.Zip(values, Tuple.Create).ToDictionary(t =&gt; t.Item1, t =&gt; t.Item2));
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多