检查用Moq调用CancellationTokenSource.Cancel() [英] 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();
}
其中PermanentCancellation类型为CancellationTokenSource。
where PermanentCancellation is of type CancellationTokenSource.
我想知道如何在_view的模拟中设置它。到目前为止,所有尝试均失败了:(我无法在google上找到示例。
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.
推荐答案
因为 CancellationTokenSource.Cancel
Because CancellationTokenSource.Cancel is not virtual you cannot mock it with moq.
您有两个选择:
创建包装器接口:
public interface ICancellationTokenSource
{
void Cancel();
}
以及将委派给包装的CancellationTokenSource的实现
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();
}
}
并使用 ICancellationTokenSource
作为 PermanentCancellation
,然后您可以在测试中创建 Mock< ICancellationTokenSource>
:
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());
并在生产代码中使用 CancellationTokenSourceWrapper
。
And use the CancellationTokenSourceWrapper
in your production code.
或使用支持模拟非虚拟成员的模拟框架,例如:
Or use a mocking framework which supports mocking non virtual members like:
- Microsoft假货
- < a href = http://www.typemock.com/isolator-product-page rel = nofollow> Typemock隔离器(商业)
- JustMock (商业)
- Microsoft Fakes
- Typemock isolator (commercial)
- JustMock (commercial)
这篇关于检查用Moq调用CancellationTokenSource.Cancel()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!