7

How to test asynchronous methods using nunit?

Namo
  • 456
  • 5
  • 11
TrustyCoder
  • 4,749
  • 10
  • 66
  • 119
  • 3
    What problem are you having? You just test them; and check for the thing they are doing. I mean, no matter what you're going to need to wait. It's just a matter of seeing if you can get it to notify you, so you don't need to poll. May or may not be possible. – Noon Silk Mar 12 '10 at 09:26
  • 1
    Near duplicate of ["How do I test an async method with NUnit, eventually with another framework?"](http://stackoverflow.com/questions/12191831/how-do-i-test-an-async-method-with-nunit-eventually-with-another-framework) – chwarr May 17 '14 at 05:01
  • 5 upvotes for a 7 word question showing no research effort? _[How do I ask a good question?](http://stackoverflow.com/help/how-to-ask)_. I'm jealous ;) –  Sep 11 '15 at 09:12
  • Does this answer your question? [How do I test an async method with NUnit (or possibly with another framework)?](https://stackoverflow.com/questions/12191831/how-do-i-test-an-async-method-with-nunit-or-possibly-with-another-framework) – ggorlen Oct 05 '22 at 05:51

2 Answers2

3

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
    }

}
Namo
  • 456
  • 5
  • 11
2

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.

Daryn
  • 3,394
  • 5
  • 30
  • 41
  • StackOverflow should not allow down votes without an explanation. Please explain yourself when down voting, so that it helps us all learn. – Daryn Feb 02 '18 at 13:32