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

相关内容

热门资讯

值得注意的是!hhpkoer辅... 值得注意的是!hhpkoer辅助挂是真的吗,德扑之心免费透视,总是存在有挂(有挂详细)德扑之心免费透...
今日百科!wepoker怎么下... 今日百科!wepoker怎么下载游戏,wepoker软件安装包,好像真的是有挂(存在有挂)1、完成有...
总结辅助挂!红龙poker有辅... 总结辅助挂!红龙poker有辅助吗,德扑之星透视辅助插件,总是是真的有挂(有挂总结)1、点击下载安装...
实测必看!wepoker安装教... 实测必看!wepoker安装教程,wepoker数据分析工具,一直是有挂(有挂透视)1、下载好脚本下...
现就发布提示!wepoker透... 现就发布提示!wepoker透视辅助下载,德扑之星辅助工具如何打开,确实真的是有挂(有挂解惑)1、德...
热点推荐!哈糖大菠萝攻略,红龙... 热点推荐!哈糖大菠萝攻略,红龙poker作弊指令,好像有挂(确实有挂)1、进入游戏-大厅左侧-新手福...
目前来看!哈糖大菠萝能开挂吗,... 目前来看!哈糖大菠萝能开挂吗,德普之星透视辅助软件是真的吗,本来真的有挂(有挂技巧)1、下载好德普之...
玩家必看科普!wejoker手... 玩家必看科普!wejoker手机版透视脚本,德普之星透视辅助软件下载,切实是真的有挂(有挂教程);小...
截至目前!hhpoker辅助器... 截至目前!hhpoker辅助器,德普之星辅助器,本来是真的有挂(有挂神器)1、用户打开应用后不用登录...
三分钟了解!poker mas... 三分钟了解!poker master辅助,wepoker作弊视频,真是真的有挂(有挂分析)1、让任何...