AutoFixture.AutoMoq supply a known value for one constructor parameter

后端 未结 6 1311
悲哀的现实
悲哀的现实 2020-12-13 14:52

I\'ve just started to use AutoFixture.AutoMoq in my unit tests and I\'m finding it very helpful for creating objects where I don\'t care about the specific

6条回答
  •  悲&欢浪女
    2020-12-13 14:56

    You could do something like this. Imagine that you want to assign a particular value to the TimeSpan argument called lifespan.

    public class LifespanArg : ISpecimenBuilder
    {
        private readonly TimeSpan lifespan;
    
        public LifespanArg(TimeSpan lifespan)
        {
            this.lifespan = lifespan;
        }
    
        public object Create(object request, ISpecimenContext context)
        {
            var pi = request as ParameterInfo;
            if (pi == null)
                return new NoSpecimen(request);
    
            if (pi.ParameterType != typeof(TimeSpan) ||
                pi.Name != "lifespan")   
                return new NoSpecimen(request);
    
            return this.lifespan;
        }
    }
    

    Imperatively, it could be used like this:

    var fixture = new Fixture();
    fixture.Customizations.Add(new LifespanArg(mySpecialLifespanValue));
    
    var sut = fixture.Create();
    

    This approach can be generalized to some degree, but in the end, we're limited by the lack of a strongly typed way to extract a ParameterInfo from a particular constructor or method argument.

提交回复
热议问题