vendredi 22 janvier 2016

How do I break Test Unit Code off into 'Re-usable' Code?

I am mocking the HTTPContext in some test methods. I have a lot of methods I need to write so I would rather re-use code than write it each time. Stay DRY.

I am implementing this method of Faking (Mocking) HTTPContext. I read that I need to break this off into a Factory to re-use it in other Unit-Test's.

Question: How do I put this code into a Factory to re-use it in Unit-Tests? Is there a better way other that a 'Factory' to re-use this? How can I implement that.


Test Code

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

}

Aucun commentaire:

Enregistrer un commentaire