2.4 快速生成Quarkus微服务代码 原创

鸿蒙开发之南拳北腿
发布于 2023-8-11 18:47
浏览
0收藏

本节内容概要:
1.生成Quarkus微服务代码;
2.在线预览代码;
3.下载项目代码。

经过前两节的步骤,快速创建项目、微服务和领域类设计后,就可以1秒钟快速生成整个Quarkus微服务代码了。

1.生成Quarkus微服务代码

在码农网工作台的左侧栏菜单中选择“后端代码”下的“Quarkus”菜单,点击“生成微服务代码”按钮,如下图所示:
2.4 快速生成Quarkus微服务代码-鸿蒙开发者社区

2.在线预览代码

现在我们可以在类IDEA的风格体验中预览代码了。根据需要,展开代码目录,选择要预览的代码文件,预览面板就能查看该代码内容了,如下图所示:
2.4 快速生成Quarkus微服务代码-鸿蒙开发者社区
预览面板右上角可以删除、修改和复制该代码:
2.4 快速生成Quarkus微服务代码-鸿蒙开发者社区
现在我们体验下上一节我们花5分钟设计的领域类,能生成怎样的Quarkus代码。

1>.领域类代码

package com.bamasmiles.goods.domain;

import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.persistence.*;
import javax.validation.constraints.*;
import java.util.Date;

/**
 * Product(商品信息) 的领域层
 * @author 码农云创
 * @date 2023/08/11
 */
@Entity
@DynamicUpdate()
@Table(name="tbl_product")
@Cacheable
public class Product extends PanacheEntityBase {

    public interface CheckCreate{}
    public interface CheckModify{}

    /**
     * 商品信息ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Null(groups={CheckCreate.class})
    @NotNull(groups={CheckModify.class})
    @Min(value=1, groups={CheckModify.class})
    @Column(name = "id")
    public Long productId;

    /**
     * 商品名称
     */
    @NotBlank(groups={CheckCreate.class, CheckModify.class})
    @Length(max=50, groups={CheckCreate.class, CheckModify.class})
    @Column(nullable = false, name = "name", length =50)
    public String name;

    /**
     * 数量
     */
    @NotNull(groups={CheckCreate.class, CheckModify.class})
    @Min(value=1, groups={CheckCreate.class, CheckModify.class})
    @Max(value=10000, groups={CheckCreate.class, CheckModify.class})
    @Column(nullable = false, name = "quantity")
    public Integer quantity;

    /**
     * 商品价格
     */
    @NotNull(groups={CheckCreate.class, CheckModify.class})
    @DecimalMin(value="0.00", groups={CheckCreate.class, CheckModify.class})
    @DecimalMax(value="100.00", groups={CheckCreate.class, CheckModify.class})
    @Digits(integer=10, fraction=2, groups={CheckCreate.class, CheckModify.class})
    @Column(nullable = false, name = "price")
    public Double price;

    /**
     * 创建时间
     */
    @Column(nullable = false, name = "creation_time", updatable=false)
    public Date creationTime = new Date();

    /**
     * 创建者ID
     */
    @Column(nullable = false, name = "creator_id", updatable=false)
    public Long creatorId;

    /**
     * 创建者
     */
    @Column(nullable = false, name = "creator", updatable=false)
    public String creator;

    /**
     * 最近修改时间
     */
    @Column(name = "last_modification_time")
    public Date lastModificationTime;

    /**
     * 最近修改者ID
     */
    @Column(name = "last_modifier_id")
    public Long lastModifierId;

    /**
     * 最近修改者
     */
    @Column(name = "last_modifier")
    public String lastModifier;

    /**
     * 已删除
     */
    @Column(nullable = false, name = "is_deleted")
    public Boolean isDeleted = false;

    /**
     * 删除时间
     */
    @Column(name = "deletion_time")
    public Date deletionTime;

    /**
     * 删除者ID
     */
    @Column(name = "deleter_id")
    public Long deleterId;

    /**
     * 删除者
     */
    @Column(name = "deleter")
    public String deleter;

    /**
     * 空构造函数
     */
    public Product(){
        super();
    }

    /**
     *带参构造函数
     */
    public Product(String name, Integer quantity, Double price, Date creationTime, Long creatorId, String creator, Date lastModificationTime, Long lastModifierId, String lastModifier, Boolean isDeleted, Date deletionTime, Long deleterId, String deleter){
        super();
        this.name = name;
        this.quantity = quantity;
        this.price = price;
        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;
    }

}

