Restful API接口测试四种方法
1.Mock单元测试
2.swagger
3.postman
4.Rest-Web-Service-Client
现有如下API接口:
请求方式:POST
url:http://localhost:60000/v1/login
请求体:{“username”:”admin”,”password”:”admin”}
返回状态码:200 成功
先介绍两款简单使用的客户端产品
一.Rest-Web-Service-Client
如下图所示。即可对接口进行测试
查看响应:
二.POSTMAN
同理,easy
重点介绍SpringBoot环境下的Mock API接口测试
三.Mock单元测试
1.pom文件中加入如下依赖
<!–单元测试–>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.Controller:
@RequestMapping(value = “/login”, method = RequestMethod.POST)
public ResponseBean authLogin(@RequestBody LoginVo login) {
if (login == null)
throw new ClientException(ErrorCode.API_EC_CLIENT_EXCEPTION);
if (StringUtils.isEmpty(login.getUsername()))
throw new ClientException(ErrorCode.API_EC_CLIENT_EXCEPTION);
if (StringUtils.isEmpty(login.getPassword()))
throw new ClientException(ErrorCode.API_EC_CLIENT_EXCEPTION);
LoginResultBean token = userService.login(login);
return ResponseBean.success(token);
}
3.编写Mock测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { LoginController.class, MockServletContext.class })
@EnableAutoConfiguration
@ComponentScan(basePackages= {“com.offcn.*”})
@WebAppConfiguration ##声明测试加载WebApplicationContext
public class LoginTest {
@Autowired
WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void SetUp(){
this.mockMvc= MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void login() throws Exception {
RequestBuilder request = null;
LoginVo loginVo=new LoginVo();
loginVo.setUsername(“admin”);
loginVo.setPassword(“admin”); ##构造请求体JSON格式
String LoginVoJson=JSONObject.toJSONString(loginVo);
request = MockMvcRequestBuilders.post(“/v1/login”)
.contentType(MediaType.APPLICATION_JSON)
.content(LoginVoJson);
String requestJson = mockMvc.perform(request).andDo(print())
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
System.out.println(requestJson);
}
}
这里注意一下,最开始看网上SetUp()方法中这样写,坑!:
mockMvc= MockMvcBuilders.standaloneSetup(new LoginController()).build();
然后没有WebApplicationContext属性
直接报空指针异常,这是由于接口测试需要全局上下文。。。。
4.启动测试类,显示测试通过
四.swagger
swgger可以不仅可以测试,还可以生成API接口文档
1.pom文件中加入如下依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2.加入@ApiOperation用于生成API文档信息
3.编写Swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Value(“${swagger.host}”)
private String swaggerHost;
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“swagger接口文档”)
.description(“基于shiro和jwt的前后端分离权限系统”)
.termsOfServiceUrl(“”)
.version(“v1”)
.contact(new Contact(“”, “”, “”))
.build();
}
@Bean
public Docket createRestApi() {
ParameterBuilder builder = new ParameterBuilder();
Parameter parameter = builder
// 从cookie中获取token
.parameterType(“cookie”) //参数类型支持header, cookie, body, query etc
.name(“token”) //参数名
.defaultValue(“”) //默认值
.description(“请输入token”)
.modelRef(new ModelRef(“string”)) //指定参数值的类型
.required(false).build(); //非必需,这里是全局配置,然而在登陆的时候是不用验证的
List<Parameter> parameters = Lists.newArrayList(parameter);
return new Docket(DocumentationType.SWAGGER_2)
.host(this.swaggerHost)
.select()
.apis(RequestHandlerSelectors.basePackage(“com.offcn.login.controller”))
.paths(PathSelectors.any())
.build()
.apiInfo(this.apiInfo())
.globalOperationParameters(parameters);
}
/**
* swagger ui资源映射
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“swagger-ui.html”)
.addResourceLocations(“classpath:/META-INF/resources/”);
registry.addResourceHandler(“/webjars*”)
.addResourceLocations(“classpath:/META-INF/resources/webjars/”);
}
/**
* swagger-ui.html路径映射,浏览器中使用/api-docs访问
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController(“/api-docs”,”/swagger-ui.html”);
}
}
4.启动项目,输入http://localhost:60000/swagger-ui.html 得到项目下所有接口信息
5.进行接口测试
得到响应: