aiapatag
aiapatag

Reputation: 3430

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

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?

Upvotes: 2

Views: 942

Answers (1)

dcastro
dcastro

Reputation: 68720

Try this:

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

Upvotes: 5

Related Questions