2>.服务层代码

package com.bamasmiles.goods.service;

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 io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.string.StringCommands;
import org.jboss.logging.Logger;
import com.bamasmiles.goods.common.BusinessException;;
import com.bamasmiles.goods.common.ErrorCode;;
import com.bamasmiles.goods.common.I18nUtils;;
import com.bamasmiles.goods.domain.Product;
import com.bamasmiles.goods.dto.SearchDTO;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.transaction.SystemException;
import javax.transaction.Transactional;
import javax.ws.rs.WebApplicationException;
import java.util.*;

/**
 * 领域类 Product(商品信息) 的服务层
 * @author 码农云创
 * @date 2023/08/11
 */
@ApplicationScoped
public class ProductService {
    private static final Logger LOGGER = Logger.getLogger(ProductService.class.getName());

    @Inject
    UserService userService;

    private final StringCommands<String, Product> redisClient;

    public ProductService(RedisDataSource ds) {
        this.redisClient = ds.string(Product.class);
    }

    /**
     * 保存数据
     * @param product 商品信息
     * @return 返回Product实体
     * @throws SystemException
     */
    @Transactional
    public Product save(Product product) throws SystemException {

        Map<String, Object> map = userService.getUserInfo();
        Long userId = Long.valueOf(map.get("userId").toString());
        String nickname = map.get("nickname").toString();

        if(product.productId==null){
            product.creatorId = userId;
            product.creator = nickname;

            product.persist();

            redisClient.set("Product." + product.productId, product);
            return product;
        }else{
            Product p = Product.findById(product.productId);

            if(product.name !=null && !product.name.equals(p.name)) {
                p.name = product.name;
            }

            if(product.quantity !=null && !product.quantity.equals(p.quantity)) {
                p.quantity = product.quantity;
            }

            if(product.price !=null && !product.price.equals(p.price)) {
                p.price = product.price;
            }

            p.lastModificationTime = new Date();
            p.lastModifierId = userId;
            p.lastModifier = nickname;

            if(redisClient.get("Product." + p.productId)!=null) {
                redisClient.getdel("Product." + p.productId);
            }
            redisClient.set("Product." + p.productId, p);
            return p;
        }
    }

    /**
     * 查找符合条件的一条数据
     * @param productId 商品信息ID
     * @return 返回Product实体
     * @throws SystemException
     */
    public Product findOne(Long productId) throws SystemException {
        Product p = redisClient.get("Product." + productId);
        if(p!=null){
            return p;
        }
        p = Product.findById(productId);
        if(p==null){
            String info  = I18nUtils.getMessage("TableName.product") + I18nUtils.getMessage("Data.NotExist") + productId;
            LOGGER.info(info);
            throw new WebApplicationException(info, 404);
        }

        redisClient.set("Product." + p.productId, p);
        return p;
    }

    /**
     * 查找符合条件的数据列表
     * @param dto 查询条件DTO
     * @return 返回支持排序和翻页的数据列表
     * @throws SystemException
     */
    public Map<String, Object> get(SearchDTO dto) throws SystemException {
        Map<String, Object> map = new HashMap();
        PanacheQuery<Product> productPanacheQuery;

        if(dto.keyword!=null){
            String keyword = dto.keyword.trim();
            productPanacheQuery = Product.find("(name like :name) and isDeleted=false",
                    (dto.sortBy==null ? Sort.by("productId desc") : Sort.by(dto.sortBy)),
                    Parameters.with("name", "%"+keyword+"%"));
        }else{
            productPanacheQuery = Product.findAll(dto.sortBy==null ? Sort.by("productId desc") : Sort.by(dto.sortBy));
        }

        List<Product> list = productPanacheQuery.page(Page.of(dto.page, dto.size)).list();
        map.put("list", list);
        map.put("total", productPanacheQuery.count());
        return map;
    }

