MVC3 unit testing response code

孤人 提交于 2019-11-28 08:29:15

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!