How to verify that method was NOT called in Moq?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 13:52:01

问题


How do I verify that method was NOT called in Moq?

Does it have something like AssertWasNotCalled?

UPDATE: Starting from Version 3.0, a new syntax can be used:

mock.Verify(foo => foo.Execute("ping"), Times.Never());

回答1:


UPDATE: Since version 3, check the update to the question above or Dann's answer below.

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 )

var m = new Mock<IMoq>(MockBehavior.Loose);
m.Expect(a => a.moo()).Throws(new Exception("Shouldn't be called."));



回答2:


Run a verify after the test which has a Times.Never enum set. e.g.

_mock.Object.DoSomething()
_mock.Verify(service => service.ShouldntBeCalled(),Times.Never());



回答3:


Stolen from: John Foster's answer to the question, "Need help to understand Moq better"

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



回答4:


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.

Actually, it's better to specify .AtMost(0) after the Returns statement.

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.




回答5:


Use .AtMostOnce();

After the real test, call the method again. If it throws an exception, it was called.



来源:https://stackoverflow.com/questions/537308/how-to-verify-that-method-was-not-called-in-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!