简体   繁体   中英

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

    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

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()

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?

You can't Setup a method that isn't virtual in Moq . Here, Factory.Create is not marked as virtual.

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. This demonstrates one reason why: you're changing your implementation to make it testable for your testing framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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