gpt4 book ai didi

c# - 使用内部 JSON 构造函数在 AutoFixture 4.8.0 中创建公共(public)类型,并带有许多构造函数参数

转载 作者:行者123 更新时间:2023-11-30 22:56:07 30 4
gpt4 key购买 nike

与 AutoFixture 4.8.0 一样,是否有更好的替代方法来使用 Fixture.Register 注册函数来创建仅公开内部构造函数的类型?

上下文:

我正在开发一个 .net 标准类库来构建供内部使用的 API。我们不想公开公共(public)构造函数,因此这些模型的所有构造函数都是内部。另外,属性是公共(public)只读。这些类将通过 Json 反序列化进行实例化,并且在这个特定的库中,有一个具有超过 20 个属性的模型需要考虑。作为奖励,我们希望尽可能使用 [AutoDataAttribute]。

即。是否有其他方法可以使用 AutoFixture 提供具有 20 多个参数的非类型和复杂类型(也是内部类型)混合的内部 json 构造函数?

[TestFixture]
public sealed class Tests
{
private Fixture _fixture;

[OneTimeSetUp]
public void OneTimeSetup()
{
_fixture = new Fixture();

_fixture.Register(() => new Vehicle(_fixture.Create<string>(), _fixture.Create<int>()));

_fixture.Register(
() => new Driver(_fixture.Create<string>(), _fixture.Create<int>(), _fixture.Create<Vehicle>()));
}

[Test]
public void CanCreateDriverWithVehicle()
{
Func<Driver> func = () => _fixture.Create<Driver>();
func.Should().NotThrow(); // Green
}
}

[PublicAPI]
public sealed class Driver
{
public readonly string Name;
public readonly int Age;
public Vehicle Vehicle;

[JsonConstructor]
internal Driver(string name, int age, Vehicle vehicle)
{
Name = name;
Age = age;
Vehicle = vehicle;
}
}

[PublicAPI]
public sealed class Vehicle
{
public readonly string Manufacturer;
public readonly int Miles;

[JsonConstructor]
internal Vehicle(string manufacturer, int miles)
{
Manufacturer = manufacturer;
Miles = miles;
}
}

最佳答案

默认情况下,AutoFixture 仅考虑公共(public)构造函数。它不会获取内部构造函数,即使它们可以从测试执行程序集访问(甚至不确定是否有合理的技术可能性来检查)。

您可以轻松定制您的装置来支持这一点。从以下代码示例中获取灵感:

[Fact]
public void ShouldActivateTypesWithInternalConstructor()
{
var fixture = new Fixture();

fixture.ResidueCollectors.Add(
new Postprocessor(
new MethodInvoker(
new ModestInternalConstructorQuery()),
new AutoPropertiesCommand()
));

var result = fixture.Create<TypeWithInternalConstructor>();

Assert.NotEqual(0, result.Property);
}

public class ModestInternalConstructorQuery : IMethodQuery
{
public IEnumerable<IMethod> SelectMethods(Type type)
{
if (type == null) throw new ArgumentNullException(nameof(type));

return from ci in type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)
where ci.IsAssembly // Take internal constructors only
let parameters = ci.GetParameters()
where parameters.All(p => p.ParameterType != type)
orderby parameters.Length ascending
select new ConstructorMethod(ci) as IMethod;
}
}

public class TypeWithInternalConstructor
{
public int Property { get; }

internal TypeWithInternalConstructor(int property)
{
Property = property;
}
}

关于c# - 使用内部 JSON 构造函数在 AutoFixture 4.8.0 中创建公共(public)类型,并带有许多构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54668249/

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