简体   繁体   English

如何使用AutoFixture自动生成包含只读列表的对象?

[英]How do I auto-generate objects containing a readonly list using AutoFixture?

I have a class that conceptually looks like this: 我有一个概念上看起来像这样的课:

public class Entity
{
    private readonly List<double> _values = new List<double>();

    ...

    public List<double> Values
    {
        get
        {
            return _values;
        }
    }
}

In a unit test, I want to use AutoFixture to provide a list of random entities: 在单元测试中,我想使用AutoFixture提供随机实体的列表:

var entities = this.fixture.CreateMany<Entity>().ToList();

However, no autogenerated values are added to the Values property of the Entity objects, as I would have expected (hoped...). 但是,没有自动生成的值被添加到Entity对象的Values属性中,正如我所期望的那样(希望...)。 I have tried to change the list of values to not being readonly and add a setter to the Values property, which solves the problem, but isn't there a better alternative to this? 我试图将值列表更改为非只读,并向Values属性添加了一个setter,这解决了问题,但是没有更好的替代方法吗?

AutoFixture doesn't fill read-only collections, but you can ask it to do so: AutoFixture不会填充只读集合,但是您可以要求它这样做:

var entity = fixture.Create<Entity>();
fixture.AddManyTo(entity.Values);

When I discovered this limitation, I went ahead and created an AutoFixture extension to do just this: Murph.AutoFixture.AutoReadOnlyCollectionProperties . 当发现此限制时,我继续创建一个AutoFixture扩展来做到这一点: Murph.AutoFixture.AutoReadOnlyCollectionProperties Publicly available on nuget.org as well. 也可以在nuget.org上公开获得。

While building an object, for any public, read-only property or field whose type implements ICollection<T> , it will use the fixture to create a list of T and then call the collection's Add() method for each one. 在构建对象时,对于其类型实现ICollection<T>任何公共,只读属性或字段,它将使用固定装置创建T的列表,然后为每个对象调用集合的Add()方法。 It will respect the fixture's OmitAutoProperties setting, and also provides an extension method, WithoutEx() that emulates the built-in Without() (which won't work with read-only properties or fields). 它将遵循灯具的OmitAutoProperties设置,并提供一个扩展方法WithoutEx()来模拟内置的Without() (不适用于只读属性或字段)。

Usage is as easy as you'd expect: 使用就像您期望的那样简单:

fixture.Customize( new AutoReadOnlyCollectionPropertiesCustomization() );
fixture.Customize< Model >( c => c.WithoutEx( m => m.Collection ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM