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
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));
}
[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With