Moq Setup InvalidCastException when Mocking an interface that implements multiple interfaces having the same method signature

蓝咒 提交于 2020-01-04 13:45:07

问题


So I have the following code:

interface Parent1
{
    void Foo();
}

interface Parent2
{
    void Foo();
}

interface ChildInterface : Parent1, Parent2
{
}

I want to mock ChildInterface and setup its Foo(). So I used Moq to do this:

var c = new Mock<ChildInterface>(MockBehavior.Strict);
c.Setup(p1 => ((Parent1)p1).Foo());
c.Setup(p2 => ((Parent2)p2).Foo());

It cannot just accept without doing an explicit casting. From explanations from this SO question. So I did that. And it compiles without errors!

But upon running it, it throws an InvalidCastException

Here is the stack trace:

   at lambda_method(Closure )
   at Moq.Mock.GetInterceptor(Expression fluentExpression, Mock mock)
   at Moq.Mock.<>c__DisplayClass19`1.<Setup>b__18()
   at Moq.PexProtector.Invoke[T](Func`1 function)
   at Moq.Mock.Setup[T](Mock`1 mock, Expression`1 expression, Func`1 condition)
   at Moq.Mock`1.Setup(Expression`1 expression)

Do you have any ideas on how this can work in Moq?


回答1:


Try this:

c.As<Parent1>().Setup(p1 => p1.Foo());
c.As<Parent2>().Setup(p2 => p2.Foo());


来源:https://stackoverflow.com/questions/19932493/moq-setup-invalidcastexception-when-mocking-an-interface-that-implements-multipl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!