简体   繁体   English

是否可以使用 Rhino Mocks 存根我不关心类型的通用方法?

[英]Is it possible to use Rhino Mocks to stub a generic method where I don't care about the type?

I have a method with the following signature that I'd like to stub:我有一个带有以下签名的方法,我想存根:

async Task<T> MyMethod<T>(SomeClass, bool, string, string, string, params object[])

The generic type, T, is the type that we expect the method to return (data returned from the server is cast to type T).泛型类型 T 是我们期望方法返回的类型(从服务器返回的数据被强制转换为类型 T)。 Note that it can't be inferred from parameters passed in;注意,不能从传入的参数中推断出来; it has to be specified each time.每次都必须指定它。

I need to create a stub for this method in Rhino Mocks, but it's expecting me to provide the generic type.我需要在 Rhino Mocks 中为这个方法创建一个存根,但它希望我提供泛型类型。 I would like it to cater for calls with any type.我希望它能够满足任何类型的呼叫。 I tried using <object> , but it then expects a call with that specific type.我尝试使用<object> ,但它随后需要使用该特定类型的调用。

I can see why this would be a problem, because calls to generic types are dealt with at compile-time, not run-time.我可以理解为什么这会是一个问题,因为对泛型类型的调用是在编译时处理的,而不是运行时。

Thought it would be worth asking, though, just in case I'm missing a trick.不过,我认为值得一问,以防万一我错过了一个技巧。

Edit 1编辑 1

I should have included that for now I've implemented a workaround whereby I've wrapped my stub builder in a helper method that is itself a generic method.我应该包括现在我已经实现了一个解决方法,我已经将我的存根构建器包装在一个辅助方法中,该方法本身就是一个通用方法。

The problem with this, though, is that I have to specify the type, and then only that type is catered for.但是,这样做的问题是我必须指定类型,然后只满足该类型。 The system under test may make several calls to the method that I'm stubbing, and I need a 'catch all' that caters for all types.被测系统可能会多次调用我正在存根的方法,我需要一个适合所有类型的“全部捕获”。

Edit 2编辑 2

My improved workaround has been to not use Rhino Mocks at all.我改进的解决方法是根本不使用 Rhino Mocks。 In stead, I'm using a mock class that implements the interface.相反,我使用了一个实现接口的模拟类。 This makes it easy to implement the generic method and return a default value (or one that's been set during construction).这使得实现泛型方法并返回默认值(或在构造期间设置的值)变得容易。 I'd still like to know if it's possible in Rhino Mocks though!不过,我仍然想知道在 Rhino Mocks 中是否可行!

You could try creating the stub in a generic method, and just return a default instance of the given type, like so:您可以尝试在通用方法中创建存根,然后只返回给定类型的默认实例,如下所示:

static void SetUpAStub<T>() 
        where T : new()
{
    var stub = MockRepository.GenerateStub<IMyInterface>();
    stub.Stub(i => i.MyMethod<T>(null, false, string.Empty, string.Empty, string.Empty))
        .Return(new TaskFactory().StartNew( () => new T()));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM