【发布时间】: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<List<IDictionary<string, string>>>();,正如 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<List<IDictionary<string, string>>>();怎么样? -
解决了值部分,但是是否可以自动生成具有两个键值对的字典,第一个键是“productno”,第二个键是“productname”?
-
第一个键是什么意思?字典没有排序...
-
在上面的示例中,我在字典中使用了两个键/值对,这两个需要将“productno”和“productname”作为键,将字符串作为值。顺序无关紧要
-
所以你需要确定性的键,但需要随机值?
标签: c# dictionary autofixture