Simulate a delay in execution in Unit Test using Moq
When you setup your mock you can tell the thread to sleep in the return func:
Mock<IMyService> myService = new Mock<IMyService>();
myService.Setup(x => x.GetResultDelayed()).Returns(() => {
Thread.Sleep(100);
return "result";
});
If running asynchronous code, Moq has the ability to delay the response with the second parameter via a TimeSpan
mockFooService
.Setup(m => m.GetFooAsync())
.ReturnsAsync(new Foo(), TimeSpan.FromMilliseconds(500)); // Delay return for 500 milliseconds.
If you need to specify a different delay each time the method is called, you can use .SetupSequence
like
mockFooService
.SetupSequence(m => m.GetFooAsync())
.Returns(new Foo())
.Returns(Task.Run(async () =>
{
await Task.Delay(500) // Delay return for 500 milliseconds.
return new Foo();
})
If you want a Moq mock to just sit and do nothing for a while you can use a callback:
Mock<IFoo> mockFoo = new Mock<IFoo>();
mockFoo.Setup(f => f.Bar())
.Callback(() => Thread.Sleep(1000))
.Returns("test");
string result = mockFoo.Object.Bar(); // will take 1 second to return
Assert.AreEqual("test", result);
I've tried that in LinqPad and if you adjust the Thread.Sleep()
the execution time varies accordingly.