初始化提交

This commit is contained in:
YangJ
2024-03-20 09:42:17 +08:00
commit 72f30209cf
3705 changed files with 285827 additions and 0 deletions

View File

@ -0,0 +1,135 @@
package cn.iocoder.yudao.module.product.service.brand;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.product.controller.admin.brand.vo.ProductBrandCreateReqVO;
import cn.iocoder.yudao.module.product.controller.admin.brand.vo.ProductBrandPageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.brand.vo.ProductBrandUpdateReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.brand.ProductBrandDO;
import cn.iocoder.yudao.module.product.dal.mysql.brand.ProductBrandMapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.BRAND_NOT_EXISTS;
import static org.junit.jupiter.api.Assertions.*;
/**
* {@link ProductBrandServiceImpl} 的单元测试类
*
* @author 芋道源码
*/
@Disabled // TODO 芋艿:后续 fix 补充的单测
@Import(ProductBrandServiceImpl.class)
public class ProductBrandServiceImplTest extends BaseDbUnitTest {
@Resource
private ProductBrandServiceImpl brandService;
@Resource
private ProductBrandMapper brandMapper;
@Test
public void testCreateBrand_success() {
// 准备参数
ProductBrandCreateReqVO reqVO = randomPojo(ProductBrandCreateReqVO.class);
// 调用
Long brandId = brandService.createBrand(reqVO);
// 断言
assertNotNull(brandId);
// 校验记录的属性是否正确
ProductBrandDO brand = brandMapper.selectById(brandId);
assertPojoEquals(reqVO, brand);
}
@Test
public void testUpdateBrand_success() {
// mock 数据
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class);
brandMapper.insert(dbBrand);// @Sql: 先插入出一条存在的数据
// 准备参数
ProductBrandUpdateReqVO reqVO = randomPojo(ProductBrandUpdateReqVO.class, o -> {
o.setId(dbBrand.getId()); // 设置更新的 ID
});
// 调用
brandService.updateBrand(reqVO);
// 校验是否更新正确
ProductBrandDO brand = brandMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, brand);
}
@Test
public void testUpdateBrand_notExists() {
// 准备参数
ProductBrandUpdateReqVO reqVO = randomPojo(ProductBrandUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> brandService.updateBrand(reqVO), BRAND_NOT_EXISTS);
}
@Test
public void testDeleteBrand_success() {
// mock 数据
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class);
brandMapper.insert(dbBrand);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbBrand.getId();
// 调用
brandService.deleteBrand(id);
// 校验数据不存在了
assertNull(brandMapper.selectById(id));
}
@Test
public void testDeleteBrand_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> brandService.deleteBrand(id), BRAND_NOT_EXISTS);
}
@Test
public void testGetBrandPage() {
// mock 数据
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class, o -> { // 等会查询到
o.setName("芋道源码");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setCreateTime(buildTime(2022, 2, 1));
});
brandMapper.insert(dbBrand);
// 测试 name 不匹配
brandMapper.insert(cloneIgnoreId(dbBrand, o -> o.setName("源码")));
// 测试 status 不匹配
brandMapper.insert(cloneIgnoreId(dbBrand, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 测试 createTime 不匹配
brandMapper.insert(cloneIgnoreId(dbBrand, o -> o.setCreateTime(buildTime(2022, 3, 1))));
// 准备参数
ProductBrandPageReqVO reqVO = new ProductBrandPageReqVO();
reqVO.setName("芋道");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 1, 1), buildTime(2022, 2, 25)}));
// 调用
PageResult<ProductBrandDO> pageResult = brandService.getBrandPage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbBrand, pageResult.getList().get(0));
}
}

View File

