Moq: Unable to cast to interface

雨燕双飞 提交于 2019-12-05 09:50:58

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;

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

ClassUnderTest.HttpContextBase = MockHttpContext.Object;

and

ClassUnderTest.User = MockPrincipal.Object;

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

Shane

Your code example show that you are mocking a http context and principal objects.

However, your code example in which you are trying to get the user it is hard to determine if you are using the Mock http context or one provided by the framework?

var user = (ICustomPrincipal)httpContext.User;

Is the above line used in a method or object using dependency injection?

Are you able to show me the method / object as a whole?

I'm guessing you have some confusion in namespaces / interface names. Are you sure, you're casting to the same ICustomPrincipal, for which you create your mock?

And why is it saying "IPrincipalProxy" in the error message? Are you mocking IPrincipal interface somewhere? Then what's the relation between IPrincipal and ICustomPrincipal?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!