Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking generic methods

Assume I have some interface with a generic method and no parameters:

public interface Interface {
   void Method<T>();
}

Now I wish to implement the mock for this class (I'm using Moq) and I wish to mock this method for some concrete type - let's say I'm mocking Method<String>() calls.

mock = new Mock<Interface>();
mock.Setup(x => x.Method ????).Returns(String("abc"));

The idea of ???? should be clear - this lambda expression should handle the case when T in the Method<T> is actually a String.

Is there any way I can achieve the wanted behavior?

like image 659
Yippie-Ki-Yay Avatar asked Dec 10 '10 11:12

Yippie-Ki-Yay


2 Answers

Simply:

mock.Setup(x => x.Method<string>()).Returns("abc");

Also make sure that your method actually returns something as currently the return type is defined as void:

public interface Interface
{
    string Method<T>();
}

class Program
{
    static void Main()
    {
        var mock = new Mock<Interface>();
        mock.Setup(x => x.Method<string>()).Returns("abc");

        Console.WriteLine(mock.Object.Method<string>()); // prints abc
        Console.WriteLine(mock.Object.Method<int>()); // prints nothing
    }
}
like image 114
Darin Dimitrov Avatar answered Nov 09 '22 20:11

Darin Dimitrov


I haven't used Moq myself, but I'd expect:

mock.Setup(x => x.Method<string>());

(Note that your sample method has a void return type, so it shouldn't be returning anything...

like image 45
Jon Skeet Avatar answered Nov 09 '22 20:11

Jon Skeet