Question

In the days before I used AutoFixture, I might have done the following arrangement to set up a unit test of a service called 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);
  // ...
}

This lengthy arrangement seems like a problem that AutoFixture is good at solving. I'd imagine that I'd be able to rewrite that arrangement using AutoFixture too look something like this:

public void TestName([Frozen] DerivedHttpResponse response, CustomerService sut)
{
  //Nothing to arrange
  // ...
}

My question is, is there a way to configure AutoFixture to do this for me, given the fact that I have many derived HttpResponse types that I want to swap out from test method to test method?

Was it helpful?

Solution

You can use the [Frozen] attribute with the named parameter 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. 
}

The named parameter As specifies the type that the frozen parameter value should be mapped to.


If the HttpResponse type is abstract you will have to create an AutoDataAttribute derived type e.g. AutoWebDataAttribute

public class AutoWebDataAttribute : AutoDataAttribute
{
    public AutoWebDataAttribute()
        : base(new Fixture().Customize(new WebModelCustomization()))
    {
    }
}

public class WebModelCustomization : CompositeCustomization
{
    public WebModelCustomization()
        : base(
            new AutoMoqCustomization())
    {
    }
}

In that case you would use the [AutoWebData] instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top