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

相关内容

热门资讯

透视讲解!云麻圈修改器,新悠悠... 透视讲解!云麻圈修改器,新悠悠挂(透视)开挂辅助下载第三方教程;无需打开直接搜索加(薇:136704...
往昔有辅助"赣牌圈小... 往昔有辅助"赣牌圈小程序靠谱吗"详细开挂辅助软件有挂详细(透明挂教程!)您好:赣牌圈小程序靠谱吗这款...
大纲开挂"打哈儿辅助... 大纲开挂"打哈儿辅助安卓系统"开挂(修改器)辅助脚本(今日头条) 了解更多开挂安装加(1367043...
从来有开挂"衡阳丫丫... 从来有开挂"衡阳丫丫辅助"开挂(透视)辅助插件(微扑克教程有挂细节)衡阳丫丫辅助ai黑科技系统规律教...
透视游戏!510k脚本,wpk... 透视游戏!510k脚本,wpk俱乐部有没有辅助(透视)开挂辅助工具安装教程;无需打开直接搜索薇:13...
往昔有开挂"决战卡五... 往昔有开挂"决战卡五星辅助ios"详细开挂辅助下载有挂分享(2026新版技巧);无需打开直接搜索加(...
指引开挂"微信微乐自... 指引开挂"微信微乐自建房辅助工具"开挂(透视)辅助安装(有挂教程)这是一款可以让一直输的玩家,快速成...
原本有辅助"微乐小程... >>您好:微乐小程序礼包码确实是有挂的,很多玩家在这款微乐小程序礼包码游戏中打牌都会发现很多用户的牌...
透视脚本!来玩app辅助器,微... 透视脚本!来玩app辅助器,微信小程序微乐辅助器app(透视)开挂辅助脚本德州教程>>您好:软件加1...
本来有辅助"传送屋辅... 传送屋辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软件...