C# 如何验证该方法未在 Moq 中调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/537308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to verify that method was NOT called in Moq?
提问by alex
采纳答案by Dan Fish
UPDATE: Since version 3, check the update to the question above or Dann's answer below.
更新:从第 3 版开始,请检查上面问题的更新或下面 Dann 的回答。
Either, make your mock strict so it will fail if you call a method for which you don't have an expect
要么,让你的模拟严格,这样如果你调用一个你没有期望的方法,它就会失败
new Mock<IMoq>(MockBehavior.Strict)
Or, if you want your mock to be loose, use the .Throws( Exception )
或者,如果您希望模拟松散,请使用 .Throws( Exception )
var m = new Mock<IMoq>(MockBehavior.Loose);
m.Expect(a => a.moo()).Throws(new Exception("Shouldn't be called."));
回答by Aaron Digulla
Use .AtMostOnce();
使用 .AtMostOnce();
After the real test, call the method again. If it throws an exception, it was called.
真正测试后,再次调用该方法。如果它抛出异常,则调用它。
回答by miha
This does not work in recent versions of Moq(since at least 3.1), it should be specified in the
Verify
method as mentioned in the answer.
这在最近版本的 Moq(至少从 3.1 开始)中不起作用,应该
Verify
在答案中提到的方法中指定它。
Actually, it's better to specify .AtMost(0)
after the Returns statement.
实际上,最好.AtMost(0)
在 Returns 语句之后指定。
var m = new Mock<ISomething>();
m.Expect(x => x.Forbidden()).Returns("foo").AtMost(0);
Although the "throws" also works, AtMost(0)
is more expressive IMHO.
虽然“抛出”也有效,AtMost(0)
恕我直言更具表现力。
回答by Chris Marisic
Stolen from: John Foster's answer to the question, "Need help to understand Moq better"
窃取自:约翰·福斯特 (John Foster) 对问题的回答,“需要帮助更好地理解最小起订量”
One of the things that you might want to test is that the pay method does not get called when a person aged over 65 is passed into the method
[Test] public void Someone_over_65_does_not_pay_a_pension_contribution() { var mockPensionService = new Mock<IPensionService>(); var person = new Person("test", 66); var calc = new PensionCalculator(mockPensionService.Object); calc.PayPensionContribution(person); mockPensionService.Verify(ps => ps.Pay(It.IsAny<decimal>()), Times.Never()); }
您可能想要测试的一件事是,当将 65 岁以上的人传入该方法时,不会调用 pay 方法
[Test] public void Someone_over_65_does_not_pay_a_pension_contribution() { var mockPensionService = new Mock<IPensionService>(); var person = new Person("test", 66); var calc = new PensionCalculator(mockPensionService.Object); calc.PayPensionContribution(person); mockPensionService.Verify(ps => ps.Pay(It.IsAny<decimal>()), Times.Never()); }
回答by Dan
Run a verify after the test which has a Times.Never
enum set. e.g.
在具有Times.Never
枚举集的测试之后运行验证。例如
_mock.Object.DoSomething()
_mock.Verify(service => service.ShouldntBeCalled(),Times.Never());