最小起订量:无法投放 [英] Moq: Unable to cast

查看:90
本文介绍了最小起订量:无法投放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模拟:

var MockHttpContext = new Mock<HttpContextBase>();
var MockPrincipal = new Mock<IPrincipal>();

MockHttpContext.SetupGet(h => h.User).Returns(MockPrincipal.Object);

测试此行时发生错误:

var user = (CustomPrincipal)httpContext.User;

这是错误:

Unable to cast object of type 'IPrincipalProxy5c6adb1b163840e192c47295b3c6d696' 
to type 'MyProject.Web.CustomPrincipal'.

我的CustomPrincipal实现IPrincipal接口.那么谁能解释我为什么会收到该错误以及如何解决该错误?

My CustomPrincipal implements the IPrincipal interface. So can anybody explain why I am getting that error and how I can solve it?

推荐答案

之所以无法进行转换,是因为MOQ正在创建自己的实现IPrinciple的类.特别是IPrincipalProxy5c6adb1b163840e192c47295b3c6d696.但是,仅仅因为这两个类都实现了相同的接口,并不意味着您可以从一个类转换为另一个类.为什么需要投射它?为什么不能使用MOQ提供的IPrinciple上的成员?

The reason you can't cast it is because MOQ is creating its own class which implements IPrinciple. Specifically the IPrincipalProxy5c6adb1b163840e192c47295b3c6d696. But just because both of those classes implement the same interface, does not mean you can cast from one class to another. Why do you need to cast it? Why can't you use the members on IPrinciple provided by MOQ?

这篇关于最小起订量:无法投放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