Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test asynchronous methods using nunit

How to test asynchronous methods using nunit?

like image 652
TrustyCoder Avatar asked Mar 12 '10 09:03

TrustyCoder


2 Answers

If you have .NET’s version 5 of the C# compiler then you can use new async and await keywords. attach the link : http://simoneb.github.io/blog/2013/01/19/async-support-in-nunit/

If you can using closure with anonymous lambda function, using thread synchronization.

eg)

[TestFixture]
class SomeTests
{
    [Test]
    public void AsyncTest()
    {
        var autoEvent = new AutoResetEvent(false); // initialize to false

        var Some = new Some();
        Some.AsyncFunction(e =>
        {
            Assert.True(e.Result);
            autoEvent.Set(); // event set
        });
        autoEvent.WaitOne(); // wait until event set
    }

}
like image 65
Namo Avatar answered Oct 02 '22 03:10

Namo


You could use NUnits Delayed Constraint

[TestFixture]
class SomeTests
{
    [Test]
    public void AsyncTest()
    {
        var result = false;
        var Some = new Some();
        Some.AsyncFunction(e =>
        {
            result = e.Result;
        });

        Assert.That(() => result, Is.True.After(1).Minutes.PollEvery(500).MilliSeconds);
    }

}

This example is for NUnit 3.6 but earlier versions also support Delayed Constraint, but lookup it up as the syntax is different.

like image 34
Daryn Avatar answered Oct 02 '22 01:10

Daryn