如何写出基于验收的测试(从代码的角度来看)

时间:2013-02-05 13:17:52

标签: c# testing acceptance-testing

我一直在研究基于验收的测试,它们看起来相当不错,因为它们更适合基于特征的开发。

问题是我不知道如何在代码中列出它们。我想尝试避免拉入另一个框架来处理这个,所以我只是想找到一个简单的方法来启动和运行这些测试。

我愿意接受代码结构所需的任何更改。我也在使用规范来建立复杂的验收标准。

我想做的样本:

public class When_a_get_request_is_created
{
    private readonly IHttpRequest _request;

    public When_a_get_request_is_created()
    {
        _request = new HttpRequest();
    }

    // How to call this?
    public void Given_the_method_assigned_is_get()
    {
        _request = _request.AsGet();
    }

    // What about this?
    public void Given_the_method_assigned_is_not_get()
    {
        _request = _request.AsPost();
    }

    // It would be great to test different assumptions.
    public void Assuming_default_headers_have_been_added()
    {
        _request = _request.WithDefaultHeaders();
    }

    [Fact]
    public void It_Should_Satisfy_RequestIsGetSpec()
    {
        Assert.True(new RequestUsesGetMethodSpec().IsSatisfiedBy(_request));
    }
}

我可能完全偏离了这个标记,但基本上我希望能够运行具有不同假设和数量的测试。我不介意我是否必须制作更多的课程或轻微的重复,只要我能指出某人参加测试以验证给定的标准。

1 个答案:

答案 0 :(得分:1)

我强烈建议使用像SpecFlow甚至MSpec这样的ATDD框架来创建这种性质的测试。然后,实现SpecFlow是使用特定于域的语言编写规范的情况,与领域专家合作(如果这是合适的),然后通过代码满足功能中定义的方案步骤。在不了解更多有关您的确切要求的情况下填写代码方面很困难,但示例功能可能如下所示:

Feature: HTTP Requests
    In order to validate that HTTP requests use the correct methods
    As a client application
    I want specific requests to use specific methods

Scenario Outline: Making HTTP Requests
    Given I am making a request
    When the method assigned is <Method>
    And the <Header> header is sent
    Then it should satisfy the requirement for a <Method> request

Examples:
| Method | Header   |
| Get    | Header 1 |
| Get    | Header 2 |
| Get    | Header 3 |
| Post   | Header 1 |

然后在绑定到该功能的步骤中,您可以编写满足规范步骤的代码。这是一个例子:

[Binding]
public class HttpRequestSteps
{
    [When(@"the method assigned is (.*)")]
    public void WhenTheMethodAssignedIs(string method)
    {
        // not sure what this should be returning, but you can store it in ScenarioContext and retrieve it in a later step binding by casting back based on key
        // e.g. var request = (HttpRequest)ScenarioContext.Current["Request"]
        ScenarioContent.Current["Request"] = _request.AsGet();
    }
}