在我使用AutoFixture之前的日子里,我可能已经做了以下安排来设置一个名为CustomerService的服务的单元测试
public void TestName()
{
//Arrange
var fakeResponse = new DerivedHttpResponse();
var fakeHandler = new FakeHttpMessageHandler(fakeResponse); // takes HttpResponse
var httpClient = new HttpClient(fakeHandler);
var sut = new CustomerService(httpClient);
// ...
}这种冗长的安排似乎是AutoFixture擅长解决的问题。我想我也可以使用AutoFixture重写这种安排,看起来就像这样:
public void TestName([Frozen] DerivedHttpResponse response, CustomerService sut)
{
//Nothing to arrange
// ...
}我的问题是,考虑到我有许多派生的HttpResponse类型,我想在测试方法之间切换,有没有一种方法可以配置AutoFixture来为我做这件事?
发布于 2013-01-19 13:15:20
可以将[Frozen]属性与命名参数As一起使用
[Theory, AutoData]
public void TestName(
[Frozen(As = typeof(HttpResponse))] DerivedHttpResponse response,
CustomerService sut)
{
// 'response' is now the same type, and instance,
// with the type that the SUT depends on.
}命名参数As指定冻结参数值应映射到的类型。
如果HttpResponse类型是抽象的,则必须创建AutoDataAttribute派生类型,例如AutoWebDataAttribute
public class AutoWebDataAttribute : AutoDataAttribute
{
public AutoWebDataAttribute()
: base(new Fixture().Customize(new WebModelCustomization()))
{
}
}
public class WebModelCustomization : CompositeCustomization
{
public WebModelCustomization()
: base(
new AutoMoqCustomization())
{
}
}在这种情况下,您将使用[AutoWebData]。
https://stackoverflow.com/questions/14410991
复制相似问题