Reputation: 566
I am trying to build a Generic testbuilder for generating objects, that i want to use in tests. One of the things I want to create is Mock implementations of interfaces. I want these Mocks to have Strict mockbehaviour, and the only way to set that afaik is by constructor parameter. I am using this code to create my interface mock:
public object Build(Type type)
{
if (type.IsInterface)
{
List<object> mockParameters = new List<object>();
mockParameters.Add(MockBehavior.Strict);
Mock mock = (Mock)Activator.CreateInstance(typeof(Mock<>).MakeGenericType(type), mockParameters);
return mock.Object;
}
}
This gives me an ArgumentException: Constructor arguments cannot be passed for interface mocks. How can i set MockBehavior.Strict on my mock created with reflection?
Upvotes: 3
Views: 2580
Reputation: 174289
Your code can be greatly simplified to this:
public T Build()
{
if (typeof(T).IsInterface)
{
return new Mock<T>(MockBehavior.Strict).Object;
}
}
Upvotes: 1