I have a method running in an infinite loop in a task from the ctor. The message does the equivalent to sending a ping
, and upon a certain number of failed pings, prevents other commands from being able to be sent. The method is started from the ctor with Task.Factory.StartNew(()=>InitPingBackgroundTask(pingCts.token));
public async Task InitPingBackgroundTask (CancellationToken token)
{
while(!token.IsCancellationRequested)
{
try
{
Ping();
// handle logic
_pingsFailed = 0;
_canSend = true;
}
catch(TimeoutException)
{
// handle logic
if(++_pingsFailed >= settings.MaxPingLossNoConnection)
_canSend = false;
}
finally
{
await Task.Delay(settings.PingInterval);
}
}
}
I have a second method DoCmd
like so:
public void DoCmd()
{
if(_canSend)
{
// handle logic
}
}
In my test, using Moq, I can set the settings to have PingInterval=TimeSpan.FromSeconds(1)
and MaxPingLossNoConnection = 2
for the sake of my test.
After setting up the sut
and everything else, I want to call DoCmd()
and verify that it is not actually sent. (I have mocked its dependencies and can verify that the logic in its method was never called)
One way to achieve this is to add a sleep or delay from within the test, before calling sut.DoCmd()
, but this makes the test take longer. Is there a way to simulate time passing (like tick(desiredTime)
in angular, or something similar)? To simulate the passing of time without having to actually wait the time?
Any leads would be appreciated :-)
EDIT Added the test code:
public void NotAllowSendIfTooManyPingsFailed()
{
var settings = new Settings()
{
PingInterval=TimeSpan.FromSeconds(1),
MaxPingLossNoConnection = 0 // ended up changing to 0 to fail immidiately
}
// set up code, that Ping messages should fail
Thread.Sleep(100); // necessary to Ping has a chance to fail before method is called
sut.DoCmd();
// assert logic, verifying that DoCmd did not go through
}
Ideally, I would like to be able to play with MaxPingLossNoConnection
and set it to different numbers to test circumstances. That would also require adding sleeps to let the time pass. In this test, I would want to remove the Sleep
altogether, as well as in other similar tests where sleep would be longer