Using the HttpClientInterception to Test Methods That Use a HttpClient

Full source code available here.

In my previous post I showed a way of testing a controller that uses a HttpClient.

I had to mock the HttpMessageHandler pass that to the HttpClient and set a bunch of properties. It works well, but is a bit long winded.

I received a comment from a reader who suggested that I try the JustEat.HttpClientInterception library. It allows you to setup responses to specified requests, and pass these to a HttpClient. Then the HttpClient is passed to the controller.

Here is how the test method looks –

public async Task GetTest()
    List<int> myList = new List<int>() {1, 2, 3, 4, 5};
    // setup the interceptor
    HttpRequestInterceptionBuilder builder = new HttpRequestInterceptionBuilder()
    // create the HttpClient from the builder
    // and setup the HttpClientBaseAddress
    HttpClient client = new HttpClientInterceptorOptions()

    ValuesController controller = new ValuesController(client);

    IActionResult result = await controller.Get();

    OkObjectResult resultObject = result as OkObjectResult;

    List<int> numbers = resultObject.Value as List<int>;
    Assert.Equal(5, numbers.Count);

Briefly, here is the constructor of the values controller. It takes the HttpClient as a parameter, usually passed by dependency injection.

public class ValuesController : Controller
    readonly IAsyncPolicy<HttpResponseMessage> _httpRetryPolicy;
    private readonly HttpClient _httpClient;

    public ValuesController(HttpClient httpClient)
        _httpClient = httpClient;

Full source code available here.

Customizing a specific string inside a class using AutoFixture

Full source code.

I’ve been using AutoFixture for a while with my unit tests. It creates objects with prefilled data, saving me the hassle of manually constructing them.

Basic usage

If you want a string from AutoFixture do something like –

string myString = fixture.Create();


If you want to prefix the string do this –

string myPrefixedString = fixture.Create("Prefix");


If you want something that looks like an email address –

string emailAddress = fixture.Create().Address;


Where it starts to get a bit tricky is if you have a class like this –

public class Account
	public Guid AccountId { get; set; }
	public string Firstname { get; set; }
	public string Lastname { get; set; }
	public IEnumerable<string> EmailAddresses { get; set; }

Because I am using a string to represent an email address AutoFixture will give me a string, not an email address.

Here are two solutions.

Solution 1

fixture.Customize<Account>(c => c.With(a => a.EmailAddresses, fixture.CreateMany<MailAddress>().Select(ma => ma.Address.ToString())));

This produces emails that look like –


Solution 2

If I want to generate email address that look a little more like real world address I have to create a SpecimenBuilder.

    public class EmailAddressesStringSpecimenBuilder : ISpecimenBuilder
        public object Create(object request, ISpecimenContext context)
            var propertyInfo = request as PropertyInfo;

            if (propertyInfo != null)
                if (propertyInfo.Name == "EmailAddresses" && propertyInfo.PropertyType == typeof (IEnumerable<string>))
					// of course you can customize how the mail addresses are created, you can even use a fixture to create strings 🙂 
                    IEnumerable<string> emailAddresses = new List<string>() {"", "", ""};
                    return emailAddresses;
            return new NoSpecimen();

How to use the customizations

            Fixture fixture = new Fixture();

			fixture.Customizations.Add(new EmailAddressesStringSpecimenBuilder());
            // use one of the two customizations here, but not both
			// fixture.Customize<Account>(c => c.With(a => a.EmailAddresses, fixture.CreateMany<MailAddress>().Select(ma => ma.Address.ToString())));

            var account1 = fixture.Create<Account>();
            var account2 = fixture.Create<Account>();

Full source code.