c# – 如何使用AutoFixture与NSubstitute的示例

我使用NSubstitute很多.我爱它

我只是看AutoFixture.看起来很棒!

我已经看到了AutoFixture for NSubstitute,并在Moq中看到了一些关于如何使用这个功能的例子.

但我似乎无法将其翻译成NSubstitute.

我试过这个:

var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());  
var addDest = Substitute.For<IPerson>();

使用:

public interface IPersonEntity
{    
   int ID { get; set; }
   string FirstName { get; set;}
   string LastName { get; set;}
   DateTime DateOfBirth { get; set; }
   char Gender { get; set; }    
}

我得到一个对象,但是没有一个属性被填充(类型为AutoFixture).

我也试过:

var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
var result = fixture.Create<IPersonEntity>();

这也给了我一个没有人口稠密属性的对象. (注意,如果我使用PersonEntity类执行上述操作,则所有属性都将被填充.)

我相信有办法使这项工作,但我似乎找不到.

所以,考虑到我的IPersonEntity接口,有谁知道如何使用AutoFixture和NSubstitute给我一个填充IPersonEntity对象?

解决方法

您可以使用AutoNSubstituteCustomization自定义Fixture实例,而不是使用以下定制:
var fixture = new Fixture().Customize(
    new AutopopulatednSubstitutePropertiesCustomization());

var result = fixture.Create<IPersonEntity>();
// -> All properties should be populated Now.

AutopopulatednSubstitutePropertiesCustomization定义为:

internal class AutopopulatednSubstitutePropertiesCustomization
    : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.ResidueCollectors.Add(
            new Postprocessor(
                new NSubstituteBuilder(
                    new MethodInvoker(
                        new NSubstituteMethodQuery())),new AutopropertiesCommand(
                    new PropertiesOnlySpecification())));
    }

    private class PropertiesOnlySpecification : IRequestSpecification
    {
        public bool IsSatisfiedBy(object request)
        {
            return request is PropertyInfo;
        }
    }
}

与AutoNSubstituteCustomization的区别在于,上述定制也是decorated,后处理器实例自动设置所请求类型的所有公共属性的值.

参考文献:

上述解决方案的灵感来自以下博客文章Mark Seemann

> How to configure AutoMoq to set up all properties
> How to automatically populate properties with AutoMoq

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么