Tried to force to create mock httpcontext objects, but does not work. Somewhere I came across a message that I need to create my own rest api client, for example, via restsharp. is it so bad? Maybe there are ways?

  • 2
    What exactly are you going to check in the tests? The fact that the standard mechanism will work in the presence of the attribute? There is no point in writing an integration test on the standard mechanism - you don’t write tests to ensure that standard binders work, deserialization works, serialization works, the data that you returned from the controller will go to the client. You need to test the behavior (which is already covered by tests on the attribute code), and not the state (that the attribute is somewhere). :) - PashaPash

1 answer 1

If we are talking about unit testing, the Authorize attribute does not interfere with testing the controller method, with the exception of methods that access the current HttpContext (for example, find out the current user HttpContext.User).

In this case, you need to create the HttpContext mock and create a controller using this mock.

[TestInitialize] public void SetupTests() { // Setup Rhino Mocks rmContext = MockRepository.GenerateMock<HttpContextBase>(); rmRequest = MockRepository.GenerateMock<HttpRequestBase>(); rmContext.Stub(x => x.Request).Return(rmRequest); // Setup Moq moqContext = new Mock<HttpContextBase>(); moqRequest = new Mock<HttpRequestBase>(); moqContext.Setup(x => x.Request).Returns(moqRequest.Object); } [TestMethod] public void RhinoMocksControllerContextTest() { // Arrange var controller = new SubscribeController(); var context = new ControllerContext(rmContext, new RouteData(), controller); controller.ControllerContext = context; var parameters = new SubscribeParameter(); // Act var result = controller.SignUp(parameters) as ProcessResult<SubscribeParameter>; // Use ViewResult here for your results. This is a specific ActionResult I built. // Assert Assert.IsNotNull(result); } 

More details can be found here - http://www.danylkoweb.com/Blog/how-to-successfully-mock-httpcontext-BT