Pickels
Pickels

Reputation: 34630

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?

Upvotes: 3

Views: 4761

Answers (2)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68677

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?

Upvotes: 5

Amy B
Amy B

Reputation: 110111

Same reason this won't work

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

Upvotes: 5

Related Questions