Moq: Unable to cast to interface

Posted by Pickels on Stack Overflow See other posts from Stack Overflow or by Pickels
Published on 2010-05-05T21:33:05Z Indexed on 2010/05/05 23:18 UTC
Read the original article Hit count: 631

Filed under:
|
|

Hello,

earlier today I asked this question.

So since moq creates it's own class from an interface I wasn't able to cast it to a different class.

So it got me wondering what if I created a ICustomPrincipal and tried to cast to that.

This is how my mocks look:

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

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

In the method I am trying to test the follow code gives the error(again):

var user = (ICustomPrincipal)httpContext.User;

The error is the following:

Unable to cast object of type 'IPrincipalProxy4081807111564298854aabfc890edcc8' 
to type 'MyProject.Web.ICustomPrincipal'.

I guess I still need some practice with interfaces and moq but shouldn't I be able to cast the class that moq created back to ICustomPrincipal? I know httpContext.User returns an IPrincipal so maybe something gets lost there?

Well if anybody can help me I would appreciate that.

Pickels

Edit:
As requested the full code of the method I am testing. It's still not finished but this is what I have so far:

public bool AuthorizeCore(HttpContextBase httpContext)
{
    if (httpContext == null)
    {
        throw new ArgumentNullException("httpContext");
    }

    var user = (ICustomPrincipal)httpContext.User;

    if (!user.Identity.IsAuthenticated)
    {
        return false;
    }

    return true;
}

© Stack Overflow or respective owner

Related posts about moq

Related posts about c#