0

I am trying to unit test an ApiController and set the current HttpContext, but every time I try and set the request information for the controller HttpContext.Current still seems to be null.

Here is the code:

[TestMethod]
public void MakePayment()
{
     var config = new HttpConfiguration();
     var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/payment");
     var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
     var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "payment" } });

     var mockUserStore = new Mock<IUserStore<ApplicationUser>>();
     var mockUserManager = new Mock<ApplicationUserManager>(mockUserStore.Object);
     mockUserManager.Setup(x => x.GetUser(It.IsAny<string>())).Returns(new ApplicationUser());

     IPayPalService payPalService = new PayPalService(mockUserManager.Object);

     var paymentController = new PaymentController(payPalService);
     paymentController.ControllerContext = new HttpControllerContext(config, routeData, request);
     paymentController.Request = request;
     paymentController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

     Payment payment = paymentController.DepositMoney(50.00);

     Assert.AreEqual(payment.intent, "sale");
}

Is there anything that I am missing here?

2
  • I'm not sure if you can just use the set properties of HttpContext to set the Request. This answer to a similar question is using a mocking framework to stub out the Request get instead. Commented Jul 29, 2014 at 17:53
  • Also, I am confused... is it the HttpContext.Current that is null? Or is it the context.Request? Commented Jul 29, 2014 at 17:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.