简体   繁体   中英

Nunit test async code with .NET 3.5

I'm using .NET 3.5 and want an Nunit test to test async code in a delegate/lambda expression, but can't get it to work. Can anyone please give some advice on how to do this, if it's possible? Here's an example (SomeMethod returns straight away, and calls OnDone at a later time):

[Test]
public void MyTest()
{
    MyClass.SomeMethod(123, OnDone);
}

private void OnDone(object sender, MyEventArgs e)
{
    Assert.AreEqual(123, e.Value);
}

If SomeMethod returns before calling the delegate, then you'll have to use some kind of synchronization primitive to wait for the delegate to be called.

An AutoResetEvent will do.

// Arrange
var are = new AutoResetEvent(false);
int args = 0;

EventHandler<object, MyEventArgs> handler = (s, e) =>
{
    args = e.Value;
    are.Set(); 
};

// Act
MyClass.SomeMethod(123, handler);


// Assert
var wasCalled = are.WaitOne(timeout: TimeSpan.FromSeconds(1));
Assert.True(wasCalled);
Assert.AreEqual(123, args);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM