Using Moq to determine if a method is called
Solution 1
You can see if a method in something you have mocked has been called by using Verify, e.g.:
static void Main(string[] args)
{
Mock<ITest> mock = new Mock<ITest>();
ClassBeingTested testedClass = new ClassBeingTested();
testedClass.WorkMethod(mock.Object);
mock.Verify(m => m.MethodToCheckIfCalled());
}
class ClassBeingTested
{
public void WorkMethod(ITest test)
{
//test.MethodToCheckIfCalled();
}
}
public interface ITest
{
void MethodToCheckIfCalled();
}
If the line is left commented it will throw a MockException when you call Verify. If it is uncommented it will pass.
Solution 2
No, mock testing assumes you are using certain testable design patterns, one of which is injection. In your case you would be testing SomeClass.SomeMethod
and SomeOtherMethod
must be implemented in another entity which needs to be interfaced.
Your Someclass
constructor would look like New(ISomeOtherClass)
. Then you would mock the ISomeOtherClass
and set expectation on its SomeOtherMethod
to be called and verify the expectation.
Related videos on Youtube
Owen
Leeds based c#/asp.net developer. See: My current open source project - Less Css for .NET My Blog - EngineChris Feel free to contact me at: E: [email protected] Skype: christopher.john.owen T: 07886711645
Updated on April 23, 2020Comments
-
Owen about 4 years
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:
public abstract class SomeClass() { public void SomeMehod() { SomeOtherMethod(); } internal abstract void SomeOtherMethod(); }
I want to test that if I call
SomeMethod()
then I expect thatSomeOtherMethod()
will be called.Am I right in thinking this sort of test is available in a mocking framework?
-
Admin over 15 yearsThis is the correct answer. You must understand something, however. You CANNNOT mock a method/property that is not abstract or virtual (obviously, all interface methods and properties can be mocked).
-
Raymond over 14 years-1: The .Expect(...).Verifiable() is redundant in this code. Using AAA the verify you have is just right. .Verifiable is for usage with .Verify() i,.e. the no arg version. See stackoverflow.com/questions/980554/…
-
reggaeguitar about 5 years@I-- yes it can
-
reggaeguitar about 5 yearsDownvoted because it's more complicated and requires a boilerplate DummyClass
-
wickdninja over 4 yearsupvoted because sometimes you cannot refactor and you need to test the implementation as it stands