模拟Ajax.IsRequest返回False [英] Mocking Ajax.IsRequest to return False

查看:72
本文介绍了模拟Ajax.IsRequest返回False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟ASP.Net MVC的Ajax.IsRequest()方法.我发现了如何使它返回true:

I am trying to mock the Ajax.IsRequest() method of ASP.Net MVC. I found out how to do it in order for it to return true:

Expect.Call(_myController.Request.Headers["X-Requested-With"]).Return("XMLHttpRequest").Repeat.Any();

这有效并返回true.现在,我需要测试代码的另一个分支.我该如何模拟它返回false?我尝试完全删除该模拟,但失败了:

This works and returns true. Now I need to test the other branch of the code. How can I mock it to return false? I have tried removing the mock altogether, It fails with:

System.NullReferenceException:对象引用未设置为的实例对象.]

System.NullReferenceException : Object reference not set to an instance of an object.]

如果我这样做:

Expect.Call(_templateReportController.Request["X-Requested-With"]).Return(null).Repeat.Any();

它以相同的错误失败.

整个测试:

  /// <summary>
    /// Tests the Edit Action when calling via Ajax
    /// </summary>
    [Test]
    public void Test_Edit_AjaxRequest()
    {
        Group group = new Group();
        group.ID = 1;
        group.Name = "Admin";
        IList<Group> groupList = new List<Group>() { group };

        Definition def  = new Definition();
        def.ID = 1;
        def.Name = "Report";
        def.LastModified = DateTime.UtcNow;
        def.Groups.Add(group);


        using (_mocks.Record())
        {
            Expect.Call(_myController.Request["X-Requested-With"]).Return("XMLHttpRequest").Repeat.Any();
            Expect.Call(_DefBiz.GetAll<Group>()).Return(groupList);
            Expect.Call(_DefBiz.Get<Definition>(1)).Return(def);
        }

        myController.DefAccess = _DefBiz;
        PartialViewResult actual;

        using (_mocks.Playback())
        {
            actual = (PartialViewResult)myController.Edit(1);
        }


    }

有什么建议吗?干杯

推荐答案

得到 NullReferenceException 的原因是因为您从未在单元中添加 controller.Request 对象测试,当您调用使用 Request.IsAjaxRequest()的控制器操作时,它将引发.

The reason your are getting NullReferenceException is because you never stubbed the controller.Request object in your unit test and when you invoke the controller action which uses Request.IsAjaxRequest() it throws.

这是使用 Rhino.Mocks 来模拟上下文的方法:

Here's how you could mock the context using Rhino.Mocks:

[TestMethod]
public void Test_Ajax()
{
    // arrange
    var sut = new HomeController();
    var context = MockRepository.GenerateStub<HttpContextBase>();
    var request = MockRepository.GenerateStub<HttpRequestBase>();
    context.Stub(x => x.Request).Return(request);
    // indicate AJAX request
    request.Stub(x => x["X-Requested-With"]).Return("XMLHttpRequest");
    sut.ControllerContext = new ControllerContext(context, new RouteData(), sut);

    // act
    var actual = sut.Index();

    // assert
    // TODO: ...
}

[TestMethod]
public void Test_Non_Ajax()
{
    // arrange
    var sut = new HomeController();
    var context = MockRepository.GenerateStub<HttpContextBase>();
    var request = MockRepository.GenerateStub<HttpRequestBase>();
    context.Stub(x => x.Request).Return(request);
    sut.ControllerContext = new ControllerContext(context, new RouteData(), sut);

    // act
    var actual = sut.Index();

    // assert
    // TODO: ...
}


这是一个更好的选择(我个人会建议您),以避免所有管道代码.使用 MVCContrib.TestHelper (基于 Rhino.Mocks ),您的单元测试可以简化为:


And here's a better alternative (which I would personally recommend you) in order to avoid all the plumbing code. Using MVCContrib.TestHelper (which is based on Rhino.Mocks) your unit test might be simplified to this:

[TestClass]
public class HomeControllerTests : TestControllerBuilder
{
    private HomeController _sut;

    [TestInitialize()]
    public void MyTestInitialize() 
    {
        _sut = new HomeController();
        this.InitializeController(_sut);
    }

    [TestMethod]
    public void HomeController_Index_Ajax()
    {
        // arrange
        _sut.Request.Stub(x => x["X-Requested-With"]).Return("XMLHttpRequest");

        // act
        var actual = _sut.Index();

        // assert
        // TODO: ...
    }

    [TestMethod]
    public void HomeController_Index_Non_Ajax()
    {
        // act
        var actual = _sut.Index();

        // assert
        // TODO: ...
    }
}

更漂亮.它还使您可以对操作结果编写更具表现力的断言.签出文档或询问是否需要更多信息.

Much prettier. It also allows you to write much more expressive asserts on the action results. Checkout the doc or ask if for more info is needed.

这篇关于模拟Ajax.IsRequest返回False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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