Reputation: 21308
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?
Upvotes: 0
Views: 1380
Reputation: 23747
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.
Upvotes: 1