I have a unit test in which I mock (with moq) an object and let it verify if it executed a method properly. This method is being executed in a Thread that I create in my SUT (System under Test). When I want to do VerifyAll() on the Mock it could happen that the Thread is still running and that it isn't finished yet executing the method - failing the test.
Is there a way to resolve this in a correct matter? for example let the VerifyAll wait or something? Because now, the test is unreliable.
This is the Test:
[Test]
public void TryToExecute_SubjectNotYetBeingProcessed_ProcessesSubject()
{
var subject = new Subject();
var rule = new Mock<IBusinessRule>();
rule.Setup(x => x.RunChildren(subject)); //RunChildren will be called in a seperate Thread
InBuffer.TryToExecute(subject, rule.Object);
rule.VerifyAll(); //It could be possible that the Thread is still running and that RunChildren() isn't invoked yet, thus failing the test.
}
public void TryToExecute(Subject subject, IBusinessRule rule){
var thread = new Thread(x =>
{
SetCurrentAsProcessing(subject);
rule.RunChildren(subject) // This is where it executes
RemoveFromProcess(subject);
});
thread.Start(); // Start the Thread
}