我有以下类:
class Foo
{
public Foo(string str, int i, bool b, DateTime d, string str2)
{
.....
}
}
我正在用AutoFixture创建一个Foo
:
var foo = fixture.Create<Foo>();
但我希望AutoFixture为str2
参数提供一个已知值,并对其他所有参数使用默认行为。
我尝试实现一个SpecimenBuilder
,但我找不到一种方法来获取与请求相关联的元数据,从而知道我是从Foo构造函数调用的。
有什么方法可以做到这一点吗?
发布于 2015-02-05 02:00:33
正如here所回答的,您可以获得如下内容
public class FooArg : ISpecimenBuilder
{
private readonly string value;
public FooArg(string value)
{
this.value = value;
}
public object Create(object request, ISpecimenContext context)
{
var pi = request as ParameterInfo;
if (pi == null)
return new NoSpecimen(request);
if (pi.Member.DeclaringType != typeof(Foo) ||
pi.ParameterType != typeof(string) ||
pi.Name != "str2")
return new NoSpecimen(request);
return value;
}
}
然后你可以像这样注册它
var fixture = new Fixture();
fixture.Customizations.Add(new FooArg(knownValue));
var sut = fixture.Create<Foo>();
发布于 2021-05-27 17:54:16
这回答了类似的问题,但使用自定义类型,例如MyType
。当给定时:
class Foo
{
public Foo(string str, MyType myType)
{
.....
}
}
class MyType
{
private readonly string myType;
public MyType(string myType)
{
this.myType = myType
}
}
你可以打电话给
fixture.Customize<MyType>(c => c.FromFactory(() => new MyType("myValue")));
var foo = fixture.Build<Foo>();
https://stackoverflow.com/questions/26149618
复制相似问题