1.侧栏菜单选择代码生成下的"Java":
点击代码区右上角的“代码魔法棒”图标,在弹出的确认面板中,可选择生成Quarkus风格代码或SpringBoot风格的代码,Grpc通讯是用于生成多微服务代码时的选项,此处不展开讲解。
2.一秒生成完整的Java项目工程代码,如下图所示:
下面摘出该项目工程中的订单相关代码。接口层代码如下:
package com.aigcoder.demo.api;
import com.aigcoder.demo.common.PageView;
import com.aigcoder.demo.common.ValidateUtils;
import com.aigcoder.demo.dto.SearchDTO;
import com.aigcoder.demo.dto.OrderCreateDTO;
import com.aigcoder.demo.dto.OrderModifyDTO;
import com.aigcoder.demo.domain.Order;
import com.aigcoder.demo.service.OrderService;
import com.aigcoder.demo.vo.OrderVO;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.enums.ParameterIn;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameters;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.jboss.logging.Logger;
/**
* 领域类 Order(订单) 的资源访问层
* @author 极客学院
* @date 2025/03/20
*/
@Path("/demo/order")
@Produces(MediaType.APPLICATION_JSON)
@Tag(name = "OrderResource", description = "领域类 Order(订单) 的资源访问层")
public class OrderResource {
private static final Logger LOGGER = Logger.getLogger(OrderResource.class);
@Inject
OrderService orderService;
/**
* 提交新增订单的请求
* POST: /demo/order/user/create
* @param dto 新增订单的表单校验DTO
* @return 反馈操作结果状态
*/
@POST
@Path("/user/create")
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@APIResponse(responseCode = "201", description = "操作成功")
@APIResponse(responseCode = "401", description = "您未通过身份认证或Token令牌已过期")
@APIResponse(responseCode = "422", description = "表单校验失败")
@Operation(summary = "提交新增订单的请求", description = "POST: /demo/order/user/create")
public Response create(OrderCreateDTO dto) {
ValidateUtils.check(dto, LOGGER);
orderService.create(dto);
return Response.status(201).build();
}
/**
* 提交修改订单的请求
* PUT: /demo/order/user/modify
* @param dto 修改订单的表单校验DTO
* @return 反馈操作结果状态
*/
@PUT
@Path("/user/modify")
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@APIResponse(responseCode = "200", description = "修改成功")
@APIResponse(responseCode = "401", description = "您未通过身份认证或Token令牌已过期")
@APIResponse(responseCode = "404", description = "未找到该数据")
@APIResponse(responseCode = "422", description = "表单校验失败")
@Operation(summary = "提交修改订单的请求", description = "PUT: /demo/order/user/modify")
public Response modify(OrderModifyDTO dto) {
ValidateUtils.check(dto, LOGGER);
orderService.modify(dto);
return Response.status(200).build();
}
/**
* 显示一条订单的信息详情
* GET: /demo/order/user/detail/{orderId}
* @param orderId 订单ID
* @return 显示一条订单的信息详情
*/
@GET
@Path("/user/detail/{orderId}")
@RolesAllowed("user")
@Parameters({
@Parameter(name = "orderId", description = "订单ID", example = "1", in = ParameterIn.PATH),
})
@APIResponse(responseCode = "200", description = "查询成功")
@APIResponse(responseCode = "401", description = "您未通过身份认证或Token令牌已过期")
@APIResponse(responseCode = "404", description = "未找到该数据")
@Operation(summary = "显示一条订单的信息详情", description = "GET: /demo/order/user/detail/{orderId}")
public Order detail(@PathParam("orderId") Long orderId) {
return orderService.detail(orderId);
}
/**
* 订单列表
* GET: /demo/order/user/list
* @param dto 搜索的DTO数据传输对象
* @return 订单列表
*/
@GET
@Path("/user/list")
@RolesAllowed("user")
@APIResponse(responseCode = "200", description = "查询成功")
@APIResponse(responseCode = "401", description = "您未通过身份认证或Token令牌已过期")
@Operation(summary = "订单列表", description = "GET: /demo/order/user/list")
public PageView<OrderVO> list(@BeanParam SearchDTO dto) {
return orderService.list(dto);
}
/**
* 删除一条订单信息(非物理删除)
* DELETE: /demo/order/user/remove/{orderId}
* @param orderId 订单ID
* @return 反馈操作结果状态
*/
@DELETE
@Path("/user/remove/{orderId}")
@RolesAllowed("user")
@Parameters({
@Parameter(name = "orderId", description = "订单ID", example = "1", in = ParameterIn.PATH),
})
@APIResponse(responseCode = "204", description = "删除成功")
@APIResponse(responseCode = "401", description = "您未通过身份认证或Token令牌已过期")
@APIResponse(responseCode = "404", description = "未找到该数据")
@Operation(summary = "删除一条订单信息(非物理删除)", description = "DELETE: /demo/order/user/remove/{orderId}")
public Response remove(@PathParam("orderId") Long orderId) {
orderService.remove(orderId);
return Response.status(204).build();
}
}
服务层代码:
package com.aigcoder.demo.service;
import cn.hutool.core.bean.BeanUtil;
import com.aigcoder.demo.common.PageView;
import com.aigcoder.demo.common.BusinessException;
import com.aigcoder.demo.common.ErrorCode;
import com.aigcoder.demo.domain.Order;
import com.aigcoder.demo.domain.User;
import com.aigcoder.demo.dto.SearchDTO;
import com.aigcoder.demo.dto.OrderCreateDTO;
import com.aigcoder.demo.dto.OrderModifyDTO;
import com.aigcoder.demo.vo.OrderVO;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.panache.common.Page;
import io.quarkus.panache.common.Parameters;
import io.quarkus.panache.common.Sort;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.WebApplicationException;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 资源类OrderResource的服务层
* @author 极客学院
* @date 2025/03/20
*/
@ApplicationScoped
public class OrderService {
private static final Logger LOGGER = Logger.getLogger(OrderService.class);
@Inject
UserService userService;
@Inject
RedisService redisService;
/**
* 提交新增订单的请求
* @param dto 新增订单的表单校验DTO
*/
@Transactional
public void create(OrderCreateDTO dto) {
Order order = new Order();
BeanUtil.copyProperties(dto, order);
User user = userService.getUserInfo();
order.creatorId = user.userId;
order.creator = user.nickname;
order.persist();
}
/**
* 提交修改订单的请求
* @param dto 修改订单的表单校验DTO
*/
@Transactional
public void modify(OrderModifyDTO dto) {
Order o = Order.findById(dto.orderId);
if(o == null){
String info = "订单不存在。ID:" + dto.orderId;
LOGGER.error(info);
throw new WebApplicationException(info, 404);
}
if(dto.orderNum !=null && !dto.orderNum.equals(o.orderNum)) {
o.orderNum = dto.orderNum;
}
if(dto.amount !=null && !dto.amount.equals(o.amount)) {
o.amount = dto.amount;
}
if(dto.memo !=null && !dto.memo.equals(o.memo)) {
o.memo = dto.memo;
}
User user = userService.getUserInfo();
o.lastModificationTime = new Date();
o.lastModifierId = user.userId;
o.lastModifier = user.nickname;
redisService.del("Order." + o.orderId);
}
/**
* 显示一条订单的信息详情
* @param orderId 订单ID
* @return 显示一条订单的信息详情
*/
public Order detail(Long orderId) {
Order o = redisService.get("Order." + orderId, Order.class);
if(o!=null){
return o;
}
o = Order.findById(orderId);
if(o==null){
String info = "订单不存在。ID:" + orderId;
LOGGER.error(info);
throw new WebApplicationException(info, 404);
}
redisService.set("Order." + o.orderId, o);
return o;
}
/**
* 订单列表
* @param dto 搜索的DTO数据传输对象
* @return 订单列表
*/
public PageView<OrderVO> list(SearchDTO dto) {
PanacheQuery<Order> orderPanacheQuery;
if(dto.keyword!=null){
String keyword = dto.keyword.trim();
orderPanacheQuery = Order.find("(orderNum like :orderNum or memo like :memo) and isDeleted = false",
(dto.sortBy==null ? Sort.by("orderId", Sort.Direction.Descending) : Sort.by(dto.sortBy)),
Parameters.with("orderNum", "%"+keyword+"%").and("memo", "%"+keyword+"%"));
}else{
orderPanacheQuery = Order.find("isDeleted = false",
(dto.sortBy==null ? Sort.by("orderId", Sort.Direction.Descending) : Sort.by(dto.sortBy)));
}
List<Order> list = orderPanacheQuery.page(Page.of(dto.page, dto.size)).list();
List<OrderVO> voList = new ArrayList<>();
for (Order order:
list) {
OrderVO orderVO = new OrderVO();
BeanUtil.copyProperties(order, orderVO);
voList.add(orderVO);
}
PageView<OrderVO> pageView = new PageView<>();
pageView.list = voList;
pageView.total = orderPanacheQuery.count();
return pageView;
}
/**
* 删除一条订单信息(非物理删除)
* @param orderId 订单ID
*/
@Transactional
public void remove(Long orderId) {
Order o = Order.findById(orderId);
if(o == null){
String info = "订单不存在。ID:" + orderId;
LOGGER.error(info);
throw new WebApplicationException(info, 404);
}
User user = userService.getUserInfo();
o.isDeleted = true;
o.deletionTime = new Date();
o.deleterId = user.userId;
o.deleter = user.nickname;
redisService.del("Order." + o.orderId);
}
}
领域类层代码:
package com.aigcoder.demo.domain;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import jakarta.persistence.*;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.hibernate.annotations.DynamicUpdate;
import java.util.Date;
/**
* 订单领域类
* @author 极客学院
* @date 2025/03/20
*/
@Entity
@DynamicUpdate()
@Table(name = "tbl_order")
@Schema(description = "订单")
public class Order extends PanacheEntityBase {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@Schema(description = "订单ID", example = "1")
public Long orderId;
@Column(nullable = false, name = "order_num", length = 50)
@Schema(description = "订单号", example = "4624849630")
public String orderNum;
@Column(nullable = false, name = "amount")
@Schema(description = "订单金额", example = "80.16")
public BigDecimal amount;
@Column(nullable = false, name = "memo", length = 50)
@Schema(description = "订单描述", example = "请加急发货急用。")
public String memo;
@Column(nullable = false, name = "creation_time", updatable = false)
@Schema(description = "创建时间", example = "2025-03-20 10:18:18")
public Date creationTime = new Date();
@Column(nullable = false, name = "creator_id", updatable = false)
@Schema(description = "创建者ID", example = "1")
public Long creatorId;
@Column(nullable = false, name = "creator", updatable = false)
@Schema(description = "创建者", example = "AI极客")
public String creator;
@Column(name = "last_modification_time")
@Schema(description = "最近修改时间", example = "2025-03-20 10:28:28")
public Date lastModificationTime;
@Column(name = "last_modifier_id")
@Schema(description = "最近修改者ID", example = "1")
public Long lastModifierId;
@Column(name = "last_modifier")
@Schema(description = "最近修改者", example = "AI极客")
public String lastModifier;
@Column(nullable = false, name = "is_deleted")
@Schema(description = "已删除", example = "true")
public Boolean isDeleted = false;
@Column(name = "deletion_time")
@Schema(description = "删除时间", example = "2025-03-20 10:38:38")
public Date deletionTime;
@Column(name = "deleter_id")
@Schema(description = "删除者ID", example = "1")
public Long deleterId;
@Column(name = "deleter")
@Schema(description = "删除者", example = "AI极客")
public String deleter;
/**
* 空构造函数
*/
public Order(){
super();
}
/**
*带参构造函数
*/
public Order(String orderNum, BigDecimal amount, String memo, Date creationTime, Long creatorId, String creator, Date lastModificationTime, Long lastModifierId, String lastModifier, Boolean isDeleted, Date deletionTime, Long deleterId, String deleter){
super();
this.orderNum = orderNum;
this.amount = amount;
this.memo = memo;
this.creationTime = creationTime;
this.creatorId = creatorId;
this.creator = creator;
this.lastModificationTime = lastModificationTime;
this.lastModifierId = lastModifierId;
this.lastModifier = lastModifier;
this.isDeleted = isDeleted;
this.deleterId = deleterId;
this.deletionTime = deletionTime;
this.deleter = deleter;
}
}
DTO类代码:
package com.aigcoder.demo.dto;
import jakarta.validation.constraints.*;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
/**
* 新增订单的表单校验DTO
* @author 极客学院
* @date 2025/03/20
*/
@Schema(description = "新增订单的表单校验DTO")
public class OrderCreateDTO {
@NotBlank(message = "订单号:不能为空")
@Length(max = 50, message = "订单号:最长不能超过50个字符")
@Schema(description = "订单号:不能为空,最长不能超过50个字符", required = true, example = "4624849630")
public String orderNum;
@NotNull(message = "订单金额:不能为null")
@DecimalMin(value = "0.00", message = "订单金额:必须大于或等于0.00")
@DecimalMax(value = "100.00", message = "订单金额:必须小于或等于100.00")
@Digits(integer = 10, fraction = 2, message = "订单金额:数字的值超出了允许范围(只允许在10位整数和2位小数范围内)")
@Schema(description = "订单金额:不能为null,必须大于或等于0.00,必须小于或等于100.00,数字的值只允许在10位整数和2位小数范围内", required = true, example = "80.16")
public BigDecimal amount;
@NotBlank(message = "订单描述:不能为空")
@Length(max = 50, message = "订单描述:最长不能超过50个字符")
@Schema(description = "订单描述:不能为空,最长不能超过50个字符", required = true, example = "请加急发货急用。")
public String memo;
}
package com.aigcoder.demo.dto;
import jakarta.validation.constraints.*;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
/**
* 修改订单的表单校验DTO
* @author 极客学院
* @date 2025/03/20
*/
@Schema(description = "修改订单的表单校验DTO")
public class OrderModifyDTO {
@NotNull(message = "订单ID:不能为null")
@Min(value = 1, message = "订单ID:最小不能小于1")
@Schema(description = "订单ID:不能为null,最小不能小于1", required = true, example = "1")
public Long orderId;
@NotBlank(message = "订单号:不能为空")
@Length(max = 50, message = "订单号:最长不能超过50个字符")
@Schema(description = "订单号:不能为空,最长不能超过50个字符", required = true, example = "4624849630")
public String orderNum;
@NotNull(message = "订单金额:不能为null")
@DecimalMin(value = "0.00", message = "订单金额:必须大于或等于0.00")
@DecimalMax(value = "100.00", message = "订单金额:必须小于或等于100.00")
@Digits(integer = 10, fraction = 2, message = "订单金额:数字的值超出了允许范围(只允许在10位整数和2位小数范围内)")
@Schema(description = "订单金额:不能为null,必须大于或等于0.00,必须小于或等于100.00,数字的值只允许在10位整数和2位小数范围内", required = true, example = "80.16")
public BigDecimal amount;
@NotBlank(message = "订单描述:不能为空")
@Length(max = 50, message = "订单描述:最长不能超过50个字符")
@Schema(description = "订单描述:不能为空,最长不能超过50个字符", required = true, example = "请加急发货急用。")
public String memo;
}
VO类代码:
package com.aigcoder.demo.vo;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
/**
* 订单信息实体
* @author 极客学院
* @date 2025/03/20
*/
@Schema(description = "订单信息实体")
public class OrderVO {
@Schema(description = "订单ID", example = "1")
public Long orderId;
@Schema(description = "订单号", example = "4624849630")
public String orderNum;
@Schema(description = "订单金额", example = "80.16")
public BigDecimal amount;
@Schema(description = "订单描述", example = "请加急发货急用。")
public String memo;
}
订单类自动测试代码:
package com.aigcoder.demo;
import io.quarkus.test.junit.QuarkusTest;
import jdk.jfr.Description;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.*;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.JSON;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
/**
* API资源(OrderResource)的接口测试
* @author 极客学院
* @date 2025/03/20
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class OrderResourceTest {
@ConfigProperty(name = "api_gateway")
String API_GATEWAY;
@Inject
TokenUtils tokenUtils;
ExpectedDTO expectedDTO;
List<ExpectedDTO> expectedDTOS;
HashMap<String, String> map;
static List<HashMap<String, String>> list;
static String access_token = "";
/**
* 测试预备数据
*/
public void setPrepareData(){
}
@Test
@Description("测试:提交新增订单的请求")
@DisplayName("测试:提交新增订单的请求")
@Order(1)
public void testCreate() {
if(access_token.isEmpty()){
access_token = tokenUtils.getAccessToken();
}
// 创建测试预备数据
this.setPrepareData();
/*
* =================== 合法用例 ===================
*/
list = new ArrayList<>();
// 合法用例
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
list.add(map);
// 合法用例
map = new HashMap<>();
map.put("orderNum", "1454638995");
map.put("amount", "88.75");
map.put("memo", "玉依合役况岔节句呈彻状刮许治苏。母建拥怜购寿园极诗针侧纱吩乒召府纤。帆货泼坝制存陆希吓厌帘自。权自奉异驳阿求房岸丧炊务仰邻奔冬左呜治。抹享宏贪败吃齐北肃迁爸。团呈泼冲更戏斥明层由的伞。");
list.add(map);
// 合法用例
map = new HashMap<>();
map.put("orderNum", "2151384176");
map.put("amount", "2.82");
map.put("memo", "姐肯织导正屈拢私因抗图臣。市员局店吐妹杀台券刘乓民迟。所命技现灶际围皮驼过打加者刻他抢。阶国妙龙坡启诉匠厌角圣畅。伯本围同迎厉丢压争羊乎份呈抓卵步汪极灰册。");
list.add(map);
for (int i = 0; i < list.size(); i++) {
given().
contentType(JSON).
body(list.get(i)).
header("Authorization", "Bearer " + access_token).
when().
//log().all().
post(API_GATEWAY + "/demo/order/user/create").
then().
log().all().
statusCode(201);
}
/*
* =================== 非法用例(数据校验不合格) ===================
*/
expectedDTOS = new ArrayList<>();
// 订单号:不能为空 [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单号:不能为空";
expectedDTOS.add(expectedDTO);
// 订单号:最长不能超过50个字符 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "qgdmdfydffnyfhnnmfajyigrnqutpkeshkeaxblpmwhqqkpwqnt");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单号:最长不能超过50个字符";
expectedDTOS.add(expectedDTO);
// 订单金额:不能为null [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:不能为null";
expectedDTOS.add(expectedDTO);
// 订单金额:必须大于或等于0.00 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "-1.0");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:必须大于或等于0.00";
expectedDTOS.add(expectedDTO);
// 订单金额:必须小于或等于100.00 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "101.0");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:必须小于或等于100.00";
expectedDTOS.add(expectedDTO);
// 订单金额:数字的值超出了允许范围(只允许在10位整数和2位小数范围内) [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "10000000000.00");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:数字的值超出了允许范围(只允许在10位整数和2位小数范围内)";
expectedDTOS.add(expectedDTO);
// 订单描述:不能为空 [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单描述:不能为空";
expectedDTOS.add(expectedDTO);
// 订单描述:最长不能超过50个字符 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "hsglmzxvippqgthsggomgqvdeawiouzttdqotedmfuhgvdssodf");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单描述:最长不能超过50个字符";
expectedDTOS.add(expectedDTO);
for (ExpectedDTO item:
expectedDTOS) {
given().
contentType(JSON).
body(item.jsonParam).
header("Authorization", "Bearer " + access_token).
when().
//log().all().
post(API_GATEWAY + "/demo/order/user/create").
then().
log().all().
statusCode(422).
body(containsString(item.expected));
}
/*
* =================== 非法用例(业务错误) ===================
*/
// 非法用例:您未通过身份认证或Token令牌已过期
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
given().
contentType(JSON).
body(map).
header("Authorization","Bearer " + access_token + "error").
when().
//log().all().
post(API_GATEWAY + "/demo/order/user/create").
then().
log().all().
statusCode(401);
}
@Test
@Description("测试:订单列表")
@DisplayName("测试:订单列表")
@Order(2)
public void testList() {
if(access_token.isEmpty()){
access_token = tokenUtils.getAccessToken();
}
// 合法用例:自然搜索
map = new HashMap<>();
given().
queryParams(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
get(API_GATEWAY + "/demo/order/user/list").
then().
log().all().
statusCode(200).
body("total", is(3));
// 合法用例:关键字搜索
map = new HashMap<>();
map.put("keyword", "");
map.put("page", "0");
map.put("size", "10");
map.put("sortBy", "orderId");
given().
queryParams(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
get(API_GATEWAY + "/demo/order/user/list").
then().
log().all().
statusCode(200).
body("total", is(3));
// 非法用例:您未通过身份认证或Token令牌已过期
map = new HashMap<>();
given().
queryParams(map).
header("Authorization","Bearer " + access_token + "error").
when().
//log().all().
get(API_GATEWAY + "/demo/order/user/list").
then().
log().all().
statusCode(401);
}
@Test
@Description("测试:显示一条订单的信息详情")
@DisplayName("测试:显示一条订单的信息详情")
@Order(3)
public void testDetail() {
if(access_token.isEmpty()){
access_token = tokenUtils.getAccessToken();
}
// 合法用例
map = new HashMap<>();
given().
pathParam("orderId", "1").
queryParams(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
get(API_GATEWAY + "/demo/order/user/detail/{orderId}").
then().
log().all().
statusCode(200);
// 非法用例:您未通过身份认证或Token令牌已过期
map = new HashMap<>();
given().
pathParam("orderId", "1").
queryParams(map).
header("Authorization","Bearer " + access_token + "error").
when().
//log().all().
get(API_GATEWAY + "/demo/order/user/detail/{orderId}").
then().
log().all().
statusCode(401);
// 非法用例:404错误,未找到该数据
map = new HashMap<>();
given().
// TODO 修正参数值
pathParam("orderId", "100").
queryParams(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
get(API_GATEWAY + "/demo/order/user/detail/{orderId}").
then().
log().all().
statusCode(404);
}
@Test
@Description("测试:提交修改订单的请求")
@DisplayName("测试:提交修改订单的请求")
@Order(4)
public void testModify() {
if(access_token.isEmpty()){
access_token = tokenUtils.getAccessToken();
}
/*
* =================== 合法用例 ===================
*/
// 合法用例
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
given().
contentType(JSON).
body(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
put(API_GATEWAY + "/demo/order/user/modify").
then().
log().all().
statusCode(200);
/*
* =================== 非法用例(数据校验不合格) ===================
*/
expectedDTOS = new ArrayList<>();
// 订单ID:不能为null [非法值:主键ID故意不传参]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单ID:不能为null";
expectedDTOS.add(expectedDTO);
// 订单ID:最小不能小于1 [非法边界值,低于允许的最小值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "0");
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单ID:最小不能小于1";
expectedDTOS.add(expectedDTO);
// 订单号:不能为空 [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单号:不能为空";
expectedDTOS.add(expectedDTO);
// 订单号:最长不能超过50个字符 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "tkrkpvyxdylexcpaamzzjymmrbtjootzlnjrhnoqkbkxdgnqusi");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单号:最长不能超过50个字符";
expectedDTOS.add(expectedDTO);
// 订单金额:不能为null [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:不能为null";
expectedDTOS.add(expectedDTO);
// 订单金额:必须大于或等于0.00 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "-1.0");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:必须大于或等于0.00";
expectedDTOS.add(expectedDTO);
// 订单金额:必须小于或等于100.00 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "101.0");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:必须小于或等于100.00";
expectedDTOS.add(expectedDTO);
// 订单金额:数字的值超出了允许范围(只允许在10位整数和2位小数范围内) [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "10000000000.00");
map.put("memo", "请加急发货急用。");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单金额:数字的值超出了允许范围(只允许在10位整数和2位小数范围内)";
expectedDTOS.add(expectedDTO);
// 订单描述:不能为空 [非法值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单描述:不能为空";
expectedDTOS.add(expectedDTO);
// 订单描述:最长不能超过50个字符 [非法边界值]
expectedDTO = new ExpectedDTO();
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "txnmunhpmnhtvoyfeebxjnncnvmuvbpmrjzqoanaigvtjjsvzwo");
expectedDTO.jsonParam = map;
expectedDTO.expected = "订单描述:最长不能超过50个字符";
expectedDTOS.add(expectedDTO);
for (ExpectedDTO item:
expectedDTOS) {
given().
contentType(JSON).
body(item.jsonParam).
header("Authorization", "Bearer " + access_token).
when().
//log().all().
put(API_GATEWAY + "/demo/order/user/modify").
then().
log().all().
statusCode(422).
body(containsString(item.expected));
}
/*
* =================== 非法用例(业务错误) ===================
*/
// 非法用例:您未通过身份认证或Token令牌已过期
map = new HashMap<>();
map.put("orderId", "1");
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
given().
contentType(JSON).
body(map).
header("Authorization","Bearer " + access_token + "error").
when().
//log().all().
put(API_GATEWAY + "/demo/order/user/modify").
then().
log().all().
statusCode(401);
// 非法用例:404错误,未找到该数据
map = new HashMap<>();
map.put("orderId", "100");
map.put("orderNum", "4624849630");
map.put("amount", "80.16");
map.put("memo", "请加急发货急用。");
given().
contentType(JSON).
body(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
put(API_GATEWAY + "/demo/order/user/modify").
then().
log().all().
statusCode(404);
}
@Test
@Description("测试:删除一条订单信息(非物理删除)")
@DisplayName("测试:删除一条订单信息(非物理删除)")
@Order(5)
public void testRemove() {
if(access_token.isEmpty()){
access_token = tokenUtils.getAccessToken();
}
// 非法用例:您未通过身份认证或Token令牌已过期
map = new HashMap<>();
given().
pathParam("orderId", "1").
queryParams(map).
header("Authorization","Bearer " + access_token + "error").
when().
//log().all().
delete(API_GATEWAY + "/demo/order/user/remove/{orderId}").
then().
log().all().
statusCode(401);
// 非法用例:404错误,未找到该数据
map = new HashMap<>();
given().
// TODO 修正参数值
pathParam("orderId", "100").
queryParams(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
delete(API_GATEWAY + "/demo/order/user/remove/{orderId}").
then().
log().all().
statusCode(404);
// 合法用例:删除成功
map = new HashMap<>();
given().
pathParam("orderId", "1").
queryParams(map).
header("Authorization","Bearer " + access_token).
when().
//log().all().
delete(API_GATEWAY + "/demo/order/user/remove/{orderId}").
then().
log().all().
statusCode(204);
}
}
详细操作可去官网免费体验!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。