@ -0,0 +1,163 @@
package cn.iocoder.yudao.module.product.service.category;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.product.controller.admin.category.vo.ProductCategoryListReqVO;
import cn.iocoder.yudao.module.product.controller.admin.category.vo.ProductCategorySaveReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.category.ProductCategoryDO;
import cn.iocoder.yudao.module.product.dal.mysql.category.ProductCategoryMapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.util.List;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.module.product.dal.dataobject.category.ProductCategoryDO.PARENT_ID_NULL;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.CATEGORY_NOT_EXISTS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* {@link ProductCategoryServiceImpl} 的单元测试类
*
* @author 芋道源码
*/
@Disabled // TODO 芋艿:后续 fix 补充的单测
@Import(ProductCategoryServiceImpl.class)
public class ProductCategoryServiceImplTest extends BaseDbUnitTest {
@Resource
private ProductCategoryServiceImpl productCategoryService;
@Resource
private ProductCategoryMapper productCategoryMapper;
@Test
public void testCreateCategory_success() {
// 准备参数
//ProductCategoryCreateReqVO reqVO = randomPojo(ProductCategoryCreateReqVO.class);
// mock 父类
//ProductCategoryDO parentProductCategory = randomPojo(ProductCategoryDO.class, o -> {
// reqVO.setParentId(o.getId());
// o.setParentId(PARENT_ID_NULL);
//});
//productCategoryMapper.insert(parentProductCategory);
//
//// 调用
//Long categoryId = productCategoryService.createCategory(reqVO);
//// 断言
//assertNotNull(categoryId);
//// 校验记录的属性是否正确
//ProductCategoryDO category = productCategoryMapper.selectById(categoryId);
//assertPojoEquals(reqVO, category);
}
@Test
public void testUpdateCategory_success() {
// mock 数据
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class);
productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据
// 准备参数
ProductCategorySaveReqVO reqVO = randomPojo(ProductCategorySaveReqVO.class, o -> {
o.setId(dbCategory.getId()); // 设置更新的 ID
});
// mock 父类
ProductCategoryDO parentProductCategory = randomPojo(ProductCategoryDO.class, o -> o.setId(reqVO.getParentId()));
productCategoryMapper.insert(parentProductCategory);
// 调用
productCategoryService.updateCategory(reqVO);
// 校验是否更新正确
ProductCategoryDO category = productCategoryMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, category);
}
@Test
public void testUpdateCategory_notExists() {
// 准备参数
ProductCategorySaveReqVO reqVO = randomPojo(ProductCategorySaveReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> productCategoryService.updateCategory(reqVO), CATEGORY_NOT_EXISTS);
}
@Test
public void testDeleteCategory_success() {
// mock 数据
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class);
productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbCategory.getId();
// 调用
productCategoryService.deleteCategory(id);
// 校验数据不存在了
assertNull(productCategoryMapper.selectById(id));
}
@Test
public void testDeleteCategory_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> productCategoryService.deleteCategory(id), CATEGORY_NOT_EXISTS);
}
@Test
public void testGetCategoryLevel() {
// mock 数据
ProductCategoryDO category1 = randomPojo(ProductCategoryDO.class,
o -> o.setParentId(PARENT_ID_NULL));
productCategoryMapper.insert(category1);
ProductCategoryDO category2 = randomPojo(ProductCategoryDO.class,
o -> o.setParentId(category1.getId()));
productCategoryMapper.insert(category2);
ProductCategoryDO category3 = randomPojo(ProductCategoryDO.class,
o -> o.setParentId(category2.getId()));
productCategoryMapper.insert(category3);
// 调用,并断言
assertEquals(productCategoryService.getCategoryLevel(category1.getId()), 1);
assertEquals(productCategoryService.getCategoryLevel(category2.getId()), 2);
assertEquals(productCategoryService.getCategoryLevel(category3.getId()), 3);
}
@Test
public void testGetCategoryList() {
// mock 数据
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class, o -> { // 等会查询到
o.setName("奥特曼");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setParentId(PARENT_ID_NULL);
});
productCategoryMapper.insert(dbCategory);
// 测试 name 不匹配
productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setName("奥特块")));
// 测试 status 不匹配
productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 测试 parentId 不匹配
productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setParentId(3333L)));
// 准备参数
ProductCategoryListReqVO reqVO = new ProductCategoryListReqVO();
reqVO.setName("特曼");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setParentId(PARENT_ID_NULL);
// 调用
List<ProductCategoryDO> list = productCategoryService.getCategoryList(reqVO);
List<ProductCategoryDO> all = productCategoryService.getCategoryList(new ProductCategoryListReqVO());
// 断言
assertEquals(1, list.size());
assertEquals(4, all.size());
assertPojoEquals(dbCategory, list.get(0));
}
}

View File

