Moq可以Mock HubConnection,但RhinoMocks不能吗?

时间:2014-07-16 15:19:41

标签: c# unit-testing signalr moq rhino-mocks

我正在查看SignalR的unit tests,并注意到其中一个测试使用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 : 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的缺点吗?

1 个答案:

答案 0 :(得分:4)

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

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