Search code examples
c#c#-4.0moqtask-parallel-librarycancellationtokensource

Checking that CancellationTokenSource.Cancel() was invoked with Moq


I have a conditional statement which should looks as follows:

//...
if(_view.VerifyData != true)
{
    //...
}
else
{
    _view.PermanentCancellation.Cancel();
}

where PermanentCancellation is of type CancellationTokenSource.

Im wondering how i should set this up in my mock of _view. All attempts thus far have failed :( and i cant find an example on google.

Any pointers would be appreciated.


Solution

  • Because CancellationTokenSource.Cancel is not virtual you cannot mock it with moq.

    You have two options:

    Create a wrapper interface:

    public interface ICancellationTokenSource
    {
        void Cancel();
    }
    

    and an implementation which delegates to the wrapped CancellationTokenSource

    public class CancellationTokenSourceWrapper : ICancellationTokenSource
    {
        private readonly CancellationTokenSource source;
    
        public CancellationTokenSourceWrapper(CancellationTokenSource source)
        {
            this.source = source;
        }
    
        public void Cancel() 
        {
            source.Cancel();
        }
    
    }
    

    And use the ICancellationTokenSource as PermanentCancellation then you can create an Mock<ICancellationTokenSource> in your tests:

    // arrange
    
    var mockCancellationTokenSource = new Mock<ICancellationTokenSource>();
    viewMock.SetupGet(m => m.PermanentCancellation)
            .Returns(mockCancellationTokenSource.Object)
    
    // act
    
    // do something
    
    // assert
    
    mockCancellationTokenSource.Verify(m => m.Cancel());
    

    And use the CancellationTokenSourceWrapper in your production code.

    Or use a mocking framework which supports mocking non virtual members like: