【问题标题】:Integration tests for Rest APIRest API 的集成测试
【发布时间】:2015-11-06 11:57:43
【问题描述】:

我想就如何为 Rest API 创建集成测试获得不同的观点。

第一种选择是使用“黄瓜书”中描述的黄瓜

Scenario: Get person
  Given The system knows about the following person:
    | fname | lname | address | zipcode |
    | Luca  | Brow  | 1, Test | 098716  |
  When the client requests GET /person/(\d+)
  Then the response should be JSON:
    """
    {
      "fname": "Luca",
      "lname": "Brow",
      "address": {
        "first": "1, Test",
        "zipcode": "098716"
      }
    }
    """

第二种选择将(再次)使用cucumber,但删除技术细节,如here所述:

Scenario: Get person
  Given The system knows about the following person:
    | fname | lname | address | zipcode |
    | Luca  | Brow  | 1, Test | 098716  |
  When the client requests the person
  Then the response contains the following attributes:
    | fname            | Luca    |
    | lname            | Brow    |
    | address :first   | 1, Test |
    | address :zipcode | 098716  |

第三个选项是使用 Spring,如 here 所述:

private MockMvc mockMvc;

@Test
public void findAll() throws Exception {
    mockMvc.perform(get("/person/1"))
            .andExpect(status().isOk())
            .andExpect(content().mimeType(IntegrationTestUtil.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.fname", is("Luca")))
            .andExpect(jsonPath("$.lname", is("Brow")))
            .andExpect(jsonPath("$.address.first", is("1, Test")))
            .andExpect(jsonPath("$.address.zipcode", is("098716")));
}

我非常喜欢第二个选项,因为它对业务用户和测试人员来说看起来更简洁,但另一方面,对于将使用此 API 的开发人员来说,第一个选项看起来更明显,因为它显示了 JSON 响应。

第三种是最简单的,因为它只是Java代码,但可读性和跨团队交互不如黄瓜。

【问题讨论】:

    标签: spring api rest testing cucumber


    【解决方案1】:

    您应该使用第三个选项,但不要使用 junit,您应该使用 spock。这是两全其美的选择。

    Spock 测试是这样写的

    def "description of what you want to test"() {
        given:
            //Do what is pre-requisite to the test
    
        when:
            def response = mockMvc.perform(get("/person/id")).andReturn().getResponse();
    
        then:  
            checkForResponse.each {
            c->c(response )
    
        }
    
        where:
            id      | checkResponse
            1       | [ResponseChecker.correctPersondetails()]
            100     | [ResponseChecker.incorrectPersondetails()]
    
      }
    

    【讨论】:

      【解决方案2】:

      集成测试旨在测试您的应用程序的组件是否可以协同工作。例如,您使用集成测试测试对数据库和 mvc 控制器的一些请求。集成测试用于测试您的基础设施。

      另一方面,BDD 测试是为了促进开发和规范之间的沟通。常见的想法是通过示例编写测试或规范。绝对没有设计来编写集成测试。

      我会推荐第三种选择。

      【讨论】:

      • 您对 BDD 的定义不正确,BDD 测试行为或软件的公共接口,在这种情况下是应用程序暴露的端点。 BDD 还增加了测试的可读性,因为它们使用 GWT(Given-When_then) 格式。
      猜你喜欢
      • 2012-10-12
      • 1970-01-01
      • 2018-09-10
      • 2014-03-09
      • 2018-11-19
      • 2014-02-15
      • 2015-06-02
      • 1970-01-01
      • 2014-03-15
      相关资源
      最近更新 更多