@ -0,0 +1,195 @@
package cn.iocoder.yudao.module.product.service.comment;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentPageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentReplyReqVO;
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentRespVO;
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentUpdateVisibleReqVO;
import cn.iocoder.yudao.module.product.controller.app.comment.vo.AppCommentPageReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.comment.ProductCommentDO;
import cn.iocoder.yudao.module.product.dal.mysql.comment.ProductCommentMapper;
import cn.iocoder.yudao.module.product.enums.comment.ProductCommentScoresEnum;
import cn.iocoder.yudao.module.product.service.sku.ProductSkuService;
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
// TODO 芋艿:单测详细 review 下
/**
* {@link ProductCommentServiceImpl} 的单元测试类
*
* @author wangzhs
*/
@Disabled // TODO 芋艿:后续 fix 补充的单测
@Import(ProductCommentServiceImpl.class)
public class ProductCommentServiceImplTest extends BaseDbUnitTest {
@Resource
private ProductCommentMapper productCommentMapper;
@Resource
@Lazy
private ProductCommentServiceImpl productCommentService;
@MockBean
private ProductSpuService productSpuService;
@MockBean
private ProductSkuService productSkuService;
public String generateNo() {
return DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomInt(100000, 999999);
}
public Long generateId() {
return RandomUtil.randomLong(100000, 999999);
}
@Test
public void testCreateCommentAndGet_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class);
productCommentMapper.insert(productComment);
// 断言
// 校验记录的属性是否正确
ProductCommentDO comment = productCommentMapper.selectById(productComment.getId());
assertPojoEquals(productComment, comment);
}
@Test
public void testGetCommentPage_success() {
// 准备参数
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
o.setUserNickname("王二狗");
o.setSpuName("感冒药");
o.setScores(ProductCommentScoresEnum.FOUR.getScores());
o.setReplyStatus(Boolean.TRUE);
o.setVisible(Boolean.TRUE);
o.setId(generateId());
o.setUserId(generateId());
o.setAnonymous(Boolean.TRUE);
o.setOrderId(generateId());
o.setOrderItemId(generateId());
o.setSpuId(generateId());
o.setSkuId(generateId());
o.setDescriptionScores(ProductCommentScoresEnum.FOUR.getScores());
o.setBenefitScores(ProductCommentScoresEnum.FOUR.getScores());
o.setContent("真好吃");
o.setReplyUserId(generateId());
o.setReplyContent("确实");
o.setReplyTime(LocalDateTime.now());
o.setCreateTime(LocalDateTime.now());
o.setUpdateTime(LocalDateTime.now());
});
productCommentMapper.insert(productComment);
Long orderId = productComment.getOrderId();
Long spuId = productComment.getSpuId();
// 测试 userNickname 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setUserNickname("王三").setScores(ProductCommentScoresEnum.ONE.getScores())));
// 测试 orderId 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setOrderId(generateId())));
// 测试 spuId 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setSpuId(generateId())));
// 测试 spuName 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setSpuName("感康")));
// 测试 scores 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setScores(ProductCommentScoresEnum.ONE.getScores())));
// 测试 replied 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setReplyStatus(Boolean.FALSE)));
// 测试 visible 不匹配
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setVisible(Boolean.FALSE)));
// 调用
ProductCommentPageReqVO productCommentPageReqVO = new ProductCommentPageReqVO();
productCommentPageReqVO.setUserNickname("王二");
productCommentPageReqVO.setOrderId(orderId);
productCommentPageReqVO.setSpuId(spuId);
productCommentPageReqVO.setSpuName("感冒药");
productCommentPageReqVO.setScores(ProductCommentScoresEnum.FOUR.getScores());
productCommentPageReqVO.setReplyStatus(Boolean.TRUE);
PageResult<ProductCommentDO> commentPage = productCommentService.getCommentPage(productCommentPageReqVO);
PageResult<ProductCommentRespVO> result = BeanUtils.toBean(productCommentMapper.selectPage(productCommentPageReqVO),
ProductCommentRespVO.class);
assertEquals(result.getTotal(), commentPage.getTotal());
PageResult<ProductCommentDO> all = productCommentService.getCommentPage(new ProductCommentPageReqVO());
assertEquals(8, all.getTotal());
// 测试获取所有商品分页评论数据
PageResult<ProductCommentDO> result1 = productCommentService.getCommentPage(new AppCommentPageReqVO(), Boolean.TRUE);
assertEquals(7, result1.getTotal());
// 测试获取所有商品分页中评数据
PageResult<ProductCommentDO> result2 = productCommentService.getCommentPage(new AppCommentPageReqVO().setType(AppCommentPageReqVO.MEDIOCRE_COMMENT), Boolean.TRUE);
assertEquals(2, result2.getTotal());
// 测试获取指定 spuId 商品分页中评数据
PageResult<ProductCommentDO> result3 = productCommentService.getCommentPage(new AppCommentPageReqVO().setSpuId(spuId).setType(AppCommentPageReqVO.MEDIOCRE_COMMENT), Boolean.TRUE);
assertEquals(2, result3.getTotal());
// 测试分页 tab count
//AppCommentStatisticsRespVO tabsCount = productCommentService.getCommentStatistics(spuId, Boolean.TRUE);
//assertEquals(4, tabsCount.getGoodCount());
//assertEquals(2, tabsCount.getMediocreCount());
//assertEquals(0, tabsCount.getNegativeCount());
}
@Test
public void testUpdateCommentVisible_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
o.setVisible(Boolean.TRUE);
});
productCommentMapper.insert(productComment);
Long productCommentId = productComment.getId();
ProductCommentUpdateVisibleReqVO updateReqVO = new ProductCommentUpdateVisibleReqVO();
updateReqVO.setId(productCommentId);
updateReqVO.setVisible(Boolean.FALSE);
productCommentService.updateCommentVisible(updateReqVO);
ProductCommentDO productCommentDO = productCommentMapper.selectById(productCommentId);
assertFalse(productCommentDO.getVisible());
}
@Test
public void testCommentReply_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class);
productCommentMapper.insert(productComment);
Long productCommentId = productComment.getId();
ProductCommentReplyReqVO replyVO = new ProductCommentReplyReqVO();
replyVO.setId(productCommentId);
replyVO.setReplyContent("测试");
productCommentService.replyComment(replyVO, 1L);
ProductCommentDO productCommentDO = productCommentMapper.selectById(productCommentId);
assertEquals("测试", productCommentDO.getReplyContent());
}
}

View File

