3

在我使用 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
  // ...
}

我的问题是,有没有办法配置 AutoFixture 来为我执行此操作,因为我有许多派生HttpResponse类型要从测试方法换成测试方法?

4

1 回答 1

5

您可以将[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]改用。

于 2013-01-19T05:15:20.277 回答