我有一些想要进行单元测试的遗留代码。我创建了第一个起订量测试,但出现以下异常:
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 对象。所以我想财产分配进展顺利。
有人看到我哪里出错了吗?