@ -0,0 +1,207 @@
package cn.iocoder.yudao.module.product.service.sku;
import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.framework.test.core.util.AssertUtils;
import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuUpdateStockReqDTO;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSkuSaveReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.iocoder.yudao.module.product.dal.mysql.sku.ProductSkuMapper;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyService;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SKU_NOT_EXISTS;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SKU_STOCK_NOT_ENOUGH;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
/**
* {@link ProductSkuServiceImpl} 的单元测试
*
* @author 芋道源码
*/
@Disabled // TODO 芋艿:后续 fix 补充的单测
@Import(ProductSkuServiceImpl.class)
public class ProductSkuServiceTest extends BaseDbUnitTest {
@Resource
private ProductSkuService productSkuService;
@Resource
private ProductSkuMapper productSkuMapper;
@MockBean
private ProductSpuService productSpuService;
@MockBean
private ProductPropertyService productPropertyService;
@MockBean
private ProductPropertyValueService productPropertyValueService;
public Long generateId() {
return RandomUtil.randomLong(100000, 999999);
}
@Test
public void testUpdateSkuList() {
// mock 数据
ProductSkuDO sku01 = randomPojo(ProductSkuDO.class, o -> { // 测试更新
o.setSpuId(1L);
o.setProperties(singletonList(new ProductSkuDO.Property(
10L, "颜色", 20L, "红色")));
});
productSkuMapper.insert(sku01);
ProductSkuDO sku02 = randomPojo(ProductSkuDO.class, o -> { // 测试删除
o.setSpuId(1L);
o.setProperties(singletonList(new ProductSkuDO.Property(
10L, "颜色", 30L, "蓝色")));
});
productSkuMapper.insert(sku02);
// 准备参数
Long spuId = 1L;
String spuName = "测试商品";
List<ProductSkuSaveReqVO> skus = Arrays.asList(
randomPojo(ProductSkuSaveReqVO.class, o -> { // 测试更新
o.setProperties(singletonList(new ProductSkuSaveReqVO.Property(
10L, "颜色", 20L, "红色")));
}),
randomPojo(ProductSkuSaveReqVO.class, o -> { // 测试新增
o.setProperties(singletonList(new ProductSkuSaveReqVO.Property(
10L, "颜色", 20L, "红色")));
})
);
// 调用
productSkuService.updateSkuList(spuId, skus);
// 断言
List<ProductSkuDO> dbSkus = productSkuMapper.selectListBySpuId(spuId);
assertEquals(dbSkus.size(), 2);
// 断言更新的
assertEquals(dbSkus.get(0).getId(), sku01.getId());
assertPojoEquals(dbSkus.get(0), skus.get(0), "properties");
assertEquals(skus.get(0).getProperties().size(), 1);
assertPojoEquals(dbSkus.get(0).getProperties().get(0), skus.get(0).getProperties().get(0));
// 断言新增的
assertNotEquals(dbSkus.get(1).getId(), sku02.getId());
assertPojoEquals(dbSkus.get(1), skus.get(1), "properties");
assertEquals(skus.get(1).getProperties().size(), 1);
assertPojoEquals(dbSkus.get(1).getProperties().get(0), skus.get(1).getProperties().get(0));
}
@Test
public void testUpdateSkuStock_incrSuccess() {
// 准备参数
ProductSkuUpdateStockReqDTO updateStockReqDTO = new ProductSkuUpdateStockReqDTO()
.setItems(singletonList(new ProductSkuUpdateStockReqDTO.Item().setId(1L).setIncrCount(10)));
// mock 数据
productSkuMapper.insert(randomPojo(ProductSkuDO.class, o -> {
o.setId(1L).setSpuId(10L).setStock(20);
o.getProperties().forEach(p -> {
// 指定 id 范围 解决 Value too long
p.setPropertyId(generateId());
p.setValueId(generateId());
});
}));
// 调用
productSkuService.updateSkuStock(updateStockReqDTO);
// 断言
ProductSkuDO sku = productSkuMapper.selectById(1L);
assertEquals(sku.getStock(), 30);
verify(productSpuService).updateSpuStock(argThat(spuStockIncrCounts -> {
assertEquals(spuStockIncrCounts.size(), 1);
assertEquals(spuStockIncrCounts.get(10L), 10);
return true;
}));
}
@Test
public void testUpdateSkuStock_decrSuccess() {
// 准备参数
ProductSkuUpdateStockReqDTO updateStockReqDTO = new ProductSkuUpdateStockReqDTO()
.setItems(singletonList(new ProductSkuUpdateStockReqDTO.Item().setId(1L).setIncrCount(-10)));
// mock 数据
productSkuMapper.insert(randomPojo(ProductSkuDO.class, o -> {
o.setId(1L).setSpuId(10L).setStock(20);
o.getProperties().forEach(p -> {
// 指定 id 范围 解决 Value too long
p.setPropertyId(generateId());
p.setValueId(generateId());
});
}));
// 调用
productSkuService.updateSkuStock(updateStockReqDTO);
// 断言
ProductSkuDO sku = productSkuMapper.selectById(1L);
assertEquals(sku.getStock(), 10);
verify(productSpuService).updateSpuStock(argThat(spuStockIncrCounts -> {
assertEquals(spuStockIncrCounts.size(), 1);
assertEquals(spuStockIncrCounts.get(10L), -10);
return true;
}));
}
@Test
public void testUpdateSkuStock_decrFail() {
// 准备参数
ProductSkuUpdateStockReqDTO updateStockReqDTO = new ProductSkuUpdateStockReqDTO()
.setItems(singletonList(new ProductSkuUpdateStockReqDTO.Item().setId(1L).setIncrCount(-30)));
// mock 数据
productSkuMapper.insert(randomPojo(ProductSkuDO.class, o -> {
o.setId(1L).setSpuId(10L).setStock(20);
o.getProperties().forEach(p -> {
// 指定 id 范围 解决 Value too long
p.setPropertyId(generateId());
p.setValueId(generateId());
});
}));
// 调用并断言
AssertUtils.assertServiceException(() -> productSkuService.updateSkuStock(updateStockReqDTO),
SKU_STOCK_NOT_ENOUGH);
}
@Test
public void testDeleteSku_success() {
ProductSkuDO dbSku = randomPojo(ProductSkuDO.class, o -> {
o.setId(generateId()).setSpuId(generateId());
o.getProperties().forEach(p -> {
// 指定 id 范围 解决 Value too long
p.setPropertyId(generateId());
p.setValueId(generateId());
});
});
// mock 数据
productSkuMapper.insert(dbSku);
// 准备参数
Long id = dbSku.getId();
// 调用
productSkuService.deleteSku(id);
// 校验数据不存在了
assertNull(productSkuMapper.selectById(id));
}
@Test
public void testDeleteSku_notExists() {
// 准备参数
Long id = 1L;
// 调用, 并断言异常
assertServiceException(() -> productSkuService.deleteSku(id), SKU_NOT_EXISTS);
}
}

