tags:

views:

78

answers:

2

Hello,

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?

Thanks in advance,

Pickels

+4  A: 

Same reason this won't work

class WoodDuck : IQuack {}
class RealDuck : IQuack {}
//
IQuack myQuacker = new WoodDuck();
RealDuck myDuck = (RealDuck) myQuacker;
David B
+1  A: 

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?

Yuriy Faktorovich
Because my CustomPrincipal has some extra methods which I need. Before I had my own interface ICustomPrincipal which I used to mock but that didn't work either.
Pickels
I'll mark this as the answer. I had a hunch Moq would create it's own class but wasn't sure so that's why I asked.Thanks again.
Pickels