Moq: impossible to execute

I have the following mocks:

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

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

Error testing this line:

var user = (CustomPrincipal)httpContext.User;

This is mistake:

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

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

+2
source share
2 answers

The reason you cannot use it is because MOQ creates its own class that implements IPrinciple. In particular, IPrincipalProxy5c6adb1b163840e192c47295b3c6d696. But just because both of these classes implement the same interface does not mean that you can drop from one class to another. Why do you need this? Why can't you use the members on the IPrinciple provided by MOQ?

+4

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

All Articles