【发布时间】:2011-05-31 00:34:39
【问题描述】:
查看here 的帖子时,看起来我应该能够使用CreateMany() 创建多个对象,使用foreach 迭代它们,然后将它们作为数组返回。
我看到的是每次迭代似乎每次都创建新对象。这是预期的行为吗?
要创建的实体:
public class TestEntity
{
public int Id { get; private set; }
public string SomeString { get; set; }
public void SetId(int value)
{
this.Id = value;
}
}
示例 Program.cs:
private static int id;
static void Main(string[] args)
{
var fixture = new Fixture();
IEnumerable<TestEntity> testEntities =
fixture.Build<TestEntity>().CreateMany(5);
Output(testEntities);
foreach (var testEntity in testEntities)
{
testEntity.SetId(id++);
Console.WriteLine(
string.Format("CHANGED IN FOREACH:: hash: {0}, id: {1}, string: {2}",
testEntity.GetHashCode(), testEntity.Id, testEntity.SomeString));
}
Output(testEntities);
}
private static void Output(IEnumerable<TestEntity> testEntities)
{
foreach (var testEntity in testEntities)
{
Console.WriteLine(
string.Format("hash: {0}, id: {1}, string: {2}",
testEntity.GetHashCode(), testEntity.Id, testEntity.SomeString));
}
}
我创建了一个问题 here(如果这是预期行为,可能会被删除)。
编辑 2011-06-02
要获得我期望的行为,如果我不想修改 AutoFixture 行为,我可以使用扩展方法:
var fixture = new Fixture();
TestEntity[] testEntities = fixture.Build<TestEntity>().CreateMany(5).ToArray();
【问题讨论】:
标签: c# autofixture