Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing method which create a new thread and result we get from event ( NUnit 2.6 )

I have class which have one public method Start, one private method and one event Finishing. Start call new Thread( private_method ). Private method return value using event. When this method finish their work, then call this event.

Now I want to write test to this class. If I write it like this:

    [Test]
    public void Test1()
    {
        SomeClass someObject = new SomeClass();

        someObject.Finishing += new SomeClass.FinishingEventHandler((sender, a) =>
        {
            Assert.True(false);
        });
        someObject.Start(); // when this method will finish, then call event Finishing
    }

It should be fail, but it isn't. I think that method Test1 is finished before event is raised. So, how can I test this code? How test method, which create a new thread, and result we get from event

like image 280
nirmus Avatar asked Mar 22 '12 22:03

nirmus


2 Answers

NUnit has built-in feature for waiting for assertion. It is called 'After':

[Test]
public void ShouldRaiseFinishedEvent()
{
    SomeClass someObject = new SomeClass();
    bool eventRaised = false;
    someObject.SomethingFinished += (o, e) => { eventRaised = true; };

    someObject.DoSomething();
    Assert.That(eventRaised, Is.True.After(500));
}
like image 66
Sergey Berezovskiy Avatar answered Nov 15 '22 00:11

Sergey Berezovskiy


[Test]
public void ShouldRaiseFinishedEvent()
{
    SomeClass someObject = new SomeClass();
    AutoResetEvent eventRaised = new AutoResetEvent(false);
    someObject.SomethingFinished += (o, e) => { eventRaised.Set(); };

    someObject.DoSomething();
    Assert.IsTrue(eventRaised.WaitOne(TimeSpan.FromMilliseconds(500)));
}

This should work

like image 26
Jeba Ranganathan Avatar answered Nov 15 '22 01:11

Jeba Ranganathan