基于Spring Boot的API测试

互联网产品的测试策略现在很多都会存在API测试、轻量级GUI测试、轻量级单元测试等。API测试其实我们一开始想得最多的图形化工具应该是postman、jmeter等。如果使用最简单的get方法,还可以直接通过使用CURL命令(即命令行工具cURL)。

1.API测试的基本步骤

不管使用什么API测试工具,API测试的基本步骤大体一致:
1.准备测试数据
2.通过API测试工具,发起对被测API的request
3.验证返回结果的response

2.基于Spring Boot构建的API

我们平时在工作中,接触得最多的是用JAVA框架Spring boot框架开发的简单的Restful API。
Springboot建议的目录结果如下:root package结构-com.example.myproject

  • 1.Application.java:根目录,主要用于做一些框架配置
  • 2.domain目录主要用于实体(Entity)与数据访问层(Repository)
  • 3.service层主要是业务类代码
  • 4.controller负责页面访问控制
    springboot目录结构

    下面例子是一个Account API的功能,基于提供的ID值创建一个Account对象,并返回这个新创建Account对象。
    git代码地址:https://github.com/SpectoLabs/spring-cloud-contract-blog/tree/master/account-service
  • 1.Services类
    AccountService.getById(String id)方法,具体逻辑就是返回一个以传入ID为ID的Account对象
package com.demo.account.services;
import com.demo.account.domains.Account;
import org.springframework.stereotype.Service;
@Service
public class AccountService {
    public Account getById(String id) {
        return new Account(id, "friends", "tom@api.io");
    }
}
  • 2.controller类
    @RestController是指controller里面的方法都是以json格式输出,不用在写什么jackjson配置
    @RequestMapping(method = RequestMethod.GET, value = "/account/{id}"):说明API的endpoint以及对应的操作是GET方法
    public Account getAccount(@PathVariable String id) {return accountService.getById(id); }:说明了GET方法具体的业务逻辑是由accountService.getById()方法实现的。
package com.demo.account.controllers;
import com.demo.account.domains.Account;
import com.demo.account.services.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AccountController {
    private final AccountService accountService;
    @Autowired
    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }
    @RequestMapping(method = RequestMethod.GET, value = "/account/{id}")
    public Account getAccount(@PathVariable String id) {
        return accountService.getById(id);
    }
}
  • 3.domains类
package com.demo.account.domains;
public class Account {
    private final String id;
    private final String type;
    private final String email;
    public Account(String id, String type, String email) {
        this.id = id;
        this.type = type;
        this.email = email;
    }
    public String getId() {
        return id;
    }
    public String getType() {
        return type;
    }
    public String getEmail() {
        return email;
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容