View File

@ -0,0 +1,470 @@
package cn.iocoder.yudao.module.product.service.spu;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSkuSaveReqVO;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuPageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuSaveReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.dal.mysql.spu.ProductSpuMapper;
import cn.iocoder.yudao.module.product.enums.spu.ProductSpuStatusEnum;
import cn.iocoder.yudao.module.product.service.brand.ProductBrandServiceImpl;
import cn.iocoder.yudao.module.product.service.category.ProductCategoryServiceImpl;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyService;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
import cn.iocoder.yudao.module.product.service.sku.ProductSkuServiceImpl;
import com.google.common.collect.Lists;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static org.assertj.core.util.Lists.newArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
// TODO @芋艿review 下单元测试
/**
* {@link ProductSpuServiceImpl} 的单元测试类
*
* @author 芋道源码
*/
@Disabled // TODO 芋艿:后续 fix 补充的单测
@Import(ProductSpuServiceImpl.class)
public class ProductSpuServiceImplTest extends BaseDbUnitTest {
@Resource
private ProductSpuServiceImpl productSpuService;
@Resource
private ProductSpuMapper productSpuMapper;
@MockBean
private ProductSkuServiceImpl productSkuService;
@MockBean
private ProductCategoryServiceImpl categoryService;
@MockBean
private ProductBrandServiceImpl brandService;
@MockBean
private ProductPropertyService productPropertyService;
@MockBean
private ProductPropertyValueService productPropertyValueService;
public String generateNo() {
return DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomInt(100000, 999999);
}
public Long generateId() {
return RandomUtil.randomLong(100000, 999999);
}
public int generaInt(){return RandomUtil.randomInt(1,9999999);}
// TODO @芋艿:单测后续 review 哈
@Test
public void testCreateSpu_success() {
// 准备参数
ProductSkuSaveReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuSaveReqVO.class, o->{
// 限制范围为正整数
o.setCostPrice(generaInt());
o.setPrice(generaInt());
o.setMarketPrice(generaInt());
o.setStock(generaInt());
o.setFirstBrokeragePrice(generaInt());
o.setSecondBrokeragePrice(generaInt());
// 限制分数为两位数
o.setWeight(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
o.setVolume(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
});
ProductSpuSaveReqVO createReqVO = randomPojo(ProductSpuSaveReqVO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setSkus(newArrayList(skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO));
});
when(categoryService.getCategoryLevel(eq(createReqVO.getCategoryId()))).thenReturn(2);
Long spu = productSpuService.createSpu(createReqVO);
ProductSpuDO productSpuDO = productSpuMapper.selectById(spu);
assertPojoEquals(createReqVO, productSpuDO);
}
@Test
public void testUpdateSpu_success() {
// 准备参数
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
});
productSpuMapper.insert(createReqVO);
// 准备参数
ProductSkuSaveReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuSaveReqVO.class, o->{
// 限制范围为正整数
o.setCostPrice(generaInt());
o.setPrice(generaInt());
o.setMarketPrice(generaInt());
o.setStock(generaInt());
o.setFirstBrokeragePrice(generaInt());
o.setSecondBrokeragePrice(generaInt());
// 限制分数为两位数
o.setWeight(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
o.setVolume(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
});
// 准备参数
ProductSpuSaveReqVO reqVO = randomPojo(ProductSpuSaveReqVO.class, o -> {
o.setId(createReqVO.getId()); // 设置更新的 ID
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
o.setSkus(newArrayList(skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO));
});
when(categoryService.getCategoryLevel(eq(reqVO.getCategoryId()))).thenReturn(2);
// 调用
productSpuService.updateSpu(reqVO);
// 校验是否更新正确
ProductSpuDO spu = productSpuMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, spu);
}
@Test
public void testValidateSpuExists_exception() {
ProductSpuSaveReqVO reqVO = randomPojo(ProductSpuSaveReqVO.class);
// 调用
Assertions.assertThrows(ServiceException.class, () -> productSpuService.updateSpu(reqVO));
}
@Test
void deleteSpu() {
// 准备参数
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
o.setStatus(-1); // 加入回收站才可删除
});
productSpuMapper.insert(createReqVO);
// 调用
productSpuService.deleteSpu(createReqVO.getId());
Assertions.assertNull(productSpuMapper.selectById(createReqVO.getId()));
}
@Test
void getSpu() {
// 准备参数
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
});
productSpuMapper.insert(createReqVO);
ProductSpuDO spu = productSpuService.getSpu(createReqVO.getId());
assertPojoEquals(createReqVO, spu);
}
@Test
void getSpuList() {
// 准备参数
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
}), randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
}));
productSpuMapper.insertBatch(createReqVOs);
// 调用
List<ProductSpuDO> spuList = productSpuService.getSpuList(createReqVOs.stream().map(ProductSpuDO::getId).collect(Collectors.toList()));
Assertions.assertIterableEquals(createReqVOs, spuList);
}
@Test
void getSpuPage_alarmStock_empty() {
// 准备参数
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(11); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
}), randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(11); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
}));
productSpuMapper.insertBatch(createReqVOs);
// 调用
ProductSpuPageReqVO productSpuPageReqVO = new ProductSpuPageReqVO();
productSpuPageReqVO.setTabType(ProductSpuPageReqVO.ALERT_STOCK);
PageResult<ProductSpuDO> spuPage = productSpuService.getSpuPage(productSpuPageReqVO);
PageResult<Object> result = PageResult.empty();
Assertions.assertIterableEquals(result.getList(), spuPage.getList());
assertEquals(spuPage.getTotal(), result.getTotal());
}
@Test
void getSpuPage_alarmStock() {
// 准备参数
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(5); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
}), randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(9); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
}));
productSpuMapper.insertBatch(createReqVOs);
// 调用
ProductSpuPageReqVO productSpuPageReqVO = new ProductSpuPageReqVO();
productSpuPageReqVO.setTabType(ProductSpuPageReqVO.ALERT_STOCK);
PageResult<ProductSpuDO> spuPage = productSpuService.getSpuPage(productSpuPageReqVO);
assertEquals(createReqVOs.size(), spuPage.getTotal());
}
@Test
void testGetSpuPage() {
// 准备参数
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
});
// 准备参数
productSpuMapper.insert(createReqVO);
// 测试 status 不匹配
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setStatus(ProductSpuStatusEnum.DISABLE.getStatus())));
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setStatus(ProductSpuStatusEnum.RECYCLE.getStatus())));
// 测试 SpecType 不匹配
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setSpecType(true)));
// 测试 BrandId 不匹配
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setBrandId(generateId())));
// 测试 CategoryId 不匹配
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setCategoryId(generateId())));
// 调用
ProductSpuPageReqVO productSpuPageReqVO = new ProductSpuPageReqVO();
// 查询条件 按需打开
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.ALERT_STOCK);
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.RECYCLE_BIN);
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.FOR_SALE);
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.IN_WAREHOUSE);
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.SOLD_OUT);
//productSpuPageReqVO.setName(createReqVO.getName());
//productSpuPageReqVO.setCategoryId(createReqVO.getCategoryId());
PageResult<ProductSpuDO> spuPage = productSpuService.getSpuPage(productSpuPageReqVO);
assertEquals(1, spuPage.getTotal());
}
/**
* 生成笛卡尔积
*
* @param data 数据
* @return 笛卡尔积
*/
public static <T> List<List<T>> cartesianProduct(List<List<T>> data) {
List<List<T>> res = null; // 结果集(当前为第N个List则该处存放的就为前N-1个List的笛卡尔积集合)
for (List<T> list : data) { // 遍历数据
List<List<T>> temp = new ArrayList<>(); // 临时结果集,存放本次循环后生成的笛卡尔积集合
if (res == null) { // 结果集为null表示第一次循环既list为第一个List
for (T t : list) { // 便利第一个List
// 利用stream生成List第一个List的笛卡尔积集合约等于自己本身需要创建一个List并把对象添加到当中存放到临时结果集
temp.add(Stream.of(t).collect(Collectors.toList()));
}
res = temp; // 将临时结果集赋值给结果集
continue; // 跳过本次循环
}
// 不为第一个List计算前面的集合笛卡尔积和当前List的笛卡尔积集合
for (T t : list) { // 便利
for (List<T> rl : res) { // 便利前面的笛卡尔积集合
// 利用stream生成List
temp.add(Stream.concat(rl.stream(), Stream.of(t)).collect(Collectors.toList()));
}
}
res = temp; // 将临时结果集赋值给结果集
}
// 返回结果
return res;
}
@Test
public void testUpdateSpuStock() {
// 准备参数
Map<Long, Integer> stockIncrCounts = MapUtil.builder(1L, 10).put(2L, -20).build();
// mock 方法(数据)
productSpuMapper.insert(randomPojo(ProductSpuDO.class, o ->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
o.setId(1L).setStock(20);
}));
productSpuMapper.insert(randomPojo(ProductSpuDO.class, o -> {
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
o.setPrice(generaInt()); // 限制范围为正整数
o.setMarketPrice(generaInt()); // 限制范围为正整数
o.setCostPrice(generaInt()); // 限制范围为正整数
o.setStock(generaInt()); // 限制范围为正整数
o.setGiveIntegral(generaInt()); // 限制范围为正整数
o.setSalesCount(generaInt()); // 限制范围为正整数
o.setBrowseCount(generaInt()); // 限制范围为正整数
o.setId(2L).setStock(30);
}));
// 调用
productSpuService.updateSpuStock(stockIncrCounts);
// 断言
assertEquals(productSpuService.getSpu(1L).getStock(), 30);
assertEquals(productSpuService.getSpu(2L).getStock(), 10);
}
}