    /**
     * 根据主键id删除一条数据记录(非物理删除)
     * @param productId 商品信息ID
     * @throws SystemException
     */
    @Transactional
    public void delete(Long productId) throws SystemException {
        Map<String, Object> map = userService.getUserInfo();
        Long userId = Long.valueOf(map.get("userId").toString());
        String nickname = map.get("nickname").toString();

        Product product = Product.findById(productId);

        product.isDeleted = true;
        product.deletionTime = new Date();
        product.deleterId = userId;
        product.deleter = nickname;

        if(redisClient.get("Product." + productId)!=null) {
            redisClient.getdel("Product." + productId);
        }
    }

}

3>.资源类代码

package com.bamasmiles.goods.api;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import org.jboss.logging.Logger;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import com.bamasmiles.goods.common.I18nUtils;
import com.bamasmiles.goods.dto.SearchDTO;
import com.bamasmiles.goods.domain.Product;
import com.bamasmiles.goods.service.ProductService;

import javax.inject.Inject;
import javax.transaction.SystemException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 领域类 Product(商品信息) 的资源访问层
 * @author 码农云创
 * @date 2023/08/11
 */
@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ProductResource {
    private static final Logger LOGGER = Logger.getLogger(ProductResource.class.getName());

    @Inject
    ProductService productService;

    @Inject
    Validator validator;

    /**
     * 提交新增商品信息的请求
     * POST: /api/admin/product/create
     * @param product
     * @return
     * @throws SystemException
     */
    @POST
    @Path("/admin/product/create")
    @RolesAllowed("admin")
    public Response create(Product product) throws SystemException {
        Set<ConstraintViolation<Product>> validate = validator.validate(product, Product.CheckCreate.class);
        if (validate.isEmpty()) {
            Product p = productService.save(product);
            return Response.ok(p).status(201).build();
        } else {
            String violations = validate.stream().map(violation -> I18nUtils.getMessage("FieldName.product." + violation.getPropertyPath().toString()) + ":" + violation.getMessage())
                    .collect(Collectors.joining(";"));
            LOGGER.info(violations);
            throw new WebApplicationException(violations, 422);
        }
    }

    /**
     * 提交修改商品信息的请求
     * PUT: /api/admin/product/modify
     * @param product
     * @return
     * @throws SystemException
     */
    @PUT
    @Path("/admin/product/modify")
    @RolesAllowed("admin")
    public Response modify(Product product) throws SystemException {
        Set<ConstraintViolation<Product>> validate = validator.validate(product, Product.CheckModify.class);
        if (validate.isEmpty()) {
            Product p = productService.save(product);
            return Response.ok(p).status(200).build();
        } else {
            String violations = validate.stream().map(violation -> I18nUtils.getMessage("FieldName.product." + violation.getPropertyPath().toString()) + ":" + violation.getMessage())
                    .collect(Collectors.joining(";"));
            LOGGER.info(violations);
            throw new WebApplicationException(violations, 422);
        }
    }

    /**
     * 显示一条商品信息的信息详情
     * GET: /api/admin/product/detail/{productId}
     * @param productId
     * @return
     * @throws SystemException
     */
    @GET
    @Path("/admin/product/detail/{productId}")
    @RolesAllowed("admin")
    public Product detail(@PathParam("productId") Long productId) throws SystemException {
        return productService.findOne(productId);
    }

    /**
     * 商品信息列表
     * GET: /api/admin/product/list
     * @param dto
     * @return
     * @throws SystemException
     */
    @GET
    @Path("/admin/product/list")
    @RolesAllowed("admin")
    public Map<String, Object> list(@BeanParam SearchDTO dto) throws SystemException {
        return productService.get(dto);
    }

    /**
     * 删除一条商品信息信息(非物理删除)
     * DELETE: /api/admin/product/delete/{productId}
     * @param productId
     * @return
     * @throws SystemException
     */
    @DELETE
    @Path("/admin/product/delete/{productId}")
    @RolesAllowed("admin")
    public Response delete(@PathParam("productId") Long productId) throws SystemException {
        productService.delete(productId);
        return Response.status(204).build();
    }

}

4>.单元测试代码

package com.bamasmiles.goods;

import io.quarkus.test.junit.QuarkusTest;
import jdk.jfr.Description;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.*;

