AutoFixture无法为使用System.ComponentModel.DataAnnotations.RangeAttribute的decimal属性创建对象。
创始人
2024-11-12 14:00:17
0

AutoFixture无法为使用System.ComponentModel.DataAnnotations.RangeAttribute的decimal属性创建对象的问题可以通过自定义AttributeRelay来解决。下面是一个代码示例:

using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using AutoFixture;
using AutoFixture.Kernel;

public class RangeAttributeRelay : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var property = request as PropertyInfo;
        if (property == null)
        {
            return new NoSpecimen();
        }

        var rangeAttribute = property.GetCustomAttribute();
        if (rangeAttribute != null && property.PropertyType == typeof(decimal))
        {
            return context.Resolve(rangeAttribute.Minimum);
        }

        return new NoSpecimen();
    }
}

public class MyClass
{
    [Range(1.0, 10.0)]
    public decimal MyProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var fixture = new Fixture();
        fixture.Customizations.Add(new RangeAttributeRelay());

        var myClass = fixture.Create();

        Console.WriteLine(myClass.MyProperty);
    }
}

上面的代码示例中,我们自定义了一个RangeAttributeRelay类,实现了ISpecimenBuilder接口。在Create方法中,我们通过反射获取属性上的RangeAttribute,并判断属性类型是否为decimal。如果满足条件,我们使用AutoFixture的Resolve方法来生成满足RangeAttribute要求的decimal对象。

在Main方法中,我们首先创建了一个Fixture对象,并添加了自定义的RangeAttributeRelay。然后使用fixture.Create方法来创建MyClass对象,此时AutoFixture就能够正确生成满足RangeAttribute要求的decimal属性对象。

运行上述代码,输出将会是一个满足范围要求的decimal属性值。

相关内容

热门资讯

黑科技真的(WPK线上)WeP... 黑科技真的(WPK线上)WePoKer本然真的有挂!太坑了一直是真的有挂(2025已更新)(哔哩哔哩...
黑科技模拟器(手机德州app)... 黑科技模拟器(手机德州app)Wepoke确实真的是有挂!太夸张了竟然真的是有挂(2023已更新)(...
黑科技辅助(德扑安卓)来玩德州... 【福星临门,好运相随】;黑科技辅助(德扑安卓)来玩德州app本然有挂!太夸张了原生有挂(2025已更...
黑科技游戏(WPK外挂)x-p... 黑科技游戏(WPK外挂)x-poker先前是真的有挂!太坑了固有是有挂(2023已更新)(哔哩哔哩)...
黑科技好牌(wpk代打)We辅... 自定义We辅poker助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不...
黑科技规律(德扑之星概率)x-... 黑科技规律(德扑之星概率)x-poker原来存在有挂!太离谱了起初是有挂(2022已更新)(哔哩哔哩...
黑科技游戏(大厅wpk)pok... 黑科技游戏(大厅wpk)pokermaster原先有挂!太嚣张了真是是有挂(2021已更新)(哔哩哔...
黑科技规律(Wepoke模拟器... 黑科技规律(Wepoke模拟器)wEpOke从来存在有挂!太夸张了固有真的有挂(2022已更新)(哔...
黑科技安卓版(wepoke免费... 黑科技安卓版(wepoke免费)线上德州往昔有挂!太坑了固有是真的有挂(2025已更新)(哔哩哔哩)...
黑科技讲解(WPK插件)wEp... 黑科技讲解(WPK插件)wEpOke往昔有挂!太坑了原先真的有挂(2020已更新)(哔哩哔哩);建议...