0
我在一些測試方法中嘲笑HTTPContext。我需要寫很多方法,所以我寧願重複使用代碼,也不願每次寫入代碼。保持乾爽。我正在執行this method of Faking (Mocking) HTTPContext。我讀到,我需要將其分解爲工廠,以便在其他單元測試中重新使用它。如何將測試單元代碼分解爲「可重用」代碼?
問題:如何將此代碼放入工廠以在單元測試中重新使用它?除了「工廠」以外,還有其他更好的方法來重用嗎?我如何實現這一點。
測試代碼
public class MyController : Controller
{
[HttpPost]
public void Index()
{
Response.Write("This is fiddly");
Response.Flush();
}
}
//Unit Test
[Fact]
public void Should_contain_fiddly_in_response()
{
var sb = new StringBuilder();
var formCollection = new NameValueCollection();
formCollection.Add("MyPostedData", "Boo");
var request = A.Fake<HttpRequestBase>();
A.CallTo(() => request.HttpMethod).Returns("POST");
A.CallTo(() => request.Headers).Returns(new NameValueCollection());
A.CallTo(() => request.Form).Returns(formCollection);
A.CallTo(() => request.QueryString).Returns(new NameValueCollection());
var response = A.Fake<HttpResponseBase>();
A.CallTo(() => response.Write(A<string>.Ignored)).Invokes((string x) => sb.Append(x));
var mockHttpContext = A.Fake<HttpContextBase>();
A.CallTo(() => mockHttpContext.Request).Returns(request);
A.CallTo(() => mockHttpContext.Response).Returns(response);
var controllerContext = new ControllerContext(mockHttpContext, new RouteData(), A.Fake<ControllerBase>());
var myController = GetController();
myController.ControllerContext = controllerContext;
myController.Index();
Assert.Contains("fiddly", sb.ToString());
}