Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify the number of times a protected method is called using Moq

Tags:

In my unit-tests I'm mocking a protected method using Moq, and would like to assert that it is called a certain number of times. This question describes something similar for an earlier version of Moq:

//expect that ChildMethod1() will be called once. (it's protected)
testBaseMock.Protected().Expect("ChildMethod1")
  .AtMostOnce()
  .Verifiable();

...
testBase.Verify();

but this no longer works; the syntax has changed since then and I cannot find the new equivalent using Moq 4.x:

testBaseMock.Protected().Setup("ChildMethod1")
  // no AtMostOnce() or related method anymore
  .Verifiable();

...
testBase.Verify();
like image 677
Gabe Moothart Avatar asked Sep 16 '10 16:09

Gabe Moothart


2 Answers

In the Moq.Protected namespace, there is an IProtectedMock interface that has a Verify method taking Times as a parameter.

Edit This is available since at least Moq 4.0.10827. Syntax example:

testBaseMock.Protected().Setup("ChildMethod1");

...
testBaseMock.Protected().Verify("ChildMethod1", Times.Once());
like image 150
Jeff Ogata Avatar answered Sep 16 '22 13:09

Jeff Ogata


To augment Ogata's answer, we can also verify a protected method that takes arguments:

testBaseMock.Protected().Setup(
    "ChildMethod1",
    ItExpr.IsAny<string>(),
    ItExpr.IsAny<string>());

testBaseMock.Protected().Verify(
    "ChildMethod1", 
    Times.Once(),
    ItExpr.IsAny<string>()
    ItExpr.IsAny<string>());

For instance, that would verify ChildMethod1(string x, string y).

See also: http://www.nudoq.org/#!/Packages/Moq.Testeroids/Moq/IProtectedMock(TMock)/M/Verify

like image 36
Shaun Luttin Avatar answered Sep 16 '22 13:09

Shaun Luttin