Using Moq to determine if a method is called

Owen picture Owen · Dec 7, 2008 · Viewed 87.6k times · Source

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 that SomeOtherMethod() will be called.

Am I right in thinking this sort of test is available in a mocking framework?

Answer

Paul picture Paul · Dec 7, 2008

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.