Moq: Unable to cast
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?
Same reason this won't work
class WoodDuck : IQuack {}
class RealDuck : IQuack {}
//
IQuack myQuacker = new WoodDuck();
RealDuck myDuck = (RealDuck) myQuacker;
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?
精彩评论