如何在不指定类型参数的情况下模拟泛型方法

How to mock generic method without specifying type parameter

我有接口

public interface ISomething
{
    ISomethingElse<T> GetInstance<T>();
}

现在我想嘲笑这个

这个有效:

var mock = new Mock<ISomething>();
mock.Setup(x => x.GetInstance<MyClass>()).Returns(Mock.Of<ISomethingElse<MyClass>>());

但我需要一个通用的方法

如果 return 类型刚好是 ISomethingElse 我可以写

var mock = new Mock<ISomething>();
mock.Setup(x => x.GetInstance<It.IsAnyTpye>()).Returns(Mock.Of<ISomethingElse>());

但是(显然)这是行不通的。

我怎样才能以更通用的方式实现这一点?

var mock = new Mock<ISomething>();
mock.Setup(x => x.GetInstance<It.IsAnyTpye>()).Returns(Mock.Of<ISomethingElse<???>>());

我想出了一个很好的解决方法。

在我的例子中,我想测试 MyClass 中使用 ISomething 的方法。 ISomething 本身在别处测试。

public void MyMethod(ISomething something)
{
    something.GetInstance(this).Setup();
    // I want to test the following code
}

我只是不想 something.GetInstance(this).Setup(); 抛出 NullReferenceException。

我用 DefaultValue = DefaultValue.Mock 解决了它,这正是我想要实现的。

new Mock<ISomething>() { DefaultValue = DefaultValue.Mock };