AutoFixture - 添加一个自定义项,使所有字典键都使用对象ID创建
创始人
2024-11-12 13:30:19
0

要使用AutoFixture添加一个自定义项,使所有字典键都使用对象ID创建,可以使用AutoFixture的自定义规则功能。

首先,您需要创建一个自定义规则来生成字典键。这可以通过实现ISpecimenBuilder接口来完成。以下是一个示例实现:

public class ObjectIdKeyBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var type = request as Type;
        if (type == null || !type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Dictionary<,>))
        {
            return new NoSpecimen();
        }

        var keyType = type.GetGenericArguments()[0];
        var objectId = ObjectId.GenerateNewId().ToString();
        var key = context.Resolve(new SeededRequest(keyType, objectId));
        return key;
    }
}

然后,您可以在测试中使用此自定义规则。下面是一个完整的示例:

using AutoFixture;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using Xunit;

public class DictionaryTests
{
    [Fact]
    public void TestDictionaryWithObjectIdKeys()
    {
        var fixture = new Fixture();
        fixture.Customizations.Add(new ObjectIdKeyBuilder());

        var dictionary = fixture.Create>();

        foreach (var key in dictionary.Keys)
        {
            Assert.True(ObjectId.TryParse(key, out _));
        }
    }
}

public class ObjectIdKeyBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var type = request as Type;
        if (type == null || !type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Dictionary<,>))
        {
            return new NoSpecimen();
        }

        var keyType = type.GetGenericArguments()[0];
        var objectId = ObjectId.GenerateNewId().ToString();
        var key = context.Resolve(new SeededRequest(keyType, objectId));
        return key;
    }
}

在上面的示例中,我们创建了一个新的Fixture实例,并添加了自定义规则ObjectIdKeyBuilder。然后,我们使用fixture.Create>()生成一个带有ObjectId作为键的字典。最后,我们使用Assert语句来验证所有字典键都是有效的ObjectId。

请注意,此示例使用了MongoDB的ObjectId类型,您可以根据自己的需求替换为其他类型。

相关内容

热门资讯

透视讲解!wepoker作弊辅... 透视讲解!wepoker作弊辅助,aapoker透视脚本,透明挂教程(果然真的有挂);亲,其实确实真...
辅助透视!德普之星有没有挂,w... 辅助透视!德普之星有没有挂,wepoker透视脚本苹果版,2025新版总结(果然是真的有挂)科技教程...
透视软件!wpk透视表,约局吧... 透视软件!wpk透视表,约局吧开挂神器是真的吗,曝光教程(都是存在有挂);人气非常高,ai更新快且高...
透视挂透视!智星德州菠萝透视插... 透视挂透视!智星德州菠萝透视插件工具,德普辅助器辅助器怎么用,德州论坛(本然是真的有挂);大神普及一...
透视系统!aapoker辅助插... 透视系统!aapoker辅助插件工具,aapoker透视脚本,力荐教程(果然是真的有挂);原来确实真...
透视攻略!hhpoker透视方... 透视攻略!hhpoker透视方法,aapoker免费透视脚本,透明挂教程(真是有挂);最新版2024...
透视数据!aapoker可以开... 透视数据!aapoker可以开挂吗,wepoker透视脚本是什么,普及教程(从前有挂);《WPK辅助...
透视辅助!aapoker辅助插... 1、透视辅助!aapoker辅助插件工具,德普之星辅助软件,可靠教程(原先真的是有挂);详细教程。2...
透视辅助!aapoker透视怎... 透视辅助!aapoker透视怎么用,hhpoker德州挂真的有吗,系统教程(先前有挂);支持2-10...
透视辅助!wpk透视脚本,来玩... 透视辅助!wpk透视脚本,来玩德州破解器,力荐教程(从前是真的有挂);原来确实真的有挂(需添加指定Q...