【发布时间】:2012-04-30 19:20:11
【问题描述】:
我有一个类,我正在单元测试,以验证特定的异常条件是否得到妥善处理。为此,我mock了内部调用的方法抛出异常。
我的模拟设置如下所示:
fr.CallBase = true;
fr.Setup(m => m.PutFile(It.IsAny<IFileConnection>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new System.IO.IOException("Test Exception", new System.Net.Sockets.SocketException()));
这正是我想要的。
但是,现在我想通过仅针对特定值抛出异常来测试连续性。我认为它应该是这样的:
fr.Setup(m => m.PutFile(It.IsAny<IFileConnection>(), It.Is<string>(a => a == "foo2.txt"), It.IsAny<string>()))
.Throws(new System.IO.IOException("Test Exception", new System.Net.Sockets.SocketException()));
...但这似乎不起作用。我做错了什么?
每个请求,整个测试:
[Test]
public void ManualRouteInterruptedInDownloadContinuesOn()
{
var firstRoute = this.UnitOfWork.GetFirstRoute();
Route r = this.UnitOfWork.GetRouteByID(firstRoute.RouteID);
r.RegExMatch = "^foo\\d.txt$";
r.Manual = true;
r.NotifyOfNewFiles = "me@company.com";
this.UnitOfWork.Save();
var fr = new Mock<ManualRouting>(r.RouteID);
fr.CallBase = true;
fr.Setup(m => m.GetFile(It.IsAny<IFileConnection>(), It.Is<string>(a => a == "foo2.txt"), It.IsAny<string>()))
.Throws(new System.IO.IOException("Test Exception", new System.Net.Sockets.SocketException()));
fr.Object.ExecuteRoute(firstRoute.RouteID);
Assert.IsTrue(fr.Object.Errors.Count == 1);
Assert.IsTrue(fr.Object.Matches.Count == 3);
}
【问题讨论】:
-
看来应该可以了,能把整个测试用例的代码贴出来吗?
-
你能分享你试图模拟的函数调用吗?
-
@BishopRook,我添加了测试。
-
建议使用
Equals()的人的评论在哪里?那行得通。 -
@jimmy_keen:对我没用。我根据建议将
It.Is<string>(a => a == "foo2.txt")更改为It.Is<string>(a => Equals(a, "foo2.txt"))并且有效。
标签: c# unit-testing mocking moq