سؤال

I have a unit test that test route with too many segments, but I'd like to extend it to test Response Status Code (which should return 404 code).

Is it possible to use that mocked httpContext and check a status code?

HttpContextMock.Object.Response.StatusCode always returns 0 status code (due to mocking just one part of HttpContext I suppose).

[TestMethod]
public void RouteWithTooManySegments()
{
    var routes = new RouteCollection();
    MyApp.RouteConfig.RegisterRoutes(routes);

    var httpContextMock = new Mock<HttpContextBase>();
    var httpResponseMock = new Mock<HttpResponseBase>();

    httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath)
        .Returns("~/dawd/dawdaw/dawdaw/daw");

    RouteData routeData = routes.GetRouteData(httpContextMock.Object);

    Assert.IsNull(routeData);
}

Using ErrorController to return status code "404" in the view and appropriate Response Status Code:

public class ErrorController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

and Web.Config rules

 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
 </httpErrors>
هل كانت مفيدة؟

المحلول

The below Unit Test would verify the HttpStatusCode would set to 404. Note it must be set in your Controller's Action as you have in your question. If you expect the Web.config to interact it is more of a web integration test, which is completely a different test.

[TestMethod]
public void RouteWithTooManySegments()
{
    var httpContextStub = new Mock<HttpContextBase>();
    var httpResponseMock = new Mock<HttpResponseBase>();
    var controllerContextStub = new Mock<ControllerContext>();

    httpContextStub.Setup(x => x.Response).Returns(httpResponseMock.Object);
    controllerContextStub.Setup(x => x.HttpContext)
        .Returns(httpContextStub.Object);

    var sut = new ErrorController
        { ControllerContext = controllerContextStub.Object };

    sut.NotFound();

    httpResponseMock.VerifySet(x => x.StatusCode = 404);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top