How to write a test case for Getasync() with mockdata return type is Task
Loading
How to write a test case for Getasync() with mockdata return type is Task
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Apr 27, 2023, 2:15 AM EDT
Assuming you're using NUnit for testing. Here's an example of how to write a test case for a method that uses
GetAsync()to retrieve data from a service with aTaskreturn type:using NUnit.Framework; using Moq; //Assuming you have a class that retrieves data from a service: public class DataService { public async Task GetDataAsync(string url) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); return await response.Content.ReadAsStringAsync(); } } }Now, let's write a test case that uses mock data to simulate the response from the service:
[TestFixture] public class DataServiceTests { private Mock _mockHttpMessageHandler; private HttpClient _httpClient; private DataService _dataService; [SetUp] public void SetUp() { _mockHttpMessageHandler = new Mock(); _httpClient = new HttpClient(_mockHttpMessageHandler.Object); _dataService = new DataService(); } [Test] public async Task GetDataAsync_ReturnsData() { //Arrange string mockData = "Mock data response"; string url = "http://example.com"; HttpResponseMessage httpResponse = new HttpResponseMessage(); httpResponse.Content = new StringContent(mockData); httpResponse.StatusCode = HttpStatusCode.OK; _mockHttpMessageHandler.Protected() .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) .ReturnsAsync(httpResponse); //Act string data = await _dataService.GetDataAsync(url); //Assert Assert.AreEqual(mockData, data); } }Here we're using
Moqto create a mockHttpMessageHandler, which we'll use to simulate the response from the service. We then set up the mock to return the expected response when theHttpClientmakes a call toSendAsync(). Finally, we call theGetDataAsync()method and verify that it returns the expected data.