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