1

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);
}
3
  • 2
    What does SomeMethod do? It seems like it's returning before executing the delegate. Commented Sep 11, 2015 at 8:35
  • 1
    without knowing what is in MyClass and SomeMethod I don't see how this is answerable. Commented Sep 11, 2015 at 8:38
  • Sorry yes, SomeMethod returns straight away, and calls OnDone at a later time. Commented Sep 11, 2015 at 8:39

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

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.