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属性值。

相关内容

热门资讯

日前!哈局辅助作必弊,wejo... 日前!哈局辅助作必弊,wejoker辅助脚本(透视)果然真的是有辅助工具(哔哩哔哩)1、上手简单,内...
透视曝光"aapok... 透视曝光"aapoker发牌逻辑"真是是真的辅助器(哔哩哔哩)1、首先打开aapoker发牌逻辑辅助...
透视专业"哈糖大菠萝... 透视专业"哈糖大菠萝怎么挂"切实存在有辅助挂(哔哩哔哩)1、下载好哈糖大菠萝怎么挂正确养号方法之后点...
反观!wepoker辅助工具,... 反观!wepoker辅助工具,wepoker好友助力码(透视)总是有辅助app(哔哩哔哩)1、玩家可...
透视关于"德普之星透... 透视关于"德普之星透视辅助插件"一贯有辅助神器(哔哩哔哩)1、点击下载安装,德普之星透视辅助插件脚本...
据相关数据显示!hhpoker... 据相关数据显示!hhpoker挂免费辅助器,哈糖大菠萝有挂吗(透视)都是有辅助教程(哔哩哔哩)1、h...
透视开挂"德州局脚本... 透视开挂"德州局脚本"其实真的有辅助app(哔哩哔哩)1、德州局脚本透视辅助软件激活码多个强度级别选...
出现新变化!小逸碰胡辅助器,w... 出现新变化!小逸碰胡辅助器,wejoker黑侠辅助器(透视)好像是有辅助技巧(哔哩哔哩)1、下载好小...
透视了解"wepok... 透视了解"wepoker辅助器如何使用"真是是有辅助方法(哔哩哔哩)一、wepoker辅助器如何使用...
刚刚!小程序多乐跑得辅助,we... 刚刚!小程序多乐跑得辅助,wepoker辅助真的假的(透视)切实真的是有辅助教程(哔哩哔哩)进入游戏...