7

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

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

重要的代码片段:

类属性:

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 对象。所以我想财产分配进展顺利。

有人看到我哪里出错了吗?

4

1 回答 1

9

我想问题出在以下几点:

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

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

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

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

希望这可以帮助。

于 2012-08-16T14:56:59.890 回答