Using Moq to test and mock method calls on a 'real' class

1,423 views
Skip to first unread message

Rob

unread,
Nov 16, 2010, 10:51:28 AM11/16/10
to Moq Discussions
I have a class that has an internal (virtual) method that I want to
test. This method calls another internal method on the same class.
What I want to do is make the call to the 1st method (passing in some
params) & mock the call to the 2nd internal method (which I later need
to verify). I don't want to let the 2nd method execute as it involves
a whole lot more setup.

Now I assume that you can mock the 2nd method using...
target.Protected().Setup("SecondMethod", new object[] {...});

but how do I invoke the first (internal) method and get it to call the
'real' code?

With VS, I can generate an 'Accessor' and use that to 'new' an object
that gives me access to non-public methods & props. If I use this in
'new Mock<Module_Accessor>()' I can now call my 1st method.

I also seem to now only require
'target.Setup(t=>t.SecondMethod()).Callback(()=>{return;});' but the
2nd method is being called rather than stubbed. I've set 'CallBase =
true' as without this the 1st method isn't being called.

R. Knaus

unread,
Dec 17, 2013, 9:19:00 AM12/17/13
to moq...@googlegroups.com
Just had a similar problem. In my case the solution was to change the access modifier of the method to mock (the 2nd method in your case) from internal to internal protected (see http://msdn.microsoft.com/en-us/library/ms173121.aspx). Apparently Moq just calls the original method if the access restriction prevents stubbing.
Reply all
Reply to author
Forward
0 new messages