gpt4 book ai didi

c# - Moq 可以模拟 HubConnection 但 RhinoMocks 不能?

转载 作者:行者123 更新时间:2023-11-30 15:28:54 24 4
gpt4 key购买 nike

我正在查看 unit tests对于 SignalR 并注意到其中一项测试使用 Moq 创建模拟 HubConnection:

[Fact]
public void HubCallbackClearedOnFailedInvocation()
{
var connection = new Mock<HubConnection>("http://foo");
var tcs = new TaskCompletionSource<object>();

tcs.TrySetCanceled();

connection.Setup(c => c.Send(It.IsAny<string>())).Returns(tcs.Task);

var hubProxy = new HubProxy(connection.Object, "foo");

var aggEx = Assert.Throws<AggregateException>(() => { hubProxy.Invoke("foo", "arg1").Wait(); });
var ex = aggEx.Unwrap();

Assert.IsType(typeof(TaskCanceledException), ex);

Assert.Equal(connection.Object._callbacks.Count, 0);
}

但是,当我尝试使用略有不同的模拟框架 RhinoMocks 执行相同操作时,它会提示该方法不是虚拟的:

[Test]
public void ShouldCreateBrokerWithHubConnection()
{
//Arrange
var url = "http://localhost6790";
var hubProxy = MockRepository.GenerateMock<IHubProxy>();
var hubConnection = MockRepository.GenerateMock<HubConnection>(url);
hubConnection.(c => c.CreateHubProxy("ArtemisClientHub")).Return(hubProxy);

... (more code)
}

System.InvalidOperationException:调用无效,已使用最后一次调用或未进行任何调用(确保调用的是虚拟 (C#)/可覆盖 (VB) 方法)。

与像 Moq 这样的新库相比,这只是 RhinoMocks 的一个缺点吗?

最佳答案

我的建议是使用代码中的非具体类型并使用 Ioc 注入(inject)具体类型。然而,信号器点网络客户端缺少与服务器不同的 DependencyResolver。我自己解决了这个问题,您可以在此处查看代码(但在您的情况下,您可以使用任何 Ioc,如 Ninject、autofac 等)

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/master/SignalR.EventAggregatorProxy.Client.DotNet/Bootstrap/DependencyResolver.cs

集线器连接和代理有点难以抽象,因为您依赖于具体类型来创建代理。我通过将集线器代理的创建抽象为工厂接口(interface)来解决它,该工厂接口(interface)返回可以轻松模拟的 IHubProxy。

看这里 https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/master/SignalR.EventAggregatorProxy.Client.DotNet/Bootstrap/Factories/HubProxyFactory.cs

所有示例都取 self 的这个库的 dot net 客户端 https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy

关于c# - Moq 可以模拟 HubConnection 但 RhinoMocks 不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24784531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com