嘲讽和HttpContextBase.get_User() [英] Mocking and HttpContextBase.get_User()

查看:131
本文介绍了嘲讽和HttpContextBase.get_User()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要嘲弄一个的HttpContext的User属性。
我使用的是斯科特Hanselmans MVCHelper类和RhinoMocks的。

I want to mock the User property of an HttpContext. I'm using Scott Hanselmans MVCHelper class and RhinoMocks.

我有一个包含code,这样的单元测试:

I have a unit test that contains code, like this:

...

MockIdentity fakeId = new MockIdentity("TEST_USER", "Windows", true);
MockPrincipal fakeUser = new MockPrincipal(null, fakeId);

using (mocks.Record())
{
    Expect.Call(fakeHttpContext.User).Return(fakeUser);
}

...

我MockIdentity和MockPrincipal类是符合的IIdentity和IPrincipal的嘲笑,分别为。

My MockIdentity and MockPrincipal classes are mocks conforming to IIdentity and IPrincipal, respectively.

我在运行单元测试,当得到一个错误报告:

I get an error when running the unit test that reports:

System.NotImplementedException:本
  方法或操作不
  实现。在System.Web.HttpContextBase.get_User()

System.NotImplementedException : The method or operation is not implemented. at System.Web.HttpContextBase.get_User()

这是发生在我试图设置用户属性的期望。

This is happening when I'm trying to set the expectation for the User property.

据我了解,httpContextBase有一个getter和setter未实现,但我认为,当嘲笑犀牛会处理这个问题。

I understand that the httpContextBase has a getter and setter that aren't implemented but I thought that Rhino would handle this when mocking.

这是否意味着我必须从HttpContextbase派生并覆盖我的模仿对象的属性。这似乎很奇怪。

Does this mean that I have to derive from the HttpContextbase and override the property for my mock object. It seems odd.

其他用户有过这样的问题,都能在这里找到报道:
http://www.mail-archive.com/rhinomocks@googlegroups.com /msg00546.html

Other users have had this issue and it's reported here: http://www.mail-archive.com/rhinomocks@googlegroups.com/msg00546.html

推荐答案

要嘲笑用户属性,你可以这样做:

To mock the user property, you can do this:

var httpContext = MockRepository.GenerateStub<HttpContextBase>();
httpContext.Stub(x=>x.User).Return(yourFakePrincipalHere);

var controllerContext = new ControllerContext(httpContext, ....);

var controller = new HomeController();
controller.ControllerContext = controllerContext;

(这里使用了新的RM 3.5 API,如果你这样做瓦特/记录/回放,则:

(this uses the new RM 3.5 api, if you're doing it w/ record/replay then:

using(mocks.Record)
{
   _httpContext = _mocks.DynamicMock<HttpContextBase>();
   SetupResult.For(_httpContext.User).Return(...);
}

using(mocks.PlayBack())
{
   ....
}

这篇关于嘲讽和HttpContextBase.get_User()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