Search code examples
c#unit-testingmockingmoqnmock2

Convert UT in NMock2 to Moq. Also, what does .Will() in NMock2 stand for?


I am new to NMock2 and Moq frameworks. I need some help converting NMock2 code in my current project to Moq code:

var myMock= myMockery.NewMock<IMyInterface>();
var myRoleMock = myMockery.NewMock<IRoleInterface>();
var acceptAction = new MyAcceptAction(myRoleMock);
Stub.On(myMock).Method("Accept").Will(acceptAction);

I am also not clear what Will() in the above code stands for. I do have an idea that Will(Return.Value(something)) in NMock2 is equivalent to Returns(something) in Moq.

So are Will(something) and Will(Return.Value(something)) the same?


Solution

  • To know the difference we have to investigate a little. Let's take a look under the hood, Will method's signature stands as:

    public void Will(params IAction[] actions)
    

    Now, the IAction interface derives from one particulary important interface which is IInvokable. As name implies, this allows implementors to be invoked (via Invoke method). How does it relate to Return.Value?

    public class Return
    {
        public static IAction Value(object result)
        { 
            return new ReturnAction(result);
        }
    }
    

    Digging a little bit deeper we can find that ReturnAction in its Invoke method simply sets return value to be used/expected by mock. That's however not the point. Return.Value is a simple wrapper creating IAction required by Will.

    Your MyAcceptAction also has to implement this interface; to know what exactly happens in the

    Stub.On(myMock).Method("Accept").Will(acceptAction);
    

    line, you will have to check how MyAcceptAction is implemented. In particular, the Invoke method.