【问题标题】:Autofixture create class from 3rd party library that has an inaccessible internal constructorAutofixture 从具有无法访问的内部构造函数的 3rd 方库创建类
【发布时间】:2019-07-10 13:14:34
【问题描述】:

我想使用 Autofixture 创建一个类的实例,我从 3rd 方库中使用该实例。

我面临的问题是这个类的构造函数有一个内部访问修饰符,并且来自第 3 方解决方案我不能真正使用 InternalsVisibleTo 属性,所以我想知道是否有任何 Autofixture 行为可以使用或者是否有任何替代技术可以应用于此类场景。

public class RecordedEvent
  {
    /// <summary>The Event Stream that this event belongs to</summary>
    public readonly string EventStreamId;
    /// <summary>The Unique Identifier representing this event</summary>
    public readonly Guid EventId;
    /// <summary>The number of this event in the stream</summary>
    .....

    internal RecordedEvent(....)
    {
      .....
    }
  }

【问题讨论】:

    标签: autofixture


    【解决方案1】:

    OOTB,AutoFixture 试图找到能够创建类实例的公共构造函数或静态工厂方法。由于您不拥有RecordedEvent 并且无法添加公共构造函数,因此您必须 AutoFixture 如何实例化它。有一种称为Customizations 的机制可以用于此。

    首先你创建一个自定义,它能够找到一个类型的所有内部构造函数:

    public class InternalConstructorCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Customize<RecordedEvent>(c =>
                c.FromFactory(
                    new MethodInvoker(
                        new InternalConstructorQuery())));
        }
    
        private class InternalConstructorQuery : IMethodQuery
        {
            public IEnumerable<IMethod> SelectMethods(Type type)
            {
                if (type == null) { throw new ArgumentNullException(nameof(type)); }
    
                return from ci in type.GetTypeInfo()
                        .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)
                       select new ConstructorMethod(ci) as IMethod;
            }
        }
    }
    

    然后你将它应用到你的Fixture:

    var fixture = new Fixture()
        .Customize(new InternalConstructorCustomization());
    

    然后您可以创建RecordedEvent 类的实例:

    var recordedEvent = fixture.Create<RecordedEvent>(); // does not throw
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 2018-07-09
      • 2017-07-13
      • 2011-10-26
      • 1970-01-01
      相关资源
      最近更新 更多