Console.WriteLine after an async call is waiting.

I am completely new to using asynchronous calls and waiting . I have a unit test function below:

public async static void POSTDataHttpContent(string jsonString, string webAddress) { HttpClient client = new HttpClient(); StringContent stringContent = new StringContent(jsonString); HttpResponseMessage response = await client.PostAsync( webAddress, stringContent); Console.WriteLine("response is: " + response); } 

Testing completes without errors, but I never see Console.WriteLine output in the output report - I'm not sure why. I looked around, and it seems to me that I may need to set this as a task? Can someone point me in the right direction?

+5
source share
2 answers

Since you are already expecting HttpResponseMessage , a simple (and consistent) solution is to return a Task<HttpResponseMessage> .

 var x = await POSTDataHttpContent("test", "http://api/"); public async Task<HttpResponseMessage> POSTDataHttpContent( string jsonString, string webAddress) { using (HttpClient client = new HttpClient()) { StringContent stringContent = new StringContent(jsonString); HttpResponseMessage response = await client.PostAsync( webAddress, stringContent); Console.WriteLine("response is: " + response); return response; } } 

However, you also need to make sure your test setup is correct. You cannot correctly call the asynchronization method from a synchronous test. Instead, mark your async test and expect the method you are calling. In addition, your test method should be marked as async Task , since neither MS Runner nor other tools (NCrunch, NUnit) will correctly process the asynchronous test method:

 [TestMethod] public async Task TestAsyncHttpCall() { var x = await POSTDataHttpContent("test", "http://api/"); Assert.IsTrue(x.IsSuccessStatusCode); } 
+3
source

I think the best thing here for you would be to select the return type of Task instead of void.

 public async Task POSTDataHttpContent(string jsonString, string webAddress) { using (HttpClient client = new HttpClient()) { StringContent stringContent = new StringContent(jsonString); HttpResponseMessage response = await client.PostAsync( webAddress, stringContent); // Assert your response may be? } } 

And if you're really adamant about not using Tasks (which is not very good):

 public void POSTDataHttpContent(string jsonString, string webAddress) { var Task = Task<HttpResponseMessage>.Run(async () => { using (HttpClient client = new HttpClient()) { StringContent stringContent = new StringContent(jsonString); HttpResponseMessage response = await client.PostAsync( webAddress, stringContent); return response; } }); Task.Wait(); Assert.IsNotNull(Task.Result); } 
+1
source

All Articles