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?
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
}
}
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...
精彩评论