Saturday, February 22, 2014

Unit Testing Async Methods with Moq

The other day I was pairing with a colleague.  We where working on unit testing some classes that where using the new async and await features.  We ran into some issue trying to get mocking working for our classes dependencies. Here is some example code on how we got things to work.

So given the following code:

public interface IClass2
{
    Task<string> GetSomeString_MethodAsync();
}

public class Class2 : IClass2
{
    public async Task<string> GetSomeString_MethodAsync()
    {
        await Task.Run(() => Thread.Sleep(2000));
        return "hello world.";
    }
}

public class Class1
{
    private IClass2 class2;

    public Class1(IClass2 class2)
    {
        this.class2 = class2;
    }

    public async Task<string> SomeMethod()
    {
        return await this.class2.GetSomeString_MethodAsync();
    }
}

And we can test it like this:

private Mock<IClass2> class2Mock;
private Class1 class1;

[TestInitialize]
public void Setup()
{
    this.class2Mock = new Mock<IClass2>();
    this.class1 = new Class1(this.class2Mock.Object);
}
            
[TestMethod]
public async Task SomeMethodTest()
{
    var expectedString = "Hello World";
    var tcs = new TaskCompletionSource<string>();
    tcs.SetResult(expectedString);
    this.class2Mock.Setup(x => x.GetSomeString_MethodAsync()).Returns(tcs.Task);

    var result = await this.class1.SomeMethod();

    Assert.AreEqual(result, expectedString);
}

Note the usage of the TaskCompletionSource in the unit test along with the declaration of the test using “async Task”.

6 comments:

  1. "TaskCompletionSource", exactly what I needed for my mocking! Thank you Dave.

    ReplyDelete
  2. Thanks so much for this blog post. I was languishing for hours trying to figure out how to mock up an await method.

    ReplyDelete
  3. 6 years old but what the heck.. You can simplify by using Task.FromResult(expectedString)instead of the TaskCompletionSource.

    ReplyDelete
  4. Ucuz, kaliteli ve organik sosyal medya hizmetleri satın almak için Ravje Medyayı tercih edebilir ve sosyal medya hesaplarını hızla büyütebilirsin. Ravje Medya ile sosyal medya hesaplarını organik ve gerçek kişiler ile geliştirebilir, kişisel ya da ticari hesapların için Ravje Medyayı tercih edebilirsin. Ravje Medya internet sitesine giriş yapmak için hemen tıkla: ravje.com

    İnstagram takipçi satın almak için Ravje Medya hizmetlerini tercih edebilir, güvenilir ve gerçek takipçilere Ravje Medya ile ulaşabilirsin. İnstagram takipçi satın almak artık Ravje Medya ile oldukça güvenilir. Hemen instagram takipçi satın almak için Ravje Medyanın ilgili sayfasını ziyaret et: instagram takipçi satın al

    Tiktok takipçi satın al istiyorsan tercihini Ravje Medya yap! Ravje Medya uzman kadrosu ve profesyonel ekibi ile sizlere Tiktok takipçi satın alma hizmetide sunmaktadır. Tiktok takipçi satın almak için hemen tıkla: tiktok takipçi satın al

    İnstagram beğeni satın almak için Ravje medya instagram beğeni satın al sayfasına giriş yap, hızlı ve kaliteli instagram beğeni satın al: instagram beğeni satın al

    Youtube izlenme satın al sayfası ile hemen youtube izlenme satın al! Ravje medya kalitesi ile hemen youtube izlenme satın almak için tıklayın: youtube izlenme satın al

    Twitter takipçi satın almak istiyorsan Ravje medya twitter takipçi satın al sayfasına tıkla, Ravje medya güvencesi ile organik twitter takipçi satın al: twitter takipçi satın al

    ReplyDelete