View File

@ -0,0 +1,50 @@
spring:
main:
lazy-initialization: true # 开启懒加载,加快速度
banner-mode: off # 单元测试,禁用 Banner
--- #################### 数据库相关配置 ####################
spring:
# 数据源配置项
datasource:
name: ruoyi-vue-pro
url: jdbc:h2:mem:testdb;MODE=MYSQL;DATABASE_TO_UPPER=false;NON_KEYWORDS=value; # MODE 使用 MySQL 模式DATABASE_TO_UPPER 配置表和字段使用小写
driver-class-name: org.h2.Driver
username: sa
password:
druid:
async-init: true # 单元测试,异步初始化 Druid 连接池,提升启动速度
initial-size: 1 # 单元测试,配置为 1提升启动速度
sql:
init:
schema-locations: classpath:/sql/create_tables.sql
# Redis 配置。Redisson 默认的配置足够使用,一般不需要进行调优
redis:
host: 127.0.0.1 # 地址
port: 16379 # 端口(单元测试,使用 16379 端口)
database: 0 # 数据库索引
mybatis-plus:
lazy-initialization: true # 单元测试,设置 MyBatis Mapper 延迟加载,加速每个单元测试
type-aliases-package: ${yudao.info.base-package}.module.*.dal.dataobject
--- #################### 定时任务相关配置 ####################
--- #################### 配置中心相关配置 ####################
--- #################### 服务保障相关配置 ####################
# Lock4j 配置项(单元测试,禁用 Lock4j
# Resilience4j 配置项
--- #################### 监控相关配置 ####################
--- #################### 芋道相关配置 ####################
# 芋道配置项,设置当前项目所有自定义的配置
yudao:
info:
base-package: cn.iocoder.yudao

