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?

2 thoughts on “TypeMock: How to Make Reflective Mocks More Natural”

  1. That’s pretty neat indeed :)

    Actually, it turns out that my implementation can handle static methods in the same manner as yours, I just didn’t think of that you could call it with something like (string s) => Logger.Log(s) to match the method signature for any call expression. I’m loving how powerful the expression trees and lambda features are! Will have to blog more about this topic later :)


  2. Hi Fredrik.

    I have to confess I didn’t read all the way into your code. Somehow, looked to me like you were overdoing it. :)

    I just thought of doing it this way to keep the API with the same look.

    Typemock really could benefit from this kind of APIs.

Comments are closed.