简体   繁体   English

当嘲笑实现具有相同方法签名的多个接口的接口时,Moq Setup InvalidCastException

[英]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(). 我想模拟ChildInterface并设置其Foo()。 So I used Moq to do this: 所以我用Moq来做到这一点:

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问题的解释 So I did that. 所以我做到了。 And it compiles without errors ! 并且它编译没有错误

But upon running it, it throws an InvalidCastException 但是在运行它时,它将引发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? 您对起订量如何工作有任何想法吗?

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM