我有一些我希望进行单元测试的遗留代码。我创建了第一个moq测试但是我得到了以下异常:
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
应该测试的方法:(_ connect)实际上是一个创建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);
}
当我调试单元测试时,我看到当在行_connection.SendRequest上执行proxy.GetVersion时,我们得到了错误。此外,当我在观察窗口中观察变量(_connection)时,我看到它是moq对象。所以我认为财产分配进展顺利。
有人看到我哪里出错吗?
答案 0 :(得分:8)
我认为问题出在以下方面:
Contract.CentralServiceRequest req = new Contract.ConfigServer.GetDataVersionRequest(new ApplicationID("AMS", "QA"));
代理进行调用以获取应用程序版本,但不使用相同的请求对象(它可能会创建另一个具有相同参数的请求对象)。因为它是不同的对象而mock被设置为期望相同,所以它失败了。
合理的解决方案是期望任何类型的CentralServiceRequest请求。我对Moq并不熟悉,但我认为它是这样的:
ConnectionMock.Setup(f => f.SendRequest(ItExpr.IsAny<Contract.CentralServiceRequest>())).Returns(reply);
希望这有帮助。