【问题标题】:How do I break Test Unit Code off into 'Re-usable' Code?如何将测试单元代码分解为“可重用”代码?
【发布时间】:2016-01-23 04:16:08
【问题描述】:

我在一些测试方法中模拟 HTTPContext。我有很多方法需要编写,所以我宁愿重复使用代码而不是每次都编写它。保持干燥。

我正在实施this method of Faking (Mocking) HTTPContext。我读到我需要将其分解为 Factory 以在其他单元测试中重新使用它。

问题:如何将此代码放入工厂以在单元测试中重复使用?除了“工厂”之外,还有更好的方法来重新使用它吗?我该如何实现。


测试代码

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

【问题讨论】:

    标签: c# unit-testing methods mocking httpcontext


    【解决方案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();
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2014-07-24
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2010-12-03
      • 2012-05-16
      相关资源
      最近更新 更多