简体   繁体   English

Moq模拟通用类

[英]Moq mock generic class

Having the following in my code: 在我的代码中包含以下内容:

var contact = m_someFactory.Create<IContact>(contact, Page.ID);

code from Factory: 工厂代码:

ObjectFactory implements AbstractFactory ObjectFactory实现AbstractFactory

    ObjectsFactory : AbstractFactory
{
    public T Create<T>()
    {
        var factory = this as IInsertFactoryMethod<T>;
        return factory != null
            ? factory.Create()
            : default(T);
    }

I want to be able to mock this. 我希望能够模拟这个。 I've created a class that implements IContact 我创建了一个实现IContact的类

public class Contact{
      public Name {get; set;}  
      IOrganization Organization { get; set; }
}

For setup I tried this: 对于安装程序,我尝试了此操作:

FactoryMock = new Mock<ObjectsFactory>();
FactoryMock.Setup(x => x.Create<IContact>()).Returns(new Mock<IContact>().Object);

and this 和这个

FactoryMock.Setup(x => x.Create<IContact>(null, It.IsAny<int>())).Returns(new Mock<IContact>().Object);

During the setup I get the following: 在安装过程中,我得到以下信息:

Additional information: Invalid setup on a non-virtual (overridable in VB) member: x => x.Create() 附加信息:在非虚拟(在VB中可重写)成员上的无效设置:x => x.Create()

What am I doing wrong? 我究竟做错了什么?

UPDATE: In my code I have the following: 更新:在我的代码中,我有以下内容:

    var contact = m_someFactory.Create<IContact>(contact, Page.ID);
var organization = contact.Organization;

How would I set this up if Organization is an interface in Contact? 如果组织是Contact中的界面,我将如何设置?

You can't Setup a method that isn't virtual in Moq . 您无法Setup Moq中非虚拟的方法 Here, Factory.Create is not marked as virtual. 在这里, Factory.Create未标记为虚拟。

Changing the signature of Create to make it virtual will allow the mock to work as you're intending it, but you're generally better off mocking interfaces rather than concretes. 更改Create的签名使其虚拟,可以使模拟按照您的预期工作,但是通常比模拟界面更好,而不是具体的。 This demonstrates one reason why: you're changing your implementation to make it testable for your testing framework. 这说明了一个原因:您正在更改实现以使其可用于您的测试框架。

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

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