[英]Is it possible to mock IHubcontext<T> using Moq Framework?
I have a controller which has a IHubContext<T>
object injected into the constructor.我有一个 controller 有一个
IHubContext<T>
object 注入到构造函数中。 I would like to unit test adding and removing connectionId
s to and from groups.我想对在组中添加和删除
connectionId
进行单元测试。 I am asking how I can do this?我在问我怎么能做到这一点? I tried this:
我试过这个:
public interface IMyHubContext :IHubContext<MyHub>
{
Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default);
Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default);
}
var cs = new CancellationTokenSource();
var ct = cs.Token;
Mock<IMyHubContext> hubMoq = new Mock<IMyHubContext>();
hubMoq.Setup(a => a.RemoveFromGroupAsync("123", $"{groupName}", ct)).Returns(null);
But this generates a compile time error.但这会产生编译时错误。
The compile time error is generated probably due to passing null
to Returns
.编译时错误的产生可能是由于将
null
传递给Returns
。 Since, RemoveFromGroupAsync
return type is Task
, I think you need to set up this call as below:由于
RemoveFromGroupAsync
返回类型为Task
,我认为您需要按如下方式设置此调用:
hubMoq.Setup(a => a.RemoveFromGroupAsync("123", $"{groupName}", ct))
.Returns(Task.CompletedTask);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.