2016-01-23 47 views
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()); 
} 

回答

1

这取决于你的需求。
也许这足以创建一个类,它将创建你假冒的上下文实例。也许有一些方法可以让你创建充满不同数据的上下文。

public class FakeContextFactory 
{ 
    public ControllerContext Create() {/*your mocking code*/} 

    public ControllerContext Create(NameValueCollection formVariables) {...} 

    ... 
} 

public void Test() 
{ 
    var context = new FakeContextFactory().Create(); 
    ... 
} 

在某些情况下,它可能是静态工厂代表的静态工厂。

如果您需要很多不同的上下文,可能最好使用构建器模式。

public void Test() 
{ 
    var context = FakeContextBuilder.New() 
         .SetRequestMethod("POST") 
         .Build(); 
    ... 
}