5

I'm new to unit testing and async operations in visual studio/c#. Appreciate any help on this.

My Main class

class Foo 
{
    public async Task<string> GetWebAsync()
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync("https://hotmail.com");
            return await response.Content.ReadAsStringAsync();
        }
    }
}

Unit Test

[TestMethod]
public void TestGet()
{
    Foo foo = new Foo();

    foo.GetWebAsync().ContinueWith((k) =>
    {
        Console.Write(k);
        Assert.IsNotNull(null, "error");
    });
}
3
  • This piece of code looks odd to me var response = await client.GetAsync("https://hotmail.com"); return await response.Content.ReadAsStringAsync();.....why not two responses and wait all, when all? Commented Feb 3, 2017 at 15:25
  • @Hackerman I'm new and the code is not perfect, can you please help fix it with an answer? Commented Feb 3, 2017 at 15:26
  • You can create another similar question on codereview.stackexchange.com Commented Feb 3, 2017 at 16:03

1 Answer 1

15

Make the Test async as well

[TestMethod]
public async Task TestGet() {
    var foo = new Foo();
    var result = await foo.GetWebAsync();
    Assert.IsNotNull(result, "error");
    Console.Write(result);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks it works, quick question, sometimes my Console.Write("..") output appears in TestExplorer besides stack trace (if error) once I select a specific test and sometimes don't, any idea?
Do you think my implementation for GetWebAsync is correct?
@user2727195 for a start it is ok. there is always room for improvement but that leads into a whole other topic of OOP design which is out of scope for this question
When do we have to call ConfigureAwait(false)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.