UnitTesting class threaded avoiding Thread.Sleep () in test?

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()
    {
        /* do some work to the database and file system */
    }
}

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); // i hate this!

        fg.Stop();

        // assert it did what i wanted it to do!
    }

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()!

:)

+5
2

, . , .

. , .

public interface ITaskFactory {}
public interface IThreadManager {}
public interface ICollectorDatabase {}
public interface IEventFactory {} 

public class FileGroupGarbageCollector 
{
  ITaskFactory taskFactory;
  IThreadManager threadManager;
  ICollectorDatabase database;
  IEventFactory events;

  FileGroupGarbageCollector (ITaskFactory taskFactory,
    IThreadManager threadManager, ICollectorDatabase database,
    IEventFactory events)
  {
     // init members..
  }
}

, FileGroupGarbageCollector . , IEventFactory mock , , WaitOne. , .

, , - Mocking, Inversion of Control, Pattern Injection Dependency.

+7

Thread.Sleep . .

- "". Rx ; . ( Rx).

Thread.Sleep , , ( , , Microsoft Moles); , "". , Thread.Sleep .

+1

All Articles