Testing Request object in Asp.net MVC

Posted by ercu

Some time ago I needed to test my Controllers, but they were depending on Referrer Url so I had to mock it. While searching I found a similar solution in MVCContrib's TestHelper documentation. So I ended up suiting it to my needs. In the function below you just have to pass the Controller as parameter. 

Used NUnit and Rhinomocks

private string referrerstr="http://thisisreferrer/";   //Don't forget to put "/" at the end of the url while testing

 private void CreateMockHttpContext(Controller controller)
        {
            var httpContext = MockRepository.GenerateStub<HttpContextBase>();

            httpContext.Stub(x => x.Request).Return(MockRepository.GenerateStub<HttpRequestBase>());

            //stub or mock what you need here

           httpContext.Request.Stub(x => x.UrlReferrer).Return(new Uri(referrerstr));          

            var context = new ControllerContext(httpContext,
                              new RouteData(),
                              controller);


            controller.ControllerContext = context;
        }

 

Then in my Test Method I just control Referer if it's equal to refererstr:

 [Test]
        public void CanCreateInstitution() {
            Institution institutionFromForm = CreateTransientInstitution();
            RedirectResult redirectResult = controller.Create(institutionFromForm)
                .AssertRedirect().ToUrl(refererstr);
            Assert.That(controller.TempData["message"].ToString().Contains("was successfully created"));
        }

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading