【问题标题】:How to mock generic method without specifying type parameter如何在不指定类型参数的情况下模拟泛型方法
【发布时间】:2022-02-03 06:23:20
【问题描述】:

我有一个界面

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<???>>());

【问题讨论】:

  • 我认为这是不可能的。另外,在进行单元测试时,我们使用一组确定的标准进行测试并验证确定的结果,那么预期的通用测试是否有意义?我们在测试什么?
  • @Jimmy 我不想测试GetInstance,但我在我想测试的方法上得到了NullReferenceException。查看我的答案,这不是我要求的,而是我的问题的解决方案。

标签: c# unit-testing mocking moq


【解决方案1】:

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

就我而言,我想测试来自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 };

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    相关资源
    最近更新 更多