MVC3 unit testing response code

后端 未结 2 550
别跟我提以往
别跟我提以往 2020-12-09 11:42

I have a controller within MVC3 which needs to return a response code 500 if something goes wrong. I am doing this by returning a view object and setting http response code

相关标签:
2条回答
  • 2020-12-09 12:03

    What is FakeHttpObject()? Is it a mock created using Moq? In that case you need to setup setters and getters to store the actual values somewhere. Mock<T>doesn't provide any implementation for properties and methods. When setting a value of property literally nothing happens and the value is 'lost'.

    Another option is to provide a fake context that is a concrete class with real properties.

    0 讨论(0)
  • 2020-12-09 12:08

    How about doing it in a more MVCish way:

    public ActionResult Http500()
    {
        return new HttpStatusCodeResult(500, "An error occurred whilst processing your request.");
    }
    

    and then:

    // arrange
    var sut = new HomeController();
    
    // act
    var actual = sut.Http500();
    
    // assert
    Assert.IsInstanceOfType(actual, typeof(HttpStatusCodeResult));
    var httpResult = actual as HttpStatusCodeResult;
    Assert.AreEqual(500, httpResult.StatusCode);
    Assert.AreEqual("An error occurred whilst processing your request.", httpResult.StatusDescription);
    

    or if you insist on using the Response object you could create a fake one:

    // arrange
    var sut = new HomeController();
    var request = new HttpRequest("", "http://example.com/", "");
    var response = new HttpResponse(TextWriter.Null);
    var httpContext = new HttpContextWrapper(new HttpContext(request, response));
    sut.ControllerContext = new ControllerContext(httpContext, new RouteData(), sut);
    
    // act
    var actual = sut.Http500();
    
    // assert
    Assert.AreEqual(500, response.StatusCode);
    Assert.AreEqual("An error occurred whilst processing your request.", response.StatusDescription);
    
    0 讨论(0)
提交回复
热议问题