在我使用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);
// ...
}
Run Code Online (Sandbox Code Playgroud)
这种冗长的安排似乎是AutoFixture善于解决的问题.我想我可以用AutoFixture重写那个排列,看起来像这样:
public void TestName([Frozen] DerivedHttpResponse response, CustomerService sut)
{
//Nothing to arrange
// ...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,有没有办法配置AutoFixture来为我做这个,因为我有很多派生HttpResponse类型,我想从测试方法换成测试方法?
您可以将该[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.
}
Run Code Online (Sandbox Code Playgroud)
named参数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())
{
}
}
Run Code Online (Sandbox Code Playgroud)
在那种情况下,你会使用[AutoWebData]相反.
| 归档时间: |
|
| 查看次数: |
357 次 |
| 最近记录: |