在 Moq 中模拟泛型方法而不指定 T

时间:2023-05-06
本文介绍了在 Moq 中模拟泛型方法而不指定 T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个接口,方法如下:

I have an interface with a method as follows:

public interface IRepo
{
    IA<T> Reserve<T>();
}

我想模拟包含此方法的类,而不必为它可以用于的每种类型指定 Setup 方法.理想情况下,我希望它返回一个 new mock<T>.Object.

I would like to mock the class that contains this method without having to specify Setup methods for every type it could be used for. Ideally, I'd just like it to return a new mock<T>.Object.

我如何做到这一点?

看来我的解释不清楚.这是一个示例 - 当我指定 T(此处为字符串)时,现在这是可能的:

It seems my explanation was unclear. Here's an example - this is possible right now, when I specify the T (here, string):

[TestMethod]
public void ExampleTest()
{
    var mock = new Mock<IRepo>();
    mock.Setup(pa => pa.Reserve<string>()).Returns(new Mock<IA<string>>().Object);
}

我想要实现的是这样的:

What I would like to achieve is something like this:

[TestMethod]
public void ExampleTest()
{
    var mock = new Mock<IRepo>();
    mock.Setup(pa => pa.Reserve<T>()).Returns(new Mock<IA<T>>().Object);
    // of course T doesn't exist here. But I would like to specify all types
    // without having to repeat the .Setup(...) line for each of them.
}

被测对象的某些方法可能会为三种或四种不同类型调用保留.如果我必须设置所有类型,我必须为每个测试编写大量设置代码.但在单个测试中,我并不关心所有这些,我只需要非空的模拟对象,除了我实际测试的对象(我很乐意为此编写更复杂的设置).

Some methods of the object under test might call reserve for three or four different types. If I have to setup all the types I have to write a lot of setup code for every test. But in a single test, I am not concerned with all of them, I simply need non-null mocked objects except for the one that I am actually testing (and for which I gladly write a more complex setup).

推荐答案

除非我误解你需要什么,否则你可以构建一个这样的方法:

Unless I'm misunderstand what you need, you could build a method like this:

private Mock<IRepo> MockObject<T>()
{
    var mock = new Mock<IRepo>();
    return mock.Setup(pa => pa.Reserve<T>())
        .Returns(new Mock<IA<T>>().Object).Object;
}

这篇关于在 Moq 中模拟泛型方法而不指定 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:Moles Isolation 框架是如何实现的? 下一篇:如何最小起订量索引属性

相关文章

最新文章