View File

@ -0,0 +1,4 @@
<configuration>
<!-- 引用 Spring Boot 的 logback 基础配置 -->
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
</configuration>

View File

@ -0,0 +1,7 @@
DELETE FROM "product_sku";
DELETE FROM "product_spu";
DELETE FROM "product_category";
DELETE FROM "product_brand";
DELETE FROM "product_property";
DELETE FROM "product_property_value";
DELETE FROM "product_comment";

View File

@ -0,0 +1,157 @@
CREATE TABLE IF NOT EXISTS `product_sku` (
`id` bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY,
`spu_id` bigint NOT NULL COMMENT 'spu编号',
`properties` varchar(512) DEFAULT NULL COMMENT '属性数组JSON 格式',
`price` int NOT NULL DEFAULT '-1' COMMENT '商品价格,单位:分',
`market_price` int DEFAULT NULL COMMENT '市场价,单位:分',
`cost_price` int NOT NULL DEFAULT '-1' COMMENT '成本价,单位: 分',
`bar_code` varchar(64) DEFAULT NULL COMMENT 'SKU 的条形码',
`pic_url` varchar(256) NOT NULL COMMENT '图片地址',
`stock` int DEFAULT NULL COMMENT '库存',
`weight` double DEFAULT NULL COMMENT '商品重量单位kg 千克',
`volume` double DEFAULT NULL COMMENT '商品体积单位m^3 平米',
`sub_commission_first_price` int DEFAULT NULL COMMENT '一级分销的佣金,单位:分',
`sub_commission_second_price` int DEFAULT NULL COMMENT '二级分销的佣金,单位:分',
`sales_count` int DEFAULT NULL COMMENT '商品销量',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
"tenant_id" bigint not null default '0',
PRIMARY KEY("id")
) COMMENT '商品sku';
CREATE TABLE IF NOT EXISTS `product_spu` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '商品 SPU 编号,自增',
`name` varchar(128) NOT NULL COMMENT '商品名称',
`keyword` varchar(256) NOT NULL COMMENT '关键字',
`introduction` varchar(256) NOT NULL COMMENT '商品简介',
`description` text NOT NULL COMMENT '商品详情',
`bar_code` varchar(64) NOT NULL COMMENT '条形码',
`category_id` bigint NOT NULL COMMENT '商品分类编号',
`brand_id` int DEFAULT NULL COMMENT '商品品牌编号',
`pic_url` varchar(256) NOT NULL COMMENT '商品封面图',
`slider_pic_urls` varchar(2000) DEFAULT '' COMMENT '商品轮播图地址\n 数组,以逗号分隔\n 最多上传15张',
`video_url` varchar(256) DEFAULT NULL COMMENT '商品视频',
`unit` tinyint NOT NULL COMMENT '单位',
`sort` int NOT NULL DEFAULT '0' COMMENT '排序字段',
`status` tinyint NOT NULL COMMENT '商品状态: 0 上架(开启) 1 下架(禁用)-1 回收',
`spec_type` bit(1) NOT NULL COMMENT '规格类型0 单规格 1 多规格',
`price` int NOT NULL DEFAULT '-1' COMMENT '商品价格,单位使用:分',
`market_price` int NOT NULL COMMENT '市场价,单位使用:分',
`cost_price` int NOT NULL DEFAULT '-1' COMMENT '成本价,单位: 分',
`stock` int NOT NULL DEFAULT '0' COMMENT '库存',
`delivery_template_id` bigint NOT NULL COMMENT '物流配置模板编号',
`recommend_hot` bit(1) NOT NULL COMMENT '是否热卖推荐: 0 默认 1 热卖',
`recommend_benefit` bit(1) NOT NULL COMMENT '是否优惠推荐: 0 默认 1 优选',
`recommend_best` bit(1) NOT NULL COMMENT '是否精品推荐: 0 默认 1 精品',
`recommend_new` bit(1) NOT NULL COMMENT '是否新品推荐: 0 默认 1 新品',
`recommend_good` bit(1) NOT NULL COMMENT '是否优品推荐',
`give_integral` int NOT NULL COMMENT '赠送积分',
`give_coupon_template_ids` varchar(512) DEFAULT '' COMMENT '赠送的优惠劵编号的数组',
`sub_commission_type` bit(1) NOT NULL COMMENT '分销类型',
`activity_orders` varchar(16) NOT NULL DEFAULT '' COMMENT '活动显示排序0=默认, 1=秒杀2=砍价3=拼团',
`sales_count` int DEFAULT '0' COMMENT '商品销量',
`virtual_sales_count` int DEFAULT '0' COMMENT '虚拟销量',
`browse_count` int DEFAULT '0' COMMENT '商品点击量',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
"tenant_id" bigint not null default '0',
PRIMARY KEY("id")
) COMMENT '商品spu';
CREATE TABLE IF NOT EXISTS `product_category` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '分类编号',
`parent_id` bigint NOT NULL COMMENT '父分类编号',
`name` varchar(255) NOT NULL COMMENT '分类名称',
`pic_url` varchar(255) NOT NULL COMMENT '移动端分类图',
`big_pic_url` varchar(255) DEFAULT NULL COMMENT 'PC 端分类图',
`sort` int DEFAULT '0' COMMENT '分类排序',
`status` tinyint NOT NULL COMMENT '开启状态',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
"tenant_id" bigint not null default '0',
PRIMARY KEY("id")
) COMMENT '商品分类';
CREATE TABLE IF NOT EXISTS `product_brand` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '品牌编号',
`name` varchar(255) NOT NULL COMMENT '品牌名称',
`pic_url` varchar(255) NOT NULL COMMENT '品牌图片',
`sort` int DEFAULT '0' COMMENT '品牌排序',
`description` varchar(1024) DEFAULT NULL COMMENT '品牌描述',
`status` tinyint NOT NULL COMMENT '状态',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
"tenant_id" bigint not null default '0',
PRIMARY KEY("id")
) COMMENT '商品品牌';
CREATE TABLE IF NOT EXISTS `product_property` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(64) DEFAULT NULL COMMENT '规格名称',
`status` tinyint DEFAULT NULL COMMENT '状态: 0 开启 1 禁用',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
"tenant_id" bigint not null default '0',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY("id")
) COMMENT '规格名称';
CREATE TABLE IF NOT EXISTS `product_property_value` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`property_id` bigint DEFAULT NULL COMMENT '规格键id',
`name` varchar(128) DEFAULT NULL COMMENT '规格值名字',
`status` tinyint DEFAULT NULL COMMENT '状态: 1 开启 2 禁用',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
"tenant_id" bigint not null default '0',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY("id")
) COMMENT '规格值';
DROP TABLE IF EXISTS `product_comment` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '评论编号,主键自增',
`user_id` bigint DEFAULT NULL COMMENT '评价人的用户编号关联 MemberUserDO 的 id 编号',
`user_nickname` varchar(255) DEFAULT NULL COMMENT '评价人名称',
`user_avatar` varchar(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '评价人头像',
`anonymous` bit(1) DEFAULT NULL COMMENT '是否匿名',
`order_id` bigint DEFAULT NULL COMMENT '交易订单编号关联 TradeOrderDO 的 id 编号',
`order_item_id` bigint DEFAULT NULL COMMENT '交易订单项编号关联 TradeOrderItemDO 的 id 编号',
`spu_id` bigint DEFAULT NULL COMMENT '商品 SPU 编号关联 ProductSpuDO 的 id',
`spu_name` varchar(255) DEFAULT NULL COMMENT '商品 SPU 名称',
`sku_id` bigint DEFAULT NULL COMMENT '商品 SKU 编号关联 ProductSkuDO 的 id 编号',
`visible` bit(1) DEFAULT NULL COMMENT '是否可见true:显示false:隐藏',
`scores` tinyint DEFAULT NULL COMMENT '评分星级1-5分',
`description_scores` tinyint DEFAULT NULL COMMENT '描述星级1-5 星',
`benefit_scores` tinyint DEFAULT NULL COMMENT '服务星级1-5 星',
`content` varchar(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '评论内容',
`pic_urls` varchar(4096) DEFAULT NULL COMMENT '评论图片地址数组',
`reply_status` bit(1) DEFAULT NULL COMMENT '商家是否回复',
`reply_user_id` bigint DEFAULT NULL COMMENT '回复管理员编号关联 AdminUserDO 的 id 编号',
`reply_content` varchar(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '商家回复内容',
`reply_time` datetime DEFAULT NULL COMMENT '商家回复时间',
`creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '创建者',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '更新者',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
`tenant_id` bigint NOT NULL DEFAULT '0' COMMENT '租户编号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 26 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin COMMENT = '商品评论';