Jer*_*acs 3 c# unit-testing moq mocking
我有一个类,我是单元测试,以验证特定的异常条件是否正常处理.为此,我模拟了内部调用的方法以抛出异常.
我的模拟设置看起来像这样:
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()));
Run Code Online (Sandbox Code Playgroud)
这正是我想要它做的.
但是,现在,我想通过仅为特定值抛出异常来测试连续性.我认为它应该是这样的:
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()));
Run Code Online (Sandbox Code Playgroud)
......但这似乎不起作用.我究竟做错了什么?
每个请求,整个测试:
[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);
}
Run Code Online (Sandbox Code Playgroud)
有人在评论中建议我应该尝试
It.Is<string>(a => Equals(a, "foo2.txt"))
Run Code Online (Sandbox Code Playgroud)
他引用了一些关于泛型的奇怪之处.我不知道它是否与泛型有任何关系,但这种改变确实有效.由于海报删除了他的评论,我正在代替他.