tags:

views:

607

answers:

2

I am modifiying a class method which formats some input paramater dates which are subsequently used as params in a method call into the base class (which lives in another assembly).

I want to verify that the dates i pass in to my method are in the correct format when they are passed to the base class method so i would like to Moq the base class method call. Is this possible with Moq?

+1  A: 

If I understand your question correctly, you have a class A defined in some other assembly, and then an class B implemented more or less like this:

public class B : A
{
    public override MyMethod(object input)
    {
        // Do something
        base.MyMethod(input);
    }
}

And now you want to verify that base.MyMethod is called?

I don't see how you can do this with a dynamic mock library. All dynamic mock libraries (with the exeption of TypeMock) work by dynamically emitting classes that derive from the type in question.

In your case, you can't very well ask Moq to derive from A, since you want to test B.

This means that you must ask Moq to give you a Mock<B>. However, this means that the emitted type derives from B, and while it can override MyMethod (which is still virtual) and call its base (B.MyMethod), it has no way of getting to the original class and verify that B calls base.MyMethod.

Imagine that you have to write a class (C) that derives from B. While you can override MyMethod, there's no way you can verify that B calls A:

public class C : B
{
    public override MyMethod(object input)
    {
        // How to verify that base calls its base?
        // base in this context means B, not A
    }
}

Again with the possible exception of TypeMock, dynamic mock libraries cannot do anothing that you cannot do manually.

However, I would assume that calling the base method you are trying to verify has some observable side effect, so if possible, can you use state-based testing instead of behavior-based testing to verify the outcome of calling the method?

In any case, state-based testing ought to be your default approach in most cases.

Mark Seemann
A: 

Agree with Mark, it's not possible using Moq.

Depending on your situation you may consider swithcing from inheritance to composition. Then you'll be able to mock the dependency and verify your method. Of course in some cases it just might not worth it.

Yacoder