1

i am writing test cases i need to mock get sync method please provide help . we are using c#

i am using test case

HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
var mockClient = new Mock<HttpClient>();
mockClient.Setup(client => client.GetAsync(requestUri)).ReturnsAsync(response1);

but i am getting invalid setup exception

Rahul
  • 76,197
  • 13
  • 71
  • 125
suresh
  • 11
  • 1
  • 3
  • var response1 = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("[{'id':1,'value':'1'}]") }; HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); my complete code: var mockClient = new Mock(); mockClient.Setup(client => client.GetAsync(requestUri)).ReturnsAsync(response1); – suresh Feb 05 '19 at 11:51
  • Welcome to Stack Overflow! Please be a bit more specific when asking a question: *What have you tried so far with a code example? ([I downvoted because there is no code](http://idownvotedbecau.se/nocode/))* / *What do you expect?* / *What error do you get?* **For Help take a look at "[How to ask](https://stackoverflow.com/help/how-to-ask)" and afterward [edit] your question.** – Hille Feb 05 '19 at 11:52

2 Answers2

4

I'd use a library such as RichardSzalay.MockHttp (https://github.com/richardszalay/mockhttp) to create a HttpClient object. For example:

// Create the mock
var mockHttp = new MockHttpMessageHandler();

// Setup the responses and or expectations
// This will return the specified response when the httpClient.GetAsync("http://localhost/api/user/5") is called on the injected object.
var request = mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

// Test code

// perform assertions
Assert.AreEqual(1, mockHttp.GetMatchCount(request));
CorneW
  • 41
  • 3
0

With new Mock<HttpClient>() I believe you are using MOQ for mocking and if so you can't mock GetAsync() likewise since MOQ is Dynamic Proxy based mocking system which allows mocking only abstract or virtual methods.

Your best alternative would be to create a Adapter/wrapper for HttpClient and mock that in this case. Something like

public interface IHttpClient
{
  HttpResponseMessage GetDataAsync(string uri);
}

Then you can mock it saying

var mockclient = new Mock<IHttpClient>();
mcokclient.Setup(x => x.GetDataAsync(It.IsAny<string>())).Returns(message);
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • 1
    i am using xunit and moq methods ...is there anyway to mock this method...(httpclient.getasync(uri)) – suresh Feb 05 '19 at 11:57
  • i am using interface like this... public interface IHttpClientHelper { Task GetAsync(string requestUri); Task GetAsync(string requestUri, string token); } – suresh Feb 06 '19 at 06:24