本文介绍了最小起订量:无法投射到界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早些时候,我问了这个问题.

earlier today I asked this question.

因此,由于moq从接口创建了它自己的类,所以我无法将其强制转换为其他类.

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

所以我想知道如果我创建一个ICustomPrincipal并尝试强制转换为该值.

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;

错误如下:

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

我想我仍然需要一些接口和moq方面的练习,但是我不应该将moq创建的类强制转换回ICustomPrincipal吗?我知道httpContext.User返回一个IPrincipal,所以可能在那里丢失了某些东西?

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.

像素


根据要求,我正在测试该方法的完整代码.尚未完成,但这是我到目前为止的内容:


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;
}

Edit2:

似乎,如果我使用Thread.CurrentPrincipal而不是HttpContext.current.user,我可以毫无问题地进行转换.现在阅读一下两者之间的区别.

Seems that if I use Thread.CurrentPrincipal instead of HttpContext.current.user I can cast it without a problem. Reading up on the differences between the two now.

推荐答案

我认为您需要能够将模拟内容注入代码...

I think you need to be able to inject your mocks into your code...

例如,在您的班级中,如果您添加以下内容:

For instance, in your class if you add the following:

public static HttpContextBase HttpContext;
public static ICustomPrincipal User;

并在您的代码中包含以下内容...

and have the following in your code...

var user = (ICustomPrincipal)User;

并在您的受测类中(例如,它被命名为ClassUnderTest)

and in your class under test (say it is named ClassUnderTest)

ClassUnderTest.HttpContextBase = MockHttpContext.Object;

ClassUnderTest.User = MockPrincipal.Object;

好吧...我认为那应该为您解决问题.

well... I think that that should fix things for you.

这篇关于最小起订量:无法投射到界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:57