Car ownership with derived types
A few days before I used AutoFixture, I could have made the following convention to unit test a service named 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 long layout seems like an issue that AutoFixture solves well. I would imagine that I could rewrite this layout using AutoFixture would look something like this too:
public void TestName([Frozen] DerivedHttpResponse response, CustomerService sut)
{
//Nothing to arrange
// ...
}
My question is, is there a way to set up AutoFixture to do this, given the fact that I have many derived types HttpResponse
that I want to swap from test method to test method?
You can use an attribute [Frozen]
with a 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
indicates the type to which the value of the frozen parameter should be mapped.
If the type HttpResponse
is abstract you will have to create a derived type AutoDataAttribute
eg.AutoWebDataAttribute
public class AutoWebDataAttribute : AutoDataAttribute
{
public AutoWebDataAttribute()
: base(new Fixture().Customize(new WebModelCustomization()))
{
}
}
public class WebModelCustomization : CompositeCustomization
{
public WebModelCustomization()
: base(
new AutoMoqCustomization())
{
}
}
In this case, you should use instead [AutoWebData]
.