Recently I was asked how to mock a generic method, now that NMock2 supports generics. Here's how:

Suppose you have this interface:

public interface IMyInterface
{
    T DoStuff<T>();

And this class using IMyInterface:

public class MyClass
{
    private IMyInterface mi_;
 
    public MyClass(IMyInterface mi)
    {
        this.mi_ = mi;
    }
 
    public string DoSomething()
    {
        return this.mi_.DoStuff<string>();
    }
}

Now, you want to write a unit test where you validate that if DoStuff<string> returns Ploeh, MyClass.DoSomething will also return Ploeh. On the version of NMock2 currently installed on my laptop, this is easily done like this:

[TestMethod]
public void ValidateDoSomething()
{
    Mockery mocks = new Mockery();
    IMyInterface mi = mocks.NewMock<IMyInterface>();
    Expect.Once.On(mi).Method("DoStuff").Will(Return.Value("Ploeh"));
 
    MyClass mc = new MyClass(mi);
    string result = mc.DoSomething();
 
    Assert.AreEqual<string>("Ploeh", result);
    mocks.VerifyAllExpectationsHaveBeenMet();
}

The only thing which is slightly surprising here is that the method name expected is DoStuff, without any indications of generics - I first expected that I should have indicated the method name as DoStuff`1, but apparently, NMock2 doesn't care whether you are expecting a generic or non-generic version of a method (if DoStuff had had a non-generic overload).

Note that this is based on a release candidate of NMock2, so there's no guarantee that this will work exactly identical in the final release.