【问题标题】:AutoFixture with derived types具有派生类型的 AutoFixture
【发布时间】:2013-01-19 04:07:14
【问题描述】:

在我使用 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 来为我做这件事?

【问题讨论】:

    标签: autofixture


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      相关资源
      最近更新 更多