0

I have the following method:

  private async Task<Result> TryGetResult (string request)
        {
            var httpClient = new HttpClient(); 
            var result = await httpClient.GetAsync(request);
            if (result.IsSuccess)
            {
                var body = await result.Content.ReadAsStringAsync();
                var deserializedResult = JsonConvert.DeserializeObject<Result>(body);
                return deserializedResult ;
            }

            if ( result.StatusCode == (HttpStatusCode)429 )
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
                return await TryGetResult(request);
            }
        }

This takes in this string request: var request = $"https://atlas.microsoft.com/search/address/json ... //(private keys omitted)

I want to unit test the method and stub out the request so that I don't make a real call. I have limited experience unit testing C# and am struggling to work out how to stub this? Please can anyone point me in the right direction?

I have tried looking at similar articles and googling but cannot find the stubbing of a string request like this and wonder if I'm going in the wrong direction with trying to test?

1 Answer 1

1

You should allow for injection of a HttpClient from the constructor of the class containing TryGetResult

public class YourClass // might want to implement IDisposable?
{
    private readonly HttpClient _client;

    public YourClass()
       : this(new HttpClient());
    {
    }

    public YourClass(HttpClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }
}

From there, I would suggest mocking the HttpClient with RichardSzalay.MockHttp. That way you can control the full response.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.