Moq 可以 Mock HubConnection 但 RhinoMocks 不能?

Kil*_*ine 4 c# unit-testing rhino-mocks moq signalr

我正在查看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);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用稍微不同的模拟框架 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)
 }
Run Code Online (Sandbox Code Playgroud)

System.InvalidOperationException : Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).

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

And*_*ers 5

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

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

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

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

所有示例均取自我的 dot net 客户端,用于此库 https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy