9

I have a class

public interface IMyInterface 
{
    string MethodA();
    void MethodB();
}

public class MyClass : IMyInterface
{
    public string MethodA()
    {
        // Do something important
    }

    public void MethodB()
    {
        string value = MethodA();
        // Do something important
    }
}

I want to unit test MethodB, but I'm having trouble thinking about how I can Mock MethodA while still calling into MethodB using Moq. Moq mocks the interface, not the class, so I can't just call mock.Object.MethodB(), right?

Is this possible? If so, how?

1
  • 1
    One remark: actually using Moq u can mock the class but there are some requirements on the classes. The class can’t be sealed. and the method being mocked must be marked as virtual. Also it cannot be static method.
    – Artiom
    Jul 28, 2012 at 11:45

2 Answers 2

4

I don't think it is possible. Even it is possible I'd prefer not to do that.

You are testing behavior of MyClass, the fact that it happen to implement IMyInterface is somewhat unrelated to testing behavior of MethodA and MethodB. You can have separate test that makes sure that class implements interfaces that you expect it to implement if necessary. Testing of MyClass.MethodB should be done on instance of MyClass, not on semi-mocked object.

If you think that behavior of MethodA is dependency you may try actually extract it explicitly from the class. It will allow to test both MethodA (which will simply delegate to the dependency) and MethodB (which will use the dependency and do more).

1

Mock dependencies you cannot instanciate easily (or all).
MyClass is class under test, so should not be mocked (you don't want to test mocked values).
But, if you have some MyClass.Foo property that is class Foo which implements IFoo interface and MethodA uses this Foo property, then you can mock it to break dependency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.