如何使用Autofixture生成字典

Joh*_*ohn 12 c# dictionary autofixture

对于列表,我们可以做到

fixture.CreateMany<List<string>>(1000); // with 1000 elements
Run Code Online (Sandbox Code Playgroud)

但如何用字典做呢?并且能够指定要生成的元素数量

小智 18

您可以简单地创建项目然后构建字典,如下所示:

fixture
  .CreateMany<KeyValuePair<int, string>>(1000)
  .ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)

这或多或少是AutoFixture 内部所做的.

另一种选择是创建一个新的ICustomization,拦截任何请求Dictionary<,>并构建它们.它可以使用现有 类中的代码实现.