在嘲弄起订量泛型方法不指定牛逼 [英] Mocking generic methods in Moq without specifying T

查看:149
本文介绍了在嘲弄起订量泛型方法不指定牛逼的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an interface with a method as follows:

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

我想模拟包含此方法,而不必指定设置方法为每一类型它可被用来为类。理想情况下,我只是喜欢它返回一个新模拟&LT; T&GT;。.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.
}

对象的待测的某些方法可能称之为储备三种或四种不同类型的。如果非要安装所有类型我都写了很多设置code为每个测试。但是,在一个单一的测试,我不关心所有的人,我只需要除了一个我实际测试非空嘲笑的对象(和我很高兴地谱写出更加复杂的设置)。

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;
}

这篇关于在嘲弄起订量泛型方法不指定牛逼的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