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

相关内容

热门资讯

热点讨论!微信微乐小程序辅助器... 热点讨论!微信微乐小程序辅助器免费安装,微乐家乡小程序自建房辅助app-都是存在有辅助工具(有挂教学...
实测教程!微信小程序微乐房间怎... 实测教程!微信小程序微乐房间怎么开挂,微信自建房辅助多少钱一个月-真是存在有辅助app(有挂秘籍)1...
热点推荐!微乐家乡麻将辅助,陕... 您好,微乐家乡麻将辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
一分钟带你了解!微乐小程序微乐... 一分钟带你了解!微乐小程序微乐辅助软件,微乐家乡破解版-切实是真的有辅助插件(发现有挂)1、让任何用...
玩家爆料!微乐家乡麻辣自建房辅... 玩家爆料!微乐家乡麻辣自建房辅助app,微乐小程序破解版修改器-都是有辅助挂(有挂方法)1、完成微乐...
我来教教你!微乐小程序游戏破解... 我来教教你!微乐小程序游戏破解器,微乐小程序免费脚本-竟然有辅助app(揭秘有挂)1、起透看视 微乐...
科技揭秘!微乐小程序游戏破解器... 您好,微乐小程序游戏破解器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
免费测试版!微信微乐小程序修改... 免费测试版!微信微乐小程序修改器,手机微乐小程序破解器如何使用-原来真的有辅助工具(有挂方式)1、完...
必知教程!微乐小程序免费工具,... 必知教程!微乐小程序免费工具,微乐江苏自建房辅助app-都是存在有辅助挂(有挂秘诀)1、微乐小程序免...
推荐十款!微乐小程序脚本工具平... 推荐十款!微乐小程序脚本工具平台,微信小程序微乐辅助-果然是真的有辅助app(有挂讲解)1、玩家可以...