Moq: Unable to cast

房东的猫 提交于 2019-12-11 03:54:28

问题


I have the following mocks:

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

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

The error occurs when testing this line:

var user = (CustomPrincipal)httpContext.User;

This is the error:

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

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


回答1:


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?




回答2:


Same reason this won't work

class WoodDuck : IQuack {}
class RealDuck : IQuack {}
//
IQuack myQuacker = new WoodDuck();
RealDuck myDuck = (RealDuck) myQuacker;


来源:https://stackoverflow.com/questions/2774785/moq-unable-to-cast

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