【问题标题】:All invocation on the mock must have a corresponding setupmock 上的所有调用都必须有相应的设置
【发布时间】:2012-08-12 22:52:45
【问题描述】:

我有一些想要进行单元测试的遗留代码。我创建了第一个最小起订量测试,但出现以下异常:

Moq.MockException:IConnection.SendRequest(ADF.Messaging.Contract.ConfigServer.GetDataVersionRequest) 调用失败,模拟行为严格。上的所有调用 mock 必须有相应的设置。

重要的代码片段:

类属性:

Public Property Connection() As IConnection
    Get
        Return _connection
    End Get
    Set(ByVal value As IConnection)
        _connection = value
    End Set
End Property

应该测试的方法:(_connection) 实际上是一个创建 tcp 套接字的类,我想模拟该属性,以便 SendRequest 返回我想要的。

Public Function GetVersion(ByVal appID As Contract.ApplicationID) As Contract.DataVersion
    EnsureConnected()
    Dim req As GetDataVersionRequest = New GetDataVersionRequest(appID)

    Dim reply As CentralServiceReply = _connection.SendRequest(req) //code I want to mock
    Utils.Check.Ensure(TypeOf reply Is GetDataVersionReply, String.Format("Unexpected type: {0}, expected GetDataVersionReply!", reply.GetType()))

    Dim version As Contract.DataVersion = CType(reply, GetDataVersionReply).Version
    version.UpgradeOwners()
    If (Not version.IsSupported) Then
        Return Contract.DataVersion.UNSUPPORTED
    End If

    Return version
End Function

测试方法:

[TestMethod]
public void TestMethod2()
{
    Contract.CentralServiceRequest req = new Contract.ConfigServer.GetDataVersionRequest(new ApplicationID("AMS", "QA"));

    DataVersion v = new DataVersion();
    v.AppVersion = "16";
    CentralServiceReply reply = new GetDataVersionReply(v);

    var ConnectionMock = new Mock<IConnection>(MockBehavior.Strict);
    ConnectionMock.Setup(f => f.SendRequest(req)).Returns(reply);

    var proxy = new ConfigServerProxy(new ApplicationID("AMS", "QA"), "ws23545", 8001);
    proxy.Connection = ConnectionMock.Object; //assign mock object

    DataVersion v2 = proxy.GetVersion(new ApplicationID("AMS", "QA"));
    Assert.AreEqual(v.AppVersion, v2.AppVersion);
}

当我调试单元测试时,我看到当 proxy.GetVersion 在 _connection.SendRequest 行上执行时,我们得到了错误。此外,当我在监视窗口中查看变量 (_connection) 时,我看到它是 moq 对象。所以我想财产分配进展顺利。

有人知道我哪里出错了吗?

【问题讨论】:

    标签: .net unit-testing mocking moq mstest


    【解决方案1】:

    我想问题出在以下几点:

    Contract.CentralServiceRequest req = new Contract.ConfigServer.GetDataVersionRequest(new ApplicationID("AMS", "QA"));
    

    Proxy 调用获取应用程序版本,但不使用相同的请求对象(它可能会创建另一个具有相同参数的对象)。由于它是不同的对象,并且模拟设置为期望相同,因此它失败了。

    合理的解决方案是期望任何类型为 CentralServiceRequest 的请求。我不太熟悉起订量,但我想大概是这样的:

    ConnectionMock.Setup(f => f.SendRequest(ItExpr.IsAny<Contract.CentralServiceRequest>())).Returns(reply);
    

    希望这会有所帮助。

    【讨论】:

    • Returns 应该返回你想要返回的东西(Returns(response))。还有更复杂的方法来处理接收到的变量(比如请求应该有一些属性设置)。查看一些文档/教程,看看可以做什么。
    • Dmitriy,我在这里遇到了同样的问题。感谢您的帮助!
    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    相关资源
    最近更新 更多