18

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148

2 Answers2

20

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
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Shouldn't `string Method` be `T Method`? – Doctor Blue Dec 10 '10 at 11:46
  • 1
    @Secret Agent Man, no, it shouldn't. At least there's nothing that obliges it to do so. It was just an example I took. A method can return whatever you want. If you want you can replace the `string` return type with `T`, the example will still work. – Darin Dimitrov Dec 10 '10 at 11:47
5

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...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194