I am trying to find the best unit test way of this class:
public class FileGroupGarbageCollector
{
private Task _task;
private readonly AutoResetEvent _event = new AutoResetEvent(false);
public void Start()
{
_task = Task.Factory.StartNew(StartCollecting);
}
public void Stop()
{
_event.Set();
}
private void StartCollecting()
{
do
{
Process();
}
while (!_event.WaitOne(60000, false));
}
private void Process()
{
}
}
It doesn't have to be the best-formed class, just trying to figure out something!
Then I have a unit test where I want to start and then stop the service, claiming that the private "Processs" method did something in the database or file system.
My unit test looks like this (nunit):
[Test]
public void TestStart()
{
var fg = new FileGroupGarbageCollector(30000);
fg.Start();
Thread.Sleep(5000);
fg.Stop();
}
Is there any way or any good template that can be used here, so I can avoid Thread.Sleep ()? I hate the idea of sleeping in unit test (not to mention production code), but I refuse to just check private functions! I want to test the open interface of this class.
Any answers are welcome :)
UPDATE AFTER ANSWER
IoC , :)
IEventFactory { IEvent Create(); }
public interface IEvent
{
bool WaitOne(int timeout);
void Set();
}
( Moq):
var mockEvent = new Mock<IEvent>();
var mockEventFactory = new Mock<IEventFactory>();
mockEvent.Setup(x => x.WaitOne(It.IsAny<int>())).Returns(true);
mockEvent.Setup(x => x.Set());
mockEventFactory.Setup(x => x.Create()).Returns(mockEvent.Object);
, IEvent.WaitOne() true , Thread.Sleep()!
:)