0

I have this class:

   public class HttpService : IHttpService
    {
        private HttpClient _httpClient;
        public HttpService()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("https://localhost:5001");
        }
        public async Task<HttpResponseMessage> PostDataAsync(string endPoint, object data)
        {
            return await _httpClient.PostAsync($"/api/chat/{endPoint}",
             new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
        }
        public async Task<UserModel> PostLoginCredentialsAsync(UserCredentials userCredentials)
        {
            var response = await PostDataAsync("Login", userCredentials).ConfigureAwait(false);
            var jsonResponseData = await response.Content.ReadAsStringAsync();
            var userResponseModel = JsonConvert.DeserializeObject<UserResponseModel>(jsonResponseData);
            if (response.StatusCode != HttpStatusCode.OK) throw new LoginException(userResponseModel.Message);
            return userResponseModel.Payload;
        }
}

I am trying to test the method PostLoginCredentialsAsync and mock the method PostDataAsync.

Now, I am not really sure what's the best way to mock it. I don't want to make PostDataAsync virtual and mock it. I could try to make another interface wrapping HttpClient, but I am not sure how that would look without changing the IHttpService interface.

Sound
  • 113
  • 5
  • Inject your httpclient. There’s packages to provide a stub – Daniel A. White Apr 28 '22 at 23:00
  • Note that while duplicate answers the question *as asked* what you really should be looking into is using Refit (or similar tools/libraries) to remove need for writing proxy code yourself and making code to depend on clean service interface rather than HttpClient. Will also eliminate need to test manually written proxy code. – Alexei Levenkov Apr 28 '22 at 23:19
  • @DanielA.White How would that work? httpclient is a concrete class. Even if I inject it, how would that help? – Sound Apr 28 '22 at 23:21
  • @AlexeiLevenkov Is there such a library that wraps HttpClient inside of an interface? Because then, that would make mocking way easier – Sound Apr 28 '22 at 23:21
  • https://www.nuget.org/packages/Moq.Contrib.HttpClient/ – Daniel A. White Apr 28 '22 at 23:26
  • @Sound I'm familiar with one I've mentioned... so I can't recommend any other. – Alexei Levenkov Apr 29 '22 at 00:11
  • @DanielA.White That package helped me a lot with mocking this method, thank you so much! – Sound Apr 29 '22 at 17:20

0 Answers0