Example #1
0
        public async void TestCancel()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
                using (var workerManager = new WorkerManager())
                {
                    hc.EnqueueInstance <IJobDispatcher>(_jobDispatcher.Object);
                    workerManager.Initialize(hc);
                    JobRequestMessage jobMessage    = CreateJobRequestMessage();
                    JobCancelMessage  cancelMessage = CreateJobCancelMessage(jobMessage.JobId);
                    bool started = false;
                    Task jobTask = null;
                    _jobDispatcher.Setup(x => x.RunAsync(jobMessage, It.IsAny <CancellationToken>()))
                    .Returns(async(JobRequestMessage message, CancellationToken token) =>
                    {
                        jobTask = Task.Delay(5000, token);
                        started = true;
                        await jobTask;
                        return(0);
                    });
                    workerManager.Run(jobMessage);
                    int i = 20;
                    while (i > 0 && (!started))
                    {
                        await Task.Delay(10);

                        i--;
                    }
                    Assert.True(started);

                    //Act
                    //send cancel message
                    workerManager.Cancel(cancelMessage);

                    //Assert
                    //wait up to 2 sec for cancellation to be processed
                    Task[] taskToWait = { jobTask, Task.Delay(2000) };
                    await Task.WhenAny(taskToWait);

                    _jobDispatcher.Verify(x => x.RunAsync(jobMessage, It.IsAny <CancellationToken>()),
                                          $"{nameof(_jobDispatcher.Object.RunAsync)} not invoked");
                    Assert.True(jobTask.IsCompleted);
                    Assert.True(jobTask.IsCanceled);
                }
        }