Rest API

时间:2015-11-06 11:57:44

标签: spring api rest testing cucumber

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

第一个选项是使用黄瓜,如" The Cucumber Book" 中所述:

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"
      }
    }
    """

第二个选项是(再次)使用黄瓜,但删除技术细节,如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代码,但可读性和跨团队交互并不像黄瓜那么好。

2 个答案:

答案 0 :(得分: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()]

  }

答案 1 :(得分:0)

进行集成测试以测试应用程序的组件是否可以一起工作。例如,您使用集成测试测试对数据库和mvc控制器的一些请求。集成测试用于测试您的基础架构。

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

我会推荐第三种选择。

相关问题