Checking that CancellationTokenSource.Cancel() was invoked with Moq

こ雲淡風輕ζ 提交于 2019-12-07 14:44:03

问题


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.


回答1:


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:

  • Microsoft Fakes
  • Typemock isolator (commercial)
  • JustMock (commercial)


来源:https://stackoverflow.com/questions/12264219/checking-that-cancellationtokensource-cancel-was-invoked-with-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!