import javax.inject.Inject;
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资源(ProductResource)的接口测试
 * @author 码农云创
 * @date 2023/08/11
 */
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ProductResourceTest {

    @ConfigProperty(name = "api_gateway")
    String API_GATEWAY;

    @Inject
    TokenUtils tokenUtils;

    ExpectedDTO expectedDTO;
    List<ExpectedDTO> expectedDTOS;
    HashMap map;
    static List<HashMap> 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("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "2167.15");
        map.put("quantity", "9530");
        list.add(map);

        // 合法用例
        map = new HashMap();
        map.put("name", "试社设还迈呢伶线纽汁详固屈肯治狐灶");
        map.put("price", "6325.55");
        map.put("quantity", "8183");
        list.add(map);

        // 合法用例
        map = new HashMap();
        map.put("name", "邻坝式财庆服底尖朽汤");
        map.put("price", "1822.17");
        map.put("quantity", "3420");
        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 + "/api/admin/product/create").
            then().
                    log().all().
                    statusCode(201);
        }

        /**
         * =================== 非法用例(数据校验不合格) ===================
         */
        expectedDTOS = new ArrayList<>();

        // 商品信息ID:必须为null [非法值:主键ID故意传参]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "0");
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "2167.15");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品信息ID:必须为null";
        expectedDTOS.add(expectedDTO);

        // 商品名称:不能为空 [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "");
        map.put("price", "2167.15");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品名称:不能为空";
        expectedDTOS.add(expectedDTO);

        // 商品名称:长度需要在0和50之间 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "eibretelihkkubzjcpfydywwgedqapxzkhudjyfqbhsnztcjors");
        map.put("price", "2167.15");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品名称:长度需要在0和50之间";
        expectedDTOS.add(expectedDTO);

        // 商品价格:不能为null [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:不能为null";
        expectedDTOS.add(expectedDTO);

        // 商品价格:必须大于或等于0.00 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "-1.0");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:必须大于或等于0.00";
        expectedDTOS.add(expectedDTO);

        // 商品价格:必须小于或等于100.00 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "101.0");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:必须小于或等于100.00";
        expectedDTOS.add(expectedDTO);

        // 商品价格:数字的值超出了允许范围(只允许在10位整数和2位小数范围内) [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "10000000000.00");
        map.put("quantity", "9530");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:数字的值超出了允许范围(只允许在10位整数和2位小数范围内)";
        expectedDTOS.add(expectedDTO);

        // 数量:不能为null [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "2167.15");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "数量:不能为null";
        expectedDTOS.add(expectedDTO);

        // 数量:最小不能小于1 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "2167.15");
        map.put("quantity", "0");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "数量:最小不能小于1";
        expectedDTOS.add(expectedDTO);

        // 数量:最大不能超过10000 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "君东君乖垂岂软龙帘畅");
        map.put("price", "2167.15");
        map.put("quantity", "10001");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "数量:最大不能超过10000";
        expectedDTOS.add(expectedDTO);

        for (ExpectedDTO item:
                expectedDTOS) {
            given().
                    contentType(JSON).
                    body(item.jsonParam).
                    header("Authorization", "Bearer " + access_token).
            when().
                    //log().all().
                    post(API_GATEWAY + "/api/admin/product/create").
            then().
                    log().all().
                    statusCode(422).
                    body(containsString(item.expected));
        }
    }

    /**
     * 商品信息列表-测试用例
     */
    @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 + "/api/admin/product/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", "productId desc");
        given().
                queryParams(map).
                header("Authorization","Bearer " + access_token).
        when().
                //log().all().
                get(API_GATEWAY + "/api/admin/product/list").
        then().
                log().all().
                statusCode(200).
                body("total", is(3));

    }

    /**
     * 显示一条商品信息的信息详情-测试用例
     */
    @Test
    @Description("测试:显示一条商品信息的信息详情")
    @DisplayName("测试:显示一条商品信息的信息详情")
    @Order(3)
    public void testDetail() {
        if(access_token.isEmpty()){
            access_token = tokenUtils.getAccessToken();
        }

        // 合法用例
        map = new HashMap();

        given().
                pathParam("productId", "1").
                contentType(JSON).
                body(map).
                header("Authorization","Bearer " + access_token).
        when().
                //log().all().
                get(API_GATEWAY + "/api/admin/product/detail/{productId}").
        then().
                log().all().
                statusCode(200);

        // 非法用例:未找到该资源
        map = new HashMap();

        given().
                pathParam("productId", "100").
                contentType(JSON).
                body(map).
                header("Authorization", "Bearer " + access_token).
        when().
                //log().all().
                get(API_GATEWAY + "/api/admin/product/detail/{productId}").
        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("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "8668.09");
        map.put("quantity", "5728");

        given().
                contentType(JSON).
                body(map).
                header("Authorization","Bearer " + access_token).
        when().
                //log().all().
                put(API_GATEWAY + "/api/admin/product/modify").
        then().
                log().all().
                statusCode(200);

        /**
         * =================== 非法用例(数据校验不合格) ===================
         */
        expectedDTOS = new ArrayList<>();

        // 商品信息ID:不能为null [非法值:主键ID故意不传参]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "8668.09");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品信息ID:不能为null";
        expectedDTOS.add(expectedDTO);

        // 商品信息ID:最小不能小于1 [非法边界值,低于允许的最小值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "0");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "8668.09");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品信息ID:最小不能小于1";
        expectedDTOS.add(expectedDTO);

        // 商品名称:不能为空 [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "");
        map.put("price", "8668.09");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品名称:不能为空";
        expectedDTOS.add(expectedDTO);

        // 商品名称:长度需要在0和50之间 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "ivtbknbhbnqjaexlrrsoaoysyedbyaqxtwgofelxmnflgssnfhu");
        map.put("price", "8668.09");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品名称:长度需要在0和50之间";
        expectedDTOS.add(expectedDTO);

        // 商品价格:不能为null [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:不能为null";
        expectedDTOS.add(expectedDTO);

        // 商品价格:必须大于或等于0.00 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "-1.0");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:必须大于或等于0.00";
        expectedDTOS.add(expectedDTO);

        // 商品价格:必须小于或等于100.00 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "101.0");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:必须小于或等于100.00";
        expectedDTOS.add(expectedDTO);

        // 商品价格:数字的值超出了允许范围(只允许在10位整数和2位小数范围内) [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "10000000000.00");
        map.put("quantity", "5728");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "商品价格:数字的值超出了允许范围(只允许在10位整数和2位小数范围内)";
        expectedDTOS.add(expectedDTO);

        // 数量:不能为null [非法值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "8668.09");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "数量:不能为null";
        expectedDTOS.add(expectedDTO);

        // 数量:最小不能小于1 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "8668.09");
        map.put("quantity", "0");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "数量:最小不能小于1";
        expectedDTOS.add(expectedDTO);

        // 数量:最大不能超过10000 [非法边界值]
        expectedDTO = new ExpectedDTO();
        map = new HashMap();
        map.put("productId", "1");
        map.put("name", "纪巧写若场昏阻坑园舌未幼");
        map.put("price", "8668.09");
        map.put("quantity", "10001");
        expectedDTO.jsonParam = map;
        expectedDTO.expected = "数量:最大不能超过10000";
        expectedDTOS.add(expectedDTO);

        for (ExpectedDTO item:
                expectedDTOS) {
            given().
                    contentType(JSON).
                    body(item.jsonParam).
                    header("Authorization", "Bearer " + access_token).
            when().
                    //log().all().
                    put(API_GATEWAY + "/api/admin/product/modify").
            then().
                    log().all().
                    statusCode(422).
                    body(containsString(item.expected));
        }
    }

    /**
     * 删除一条商品信息信息(非物理删除)-测试用例
     */
    @Test
    @Description("测试:删除一条商品信息信息(非物理删除)")
    @DisplayName("测试:删除一条商品信息信息(非物理删除)")
    @Order(5)
    public void testDelete() {
        if(access_token.isEmpty()){
            access_token = tokenUtils.getAccessToken();
        }

        // 合法用例
        map = new HashMap();

        given().
                pathParam("productId", "1").
                contentType(JSON).
                body(map).
                header("Authorization","Bearer " + access_token).
        when().
                //log().all().
                delete(API_GATEWAY + "/api/admin/product/delete/{productId}").
        then().
                log().all().
                statusCode(204);
    }

}

3.下载项目代码

点击“下载项目代码”按钮,即可将整个Quarkus微服务的项目代码Zip包下载到你的电脑本地:
2.4 快速生成Quarkus微服务代码-鸿蒙开发者社区

原创不易,请不吝点赞或评论互动,以激励作者的创作热情。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
com.bamasmiles.goods.zip 68.55K 15次下载
2
收藏
回复
举报
回复
    相关推荐