与AutoFixture 4.8.0一样,是否有更好的替代方法来使用Fixture.Register
注册一个函数以创建仅公开internal
构造函数的类型?
我正在使用.net标准类库来构建供内部使用的API。我们不想公开公共构造函数,因此这些模型的所有构造函数都是internal
。属性另外为public readonly
。这些类将通过Json反序列化实例化,在这个特定的库中,有一个模型要考虑的属性> 20。另外,我们希望尽可能使用[AutoDataAttribute]。
即。除了使用AutoFixture为内部jsonconstructor提供具有20多个参数的非复杂类型和复杂类型(也是内部类型)的混合之外,还有其他选择吗?
[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;
}
}
答案 0 :(得分:2)
默认情况下,AutoFixture仅考虑公共构造函数。即使可以从测试执行程序集访问内部构造函数,它也不会使用(甚至不确定是否有合理的技术可能性进行检查)。
您可以轻松地自定义灯具以支持它。从以下代码示例中获取灵感:
[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;
}
}