views:

91

answers:

2

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();
+1  A: 

You can use the Times class:

logger.Verify(x => x.LogTrace(expectedMessage), Times.Once());
adrift
No, I am trying to mock a protected member. I cannot use the lambda syntax afaik, and I do not see an overload of Verify that will work with protected members.
Gabe Moothart
Sorry, my mistake. I noticed in the Moq.Protected namespace, there is an IProtectedMock interface that has a Verify method taking Times as a parameter. Maybe this is what you are looking for...
adrift
Yes! It was not there in the 4.0.x build I was using, but it is in 4.0.10827. My downvote is to old to undo, but if you create a new answer for this I will upvote/accept.
Gabe Moothart
Great, I'm glad that was it :)
adrift
+2  A: 

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