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

相关内容

热门资讯

科普透视!wepoker有透视... 科普透视!wepoker有透视功能吗,微信微乐跑得快游戏辅助脚本,机巧教程(有挂猫腻)-哔哩哔哩1、...
总结透视!来玩app破解版,微... 总结透视!来玩app破解版,微乐陕西小程序脚本,教材教程(有挂技巧)-哔哩哔哩1、进入游戏-大厅左侧...
解密透视!福建大菠萝万能辅助器... 解密透视!福建大菠萝万能辅助器,微乐微信小程序辅助软件,手段教程(有挂教学)-哔哩哔哩进入游戏-大厅...
推荐透视!德普之星透视软件免费... 您好,德普之星透视软件免费入口官网这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...
教你透视!hhpoker可以控... 教你透视!hhpoker可以控制牌吗,微乐小程序辅助多少钱,诀窍教程(有挂方针)-哔哩哔哩一、hhp...
解迷透视!大菠萝辅助器,微乐小... 您好,大菠萝辅助器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
必备透视!德州透视插件,微信小... 必备透视!德州透视插件,微信小程序 微乐陕西挖坑 外挂,方式教程(讲解有挂)-哔哩哔哩1、下载好德州...
详细透视!we-poker辅助... 详细透视!we-poker辅助软件教程,微乐小程序辅助器免费安卓,方针教程(确实有挂)-哔哩哔哩1、...
揭露透视!wepoker免费透... 揭露透视!wepoker免费透视,微乐小程序游戏破解器,演示教程(有挂详细)-哔哩哔哩1、超多福利:...
教你透视!哈糖大菠萝挂,微信小... 教你透视!哈糖大菠萝挂,微信小程序辅助多少钱,绝活儿教程(真的有挂)-哔哩哔哩1、每一步都需要思考,...