user21318030
user21318030

Reputation:

Mocking is not working to inner function where HTTPwrapper class method gets called

I am mocking one of the inner function before giving actual call to outer function. I am mocking a httpwrpapper class method. Problem is my mocked method doesn't return the response. Below is the code entire code.

Httpwrapper class and method

public class HTTPClientWrapper: IHTTPClientWrapper
{    
  public async Task<T>PostAsync<T>(string url, object somepostobject)
  {
    T result = null;    
    using(var client = new HttpClient()) {
      var response = await client.PostAsync(apiUrl, postObject, new   JsonMediaTypeFormatter()).ConfigureAwait(false);

      response.EnsureSuccessStatusCode();

      await response.Content.ReadAsStringAsync().ContinueWith((Task <string> x) =>{
        if (x.IsFaulted) throw x.Exception;

        result = JsonConvert.DeserializeObject<T>(x.Result);

      });
    }

    return result;
  }
}

Consuming method

public class Executor {
 public Executor(IHTTPClientWrapper httpClientWrapper)
 {
  _httpClientWrpper=httpClientWrapper;
 }

 public void SomeMethod()
 {
  string test="test";
  GetConfig();
  var response = _httpClientWrpper.PostAsync<PersonResponse>(url,postObject);
 }
}

want to write a unit test case for this method.

public void SomeMethod() { string test="test"; GetConfig(); var response = _httpClientWrpper.PostAsync(url,postObject); }

I tried below, but at the time of actual invoking of method it is not produce/trigger the responce which I mocked

Mock<IHTTPClientWrapper> mockhttpClient =new Mock<IHTTPClientWrapper>();
    
mockhttpClient.setup(t=>t.PostAsync<PersonResponse>(It.IsAny<string>(),It.IsAny<string>()).Returns(Task.FromResult<PersonResponse>(mockresponse));

mockexecutor.object.SomeMethod(someparametrs);

Upvotes: 1

Views: 197

Answers (1)

Peter Csala
Peter Csala

Reputation: 22819

TL;DR: You should not mock your to be tested code.


mockexecutor.object.SomeMethod(someparametrs);

This line suggests me that you try to call the SomeMethod on a mocked object.

Whenever we are talking about mocking then we should mock only the dependencies of the system under test (or in short sut).

So, in your case you should mock the IHTTPClientWrapper, but not the Executor

//Arrange
var mockHttpClient =new Mock<IHTTPClientWrapper>();
mockHttpClient
   .Setup(client => ...)
   .ReturnsAsync(...);


var sut = new Executor(mockHttpClient.Object);

//Act
sut.SomeMethod();

//Assert
...

Upvotes: 0

Related Questions