2016-01-23 54 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(); 
    ... 
}