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

相关内容

热门资讯

黑科技玄学(wpk私人局)外挂... 黑科技玄学(wpk私人局)外挂透明挂辅助黑科技(透明黑科技)真是是真的有挂(发现有挂)-哔哩哔哩;一...
黑科技免费(wpk猫腻)外挂透... 黑科技免费(wpk猫腻)外挂透明挂辅助器(透明挂黑科技)都是有挂(有挂教学)-哔哩哔哩1、玩家可以在...
黑科技苹果版(线上微扑克)外挂... 黑科技苹果版(线上微扑克)外挂透明挂辅助下载(透明挂黑科技)总是真的是有挂(存在有挂)-哔哩哔哩黑科...
黑科技安卓版(wepoke智能... 黑科技安卓版(wepoke智能ai)外挂透明挂辅助插件(辅助挂)本来是真的有挂(证实有挂)-哔哩哔哩...
黑科技免费(最新版wpk)外挂... 黑科技免费(最新版wpk)外挂透明挂辅助AI(软件透明挂)一贯是有挂(有挂方略)-哔哩哔哩1、首先打...
黑科技安装(aapoker正规... 黑科技安装(aapoker正规)外挂透明挂辅助下载(透视)都是有挂(真的有挂)-哔哩哔哩1、很好的工...
黑科技好友房(约局吧)外挂透明... 黑科技好友房(约局吧)外挂透明挂辅助AI(透视)切实真的有挂(有挂细节)-哔哩哔哩1、黑科技好友房(...
黑科技教程(wepoke模拟器... 黑科技教程(wepoke模拟器)外挂透明挂辅助挂(透明挂黑科技)竟然是真的有挂(有挂辅助)-哔哩哔哩...
黑科技黑科技(Wepoke工具... 黑科技黑科技(Wepoke工具)外挂透明挂辅助设备(ai代打)其实是真的有挂(有挂详细)-哔哩哔哩W...
黑科技黑科技(wpk胜率)外挂... 黑科技黑科技(wpk胜率)外挂透明挂辅助代打(辅助挂)一贯有挂(有挂方针)-哔哩哔哩1、wpk胜率系...