简体   繁体   English

创建 Mock 的通用方法<interface>起订量

[英]Generic method for creating Mock<interface> by Moq

I am trying to create some abstract class which will keep some common operation for preparing Stubs by Moq.我正在尝试创建一些抽象类,该类将保留一些用于按 Moq 准备存根的常见操作。 I wrote something but I cannot overcome errors我写了一些东西,但我无法克服错误

public abstract class StubsCreatorAbstract
{
    public Mock<T> GenerateObject<T>() where T : IStub
    {
        var mock = new Mock<T>();
        return mock;
    }

    public Mock<D> SetupValue<T, D>(Mock<D> stub, string nameOfField, T value) where D : IStub
    {
        var field = typeof(D).GetProperty(nameOfField);
        if (field == null)
        {
            throw new ArgumentException("Field do not exist");
        }

        field.SetValue(stub.Object, value);
        return stub;
    }
 }

The problems is: Mock must be a reference type.问题是: Mock 必须是引用类型。 My question is - it's possible to overcome that problem?我的问题是 - 有可能克服这个问题吗? Thanks in advance提前致谢

Update:更新:

That's compiler error.那是编译器错误。 Problem regarding to T - it's saying关于 T 的问题 - 它说

"the type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Mock<T>".

The short answer is that:简短的回答是:

public Mock<T> GenerateObject<T>() where T : IStub
{
    var mock = new Mock<T>();
    return mock;
}

won't work.不会工作。 Instead you should use:相反,您应该使用:

new Mock<YourTypeHere>();

instead.反而。

As to why your original code doesn't work, I've done a bit of research but I am not 100% sure why.至于为什么你的原始代码不起作用,我做了一些研究,但我不是 100% 确定为什么。

It seems like you are using a non reference type as the generic constraint.似乎您正在使用非引用类型作为通用约束。 I believe IStub is the interface that is being implemented in the concrete class that you are using.我相信 IStub 是在您正在使用的具体类中实现的接口。 if you specify the constraint like below, it will work fine.如果您指定如下约束,它将正常工作。

If you want more specific constraint, let your classes inherit from a base class and give that as the constraint here.如果您想要更具体的约束,请让您的类从基类继承并在此处将其作为约束。

 public abstract class StubsCreatorAbstract
{
    public Mock<T> GenerateObject<T>() where T : class 
    {
        var mock = new Mock<T>();
        return mock;
    }

    public Mock<D> SetupValue<T, D>(Mock<D> stub, string nameOfField, T value) where D : class
    {
        var field = typeof(D).GetProperty(nameOfField);
        if (field == null)
        {
            throw new ArgumentException("Field do not exist");
        }

        field.SetValue(stub.Object, value);
        return stub;
    }
}

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

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