[英]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>>());
但我需要一个通用的方法
如果返回类型只是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 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.