gpt4 book ai didi

c# - 使用 AutoFixture 为字符串属性生成匿名数字

转载 作者:太空狗 更新时间:2023-10-30 00:43:56 25 4
gpt4 key购买 nike

我正在对一些映射方法进行单元测试,我有一个字符串类型的源属性映射到一个整数类型的目标属性。

所以我希望 AutoFixture 为特定字符串属性(而不是所有字符串属性)创建带有匿名整数的源对象。

这可能吗?

最佳答案

解决此问题的最佳方法是 create a convention based custom value generator将匿名数值的字符串表示分配给特定属性,基于其名称

所以,举个例子,假设你有一个这样的类:

public class Foo
{
public string StringThatReallyIsANumber { get; set; }
}

自定义值生成器如下所示:

public class StringThatReallyIsANumberGenerator : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var targetProperty = request as PropertyInfo;

if (targetProperty == null)
{
return new NoSpecimen(request);
}

if (targetProperty.Name != "StringThatReallyIsANumber")
{
return new NoSpecimen(request);
}

var value = context.CreateAnonymous<int>();

return value.ToString();
}
}

这里的关键点是自定义生成器将只针对名为 StringThatReallyIsANumber 的属性,在本例中这是我们的约定

为了在您的测试中使用它,您只需通过 Fixture.Customizations 集合将它添加到您的 Fixture 实例:

var fixture = new Fixture();
fixture.Customizations.Add(new StringThatReallyIsANumberGenerator());

var anonymousFoo = fixture.CreateAnonymous<Foo>();

关于c# - 使用 AutoFixture 为字符串属性生成匿名数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9209050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com