Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Autofixture能否创建匿名类型?_C#_Unit Testing_Autofixture - Fatal编程技术网

C# Autofixture能否创建匿名类型?

C# Autofixture能否创建匿名类型?,c#,unit-testing,autofixture,C#,Unit Testing,Autofixture,假设我希望在单元测试中调用以返回如下所示的匿名类型- var anonymousType = { id = 45, Name="MyName", Description="Whatever" } Autofixture能否生成匿名类型?如果是,语法是什么?否,AutoFixture不支持匿名类型,因为它们是使用它们的库的内部类型。作为@MarkSeemann,AutoFixture不能支持匿名类型 关于自动夹具和动态夹具的注记 这可能不适用于您的特定情况,但我认为值得一提的是,如果您需要在测试

假设我希望在单元测试中调用以返回如下所示的匿名类型-

var anonymousType = { id = 45, Name="MyName", Description="Whatever" }

Autofixture能否生成匿名类型?如果是,语法是什么?

否,AutoFixture不支持匿名类型,因为它们是使用它们的库的内部类型。

作为@MarkSeemann,AutoFixture不能支持匿名类型

关于自动夹具和动态夹具的注记 这可能不适用于您的特定情况,但我认为值得一提的是,如果您需要在测试中创建动态类型对象的实例,并且您不关心它们的特定状态,那么您可以配置AutoFixture来创建响应您对其调用的任何属性或方法的实例

下面是一个例子:

public class DynamicCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customizations.Insert(
            0,
            new FilteringSpecimenBuilder(
                new FixedBuilder(new AnythingObject()),
                new ExactTypeSpecification(typeof(object))));
    }

    private class AnythingObject : DynamicObject
    {
        public override bool TryGetMember(
            GetMemberBinder binder,
            out object result)
        {
            result = new AnythingObject();
            return true;
        }

        public override bool TryInvokeMember(
            InvokeMemberBinder binder,
            object[] args,
            out object result)
        {
            result = new AnythingObject();
            return true;
        }
    }
}
在这种情况下,
AnythingObject
只是为它接收到调用的任何属性或方法返回其自身的新实例。这将允许您说,例如:

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

var foo = fixture.Create<dynamic>();

Assert.NotNull(foo.Bar);
Assert.NotNull(foo.Baz());
在这里,我们正在寻找一个名为
“Bar”
的属性,并为它提供一个
字符串
,而其他所有内容只会得到
AnythingObject
的实例。因此,我们可以说:

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

var foo = fixture.Create<dynamic>();

Assert.IsType<string>(foo.Bar);
Assert.NotNull(foo.Baz);
var fixture=newfixture();
fixture.Customize(新的dynamicCustomize());
var foo=fixture.Create();
Assert.IsType(foo.Bar);
Assert.NotNull(foo.Baz);

考虑避免匿名类型,因为它们对于系统的其他部分不是太透明。您总是创建一个DTO对象,或者只是使用字典。每当您希望使用匿名类型时,要考虑两次,然后考虑使用DTO;虽然马克的答案是正确的,但这很有趣,我一定会玩它。非常感谢你。
var fixture = new Fixture();
fixture.Customize(new DynamicCustomization());

var foo = fixture.Create<dynamic>();

Assert.IsType<string>(foo.Bar);
Assert.NotNull(foo.Baz);