hits counter

TypeMock: How to Make Reflective Mocks More Natural

Like I said before, this as been on the back of my mind for a while.

A while back I introduced a way to get the MethodInfo of a method in a strongly typed way using LINQ, and that's how I'm going to make Reflective Mocks more Natural.

Well, it's as easy as this:

public static class MockExtender
    public static IParameters ExpectAndReturn<T1, T2, TResult>(this IMockControl mock, Expression<Func<T1, T2, TResult>> expression, object ret, params Type[] genericTypes)
        return mock.ExpectAndReturn((expression.Body as MethodCallExpression).Method.Name, ret, genericTypes);

(For now, I'll leave to someone else the implementation of the rest of the overloads)

With this implementation it's possible to handle static classes (a limitation of Fredrik's implementation).

As for private methods, just let Visual Studio (2008, in this sample) and TypeMock do their magic.

So, to test this class:

public static class Class1
    public static string PublicMethod(string param1, int param2)
        return PrivateMethod(param2, param1);

    private static string PrivateMethod(int param2, string param1)
        throw new NotImplementedException();

We just write this test:

public void PublicMethodTest()
    string param1 = "param";
    int param2 = 5;
    string expected = "return";
    string actual;

    Mock targetMock = MockManager.Mock(typeof(Class1));

    targetMock.ExpectAndReturn((int i, string s) => ClassLibrary1.Class1_Accessor.PrivateMethod(i, s), expected).Args(param2, param1);

    actual = Class1.PublicMethod(param1, param2);

    Assert.AreEqual(expected, actual);

How about this for clean and simple?

1 Comment

  • Thanks for this post. &nbsp;It clears up some questions my coworkers and I have had about TypeMock!
    We noticed that you don't use the &lt;TResult&gt; type in your ExpectAndReturn extension method in the example. &nbsp;Do you mean:
    public static IParameters ExpectAndReturn&lt;T1, T2, TResult&gt;(this IMockControl mock, Expression&lt;Func&lt;T1, T2, TResult&gt;&gt; expression, TResult ret, params Type[] genericTypes)
    where TResult ret replaces object ret?

Comments have been disabled for this content.