I am unit testing a component that does work on any number of threads and raises events on those threads. I have written a simple event register that I use to assert that the events I expect have been raised:
public class EventRegister
{
private readonly object _lock = new object();
public int Count { get; private set; }
public void Increment()
{
lock (_lock)
{
Count++;
Monitor.Pulse(_lock);
}
}
public static EventRegister operator ++(EventRegister counter)
{
counter.Count++;
return counter;
}
public static implicit operator int(EventRegister counter)
{
return counter.Count;
}
public bool HasFired { get { return Count > 0; } }
public void Wait(int unitCount)
{
Wait(unitCount, TimeSpan.MinValue);
}
public void Wait(int unitCount, TimeSpan timeout)
{
lock (_lock)
{
var start = DateTime.Now;
while (Count < unitCount)
{
if (timeout != TimeSpan.MinValue && !Debugger.IsAttached)
{
Monitor.Wait(_lock, timeout);
if (DateTime.Now-start>timeout)
throw new TimeoutException();
}
else
Monitor.Wait(_lock);
}
}
}
}
this works fine and I happy enough with it, but have I reinvented the wheel? Does NUnit or MOQ (or any other lib) already include some other mechanism for doing the same thing?
To answer your 2 questions:
You have reinvented the wheel. Not quite the same wheel model I have (re) invented myself, but quite similar nonetheless. I am pretty sure a lot of other persons reinvented such a wheel somewhere else as well.
Moq does not provide such functionality, neither does MSTest. Last time I did use NUnit, it did not provide it.
A lot of multi-thread, event-based boiler plate code seems to be written over and over again. Maybe it is time for a framework-agnostic thread and event helper library to be built…