开发者

How do I create a mock using reflection with parameters using Moq?

开发者 https://www.devze.com 2023-04-08 18:37 出处:网络
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 Str

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 afai开发者_如何学Gok 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?


Your code can be greatly simplified to this:

public T Build()
{
    if (typeof(T).IsInterface)
    {
       return new Mock<T>(MockBehavior.Strict).Object;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号