简体   繁体   English

使用Moq模拟带有条件参数的方法

[英]Mocking a method with conditional arguments using Moq

I have a class that I am unit testing, to verify a specific exception condition is handled gracefully. 我有一个类,我是单元测试,以验证特定的异常条件是否正常处理。 To this end, I mock the method that is called internally to throw the exception. 为此,我模拟了内部调用的方法以抛出异常。

my mocking setup looks like this: 我的模拟设置看起来像这样:

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()));

this does exactly what I want it to do. 这正是我想要它做的。

Now, however, I want to test continuity by only throwing an exception for a specific value. 但是,现在,我想通过仅为特定值抛出异常来测试连续性。 I thought it should look like this: 我认为它应该是这样的:

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()));

...but this doesn't seem to work. ......但这似乎不起作用。 What am I doing wrong? 我究竟做错了什么?

Per request, the entire test: 每个请求,整个测试:

[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);
}

There was someone who suggested in comments that I should try 有人在评论中建议我应该尝试

It.Is<string>(a => Equals(a, "foo2.txt"))

He cited some oddness with generics. 他引用了一些关于泛型的奇怪之处。 I don't know if it had anything to do with generics, but this change did in fact work. 我不知道它是否与泛型有任何关系,但这种改变确实有效。 Since the poster deleted his comment, I am making the answer in his stead. 由于海报删除了他的评论,我正在代替他。

I think that 我觉得

m.PutFile(It.IsAny<IFileConnection>(), "foo2.txt")

should work 应该管用

How do the internals of fr ever know to call GetFile with foo2.txt as the file name? fr的内部如何通过foo2.txt作为文件名来调用GetFile It seems like you're setting up your test specification broadly ( ^foo\\\\d.txt$ ) but your mock narrowly ( foo2.txt ), shouldn't it be the other way around? 看起来你正在广泛地设置你的测试规范( ^foo\\\\d.txt$ ),但你的模拟狭窄( foo2.txt ),不应该是相反的方式吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM