# 测试文档
**<font size = 5>文档作者</font>**
主要编写者:李孟宇、汪楷涵、劳厚新、史珈豪
其他编写者:无
**<font size = 5>文档修改历史</font>**
| 修改人员 | 日期 | 修改原因 | 版本号 |
| :------: | ------------ | ---------------------- | ------ |
| 李孟宇 | 2024年6月4日 | 创建了测试文档 | V1.0.0 |
| 李孟宇 | 2024年6月5日 | 添加了集成测试相关内容 | V1.0.1 |
| 汪楷涵 | 2024年6月5日 | 添加了功能测试5.1-5.8 | V1.0.2 |
| 劳厚新 | 2024年6月5日 | 添加了功能测试5.9-5.16 | V1.0.3 |
| | | | |
[toc]
## 1. 引言
### 1.1 目的
为了更好地辅助开发、保证产品的正确性安全性、提高用户信赖程度而进行明确的、有目的的、有效率的测试。
### 1.2 测试概述
| 产品名称 | 南鲸网购平台管理系统 |
| :------- | ----------------------------------- |
| 版本 | 1.0 |
| 测试标准 | ISO 29119 |
| 测试方法 | 单元测试、集成测试、功能测试 |
| 硬件环境 | 市面上笔记本电脑常见配置 |
| 软件环境 | Windows11,Java 8,Springboot框架 |
| 测试平台 | ntelliJ IDEA, JUnit 5,MySQL数据库 |
### 1.3 参考文献
- 《软件开发的技术基础》丁二玉、刘钦编著
- IEEE标准
- ISO标准
- 南鲸网购平台管理系统用例文档
- 南鲸网购平台管理系统需求规格说明书
- 南鲸网购平台管理系统体系结构设计文档
- 南鲸网购平台管理系统详细设计文档
## 2. 测试过程
**测试目标**
- 确保南鲸网购平台管理系统的各项功能和性能符合预期,并保证系统的稳定性和可靠性。
**测试范围**
- 测试涵盖了南鲸网购平台管理系统的单元测试、集成测试和功能测试。
**测试计划**
- 测试将在开发完成后的两周内完成。
**测试策略**
- 使用JUnit和Mock等工具进行单元测试,覆盖率达到80%以上。
- 使用MockMvc进行集成测试,验证各组件之间的交互。
- 对系统进行功能测试,验证系统的各项功能是否符合需求。
**测试用例设计:**
- 测试用例将根据功能需求和系统设计进行设计,覆盖主要功能模块和边界条件。
**测试执行:**
- 测试将由团队成员负责执行,同时记录测试结果和发现的问题。
## 3. 单元测试
### 3.1 测试概述
单元测试的目的在于确保每个单元都能独立地正常工作,从而提高整个程序的质量、可靠性和可维护性。本报告涵盖了对每个层级的单元测试,主要对Service的接口进行了相关测试。
### 3.2 测试详情
接下来我们只给出相关测试用例和测试结果,以及部分示例代码,详细测试代码见[附录7.1 单元测试代码](# 7.1 单元测试代码)。
**测试程序示例:**
```java
@Test
void testCreateStore_Success() {
StoreVO storeVO = new StoreVO();
storeVO.setName("New Store");
when(storeRepository.save(any(Store.class))).thenReturn(new Store());
Boolean result = storeService.createStore(storeVO);
assertTrue(result);
verify(storeRepository, times(1)).save(any(Store.class));
}
```
#### 3.2.1 用户模块测试
**UserServiceTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------------------- | ------------------------------ | ------------ | ---------- |
| testRegister_Success | 符合要求的用户信息 | 用户注册成功 | ***通过*** |
| testRegister_PhoneAlreadyExists | 用户手机号已存在 | 用户注册失败 | ***通过*** |
| testLogin_Success | 用户未登录 | 用户登录成功 | ***通过*** |
| testLogin_PhoneOrPasswordError | 用户登录时手机号或密码出现错误 | 用户登录失败 | ***通过*** |
| testGetInformation | 用户已登录 | 获得用户信息 | ***通过*** |
| testUpdateInformation | 用户已登录 | 更新信息成功 | ***通过*** |
**测试结果截图**

#### 3.2.2 商店模块测试
**StoreServiceTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| -------------------------------- | -------------- | -------------------- | ---------- |
| testGetInformation_Success | 正确的商店id | 得到商店详情 | ***通过*** |
| testGetInformation_StoreNotFound | 错误的商店id | 抛出商店不存在的异常 | ***通过*** |
| testGetAllProducts_Success | 正确的商店id | 得到商店的商品列表 | ***通过*** |
| testGetAllProducts_NoProducts | 正确的商店id | 抛出商品不存在的异常 | ***通过*** |
| testCreateStore_Success | 正确的商店信息 | 返回创建成功 | ***通过*** |
| testCreateStore_Exception | 正确的商店信息 | 抛出创建失败的异常 | ***通过*** |
| testGetAllStore_Success | 无 | 返回所有商店列表 | ***通过*** |
| testGetAllStore_NoStores | 无 | 抛出无商店的异常 | ***通过*** |
**测试结果截图**

#### 3.2.3 商品模块测试
**ProduceServiceTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ---------------------------------- | ------------------------ | -------------------------- | ---------- |
| testGetInformation_Success | 商品id | 得到商品详情 | ***通过*** |
| testGetInformation_ProductNotFound | 商品id | 抛出商品不存在的异常 | ***通过*** |
| testSetCurrentNum_Success | 商品id | 更改商品数量成功 | ***通过*** |
| testSetCurrentNum_ProductNotFound | 商品id | 抛出商店不存在的异常 | ***通过*** |
| testCreateProduct_Success | 商品信息 | 返回创建成功 | ***通过*** |
| testCreateProduct_Exception | 商品信息 | 抛出创建失败的异常 | ***通过*** |
| testGetComment_Success | 商品id | 得到商品评论 | ***通过*** |
| testGetComment_NoComments | 商品id | 抛出评论不存在的异常 | ***通过*** |
| testFind_Success | 商品名称,类别,价格区间 | 返回所有满足要求的商品列表 | ***通过*** |
| testFind_NoProducts | 商品名称,类别,价格区间 | 抛出此类商品不存在的异常 | ***通过*** |
**测试结果截图**

#### 3.2.4 订单模块测试
**OrderServiceTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------------ | ---------------- | ---------------------- | ---------- |
| testGetAllOrders_Success | 用户id,用户类型 | 得到用户的所有相关订单 | ***通过*** |
| testCreateOrder_Success | 正确的订单信息 | 返回创建订单id | ***通过*** |
| testPaySuccess_Success | 订单id,优惠券id | 返回支付成功 | ***通过*** |
| testSend_Success | 订单id | 返回发货成功 | ***通过*** |
| testGetProduct_Success | 订单id | 返回收货成功 | ***通过*** |
| testGetOrderInfo_Success | 订单id | 得到订单详情 | ***通过*** |
**测试结果截图**

#### 3.2.5 优惠券模块测试
**CouponServiceTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------------------- | ------------------ | ------------------ | ---------- |
| testSelectCoupon_Success | 订单id,优惠券id | 返回预计金额 | ***通过*** |
| testUseCoupon_Success | 订单id,优惠券id | 返回使用成功 | ***通过*** |
| testGetCouponGroups_Success | 商店id | 得到商店的优惠券组 | ***通过*** |
| testCreateCouponGroup_Success | 正确的优惠券组信息 | 返回创建成功 | ***通过*** |
| testCreateCouponGroup_Exception | 错误的优惠券组信息 | 抛出异常 | ***通过*** |
**测试结果截图**

## 4. 集成测试
### 4.1 测试概述
集成测试的目的在于验证不同模块之间的交互是否正确,以确保系统在实际应用中的可靠性和稳定性。本报告涵盖了对多个层级之间的集成测试,主要对Controller的接口进行了相关测试。
### 4.2 测试详情
接下来我们只给出相关测试用例和测试结果,以及部分示例代码,详细测试代码见[附录7.2 集成测试代码](# 7.2 集成测试代码)。
**测试程序示例:**
```java
@Test
public void testGetInformation() throws Exception {
Integer storeId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/stores/detail/getInfo")
.param("id", storeId.toString())
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").exists())
.andDo(print());
}
```
#### 4.2.1 用户模块测试
**UserContollerTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------------- | ---------------------------------- | ---------------- | ---------- |
| testRegister | 符合要求的用户信息 | 用户注册成功 | ***通过*** |
| testLogin | 符号要求的用户手机号和密码 | 用户登录成功 | ***通过*** |
| testGetInformation | 用户已登录 | 返回用户信息 | ***通过*** |
| testUpdateInformation | 用户已登录,输入符合要求的用户信息 | 用户更新信息成功 | ***通过*** |
**测试结果截图**

#### 4.2.2 商店模块测试
**StoreControllerTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------ | -------------- | ------------------ | ---------- |
| testGetInformation | 正确的商店id | 得到商店详情 | ***通过*** |
| testGetAllProducts | 正确的商店id | 得到商店的商品列表 | ***通过*** |
| testCreateStore | 正确的商店信息 | 返回创建成功 | ***通过*** |
| testGetAllStore | 无 | 返回所有商店列表 | ***通过*** |
**测试结果截图**

#### 4.2.3 商品模块测试
**ProductControllerTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------ | ------------------------ | ---------------------- | ---------- |
| testGetInformation | 商品id | 得到商品详情 | ***通过*** |
| testSetCurrentNum | 商品id | 返回修改成功 | ***通过*** |
| testCreateProduct | 正确的商品信息 | 返回创建成功 | ***通过*** |
| testGetComment | 商品id | 返回商品的评论列表 | ***通过*** |
| testFind | 商品名称,类别,价格区间 | 返回符合条件的商品列表 | ***通过*** |
**测试结果截图**

#### 4.2.4 订单模块测试
**OrderControllerTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ----------------- | ------------------------ | ------------------------------------ | ---------- |
| testGetAllOrders | 用户id,用户类型 | 得到用户的所有相关订单 | ***通过*** |
| testCreateOrder | 正确的订单信息 | 返回创建订单id | ***通过*** |
| testPay | 订单id,优惠券id | 返回的form是一个String类型的html页面 | ***通过*** |
| testSend | 订单id | 返回发货成功 | ***通过*** |
| testGetProduct | 订单id | 返回收货成功 | ***通过*** |
| testEvaluateOrder | 订单id,评分和评论详情 | 返回评论成功 | ***通过*** |
| testGetOrderInfo | 订单id | 得到订单详情 | ***通过*** |
| testGetAllSheet | 经理查看所有报表 | 得到所有报表的下载链接 | ***通过*** |
| testGetStoreSheet | 商店管理人员查看商店报表 | 得到商店报表的下载链接 | ***通过*** |
**测试结果截图**

#### 4.2.5 优惠券模块测试
**CouponControllerTests**
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ---------------------- | ------------------ | ------------------ | ---------- |
| testCollectCoupon | 优惠券组id | 返回领取优惠券成功 | ***通过*** |
| testGetAllAvailCoupons | 订单id | 得到所有可用优惠券 | ***通过*** |
| testSelectCoupon | 订单id,优惠券id | 返回预计金额 | ***通过*** |
| testGetCouponGroups | 商店id | 得到商店的优惠券组 | ***通过*** |
| testCreateCouponGroup | 正确的优惠券组信息 | 返回创建成功 | ***通过*** |
**测试结果截图**

## 5. 功能测试
### 5.1 用户可以登录、注册、查看与修改个人信息
#### 5.1.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------------- | ------------------------------------ | ---------------------- | ---------- |
| testLogin | 在登陆界面输入正确的账号密码点击登录 | 进入商店界面 | ***通过*** |
| testRegister | 在注册界面输入正确的信息点击注册 | 注册成功并返回登陆界面 | ***通过*** |
| testViewInformation | 在商店界面点击导航栏中的个人信息按钮 | 进入个人信息界面 | ***通过*** |
| testChangeInformation | 在个人信息界面输入正确的信息点击更新 | 个人信息修改成功 | ***通过*** |
#### 5.1.2 结果截图
**testLogin:**


**testRegister:**


**testViewInformation:**

**testChangeInformation:**


### 5.2 商场管理人员可以创建商店
#### 5.2.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------- | ---------------------------------- | ------------ | ---------- |
| testCreateStore | 在创建商店界面输入正确信息点击创建 | 创建商店成功 | ***通过*** |
#### 5.2.2 结果截图
**testCreateStore:**


### 5.3 用户可以查看商店信息
#### 5.3.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ---------------- | ------------------ | ------------ | ---------- |
| testViewAllStore | 点击导航栏主页按钮 | 展示所有商店 | ***通过*** |
#### 5.3.2 结果截图
**testViewAllStore:**

### 5.4 门店工作人员可以创建商品、添加库存
#### 5.4.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ----------------- | -------------------------------------------------- | ------------ | ---------- |
| testCreateProduct | 在创建商品界面输入正确信息点击创建 | 创建商品成功 | ***通过*** |
| testChangeNumber | 在商品详情界面点击更改商品库存并输入更改后的库存数 | 库存修改成功 | ***通过*** |
#### 5.4.2 结果截图
**testCreateProduct:**


**testChangeNumber:**


### 5.5 用户可以查看商店下的所有商品
#### 5.5.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| -------------------- | -------- | ---------------- | ---------- |
| testViewStoreProduct | 点击商店 | 展示商店所有商品 | ***通过*** |
#### 5.5.2 结果截图
**testViewStoreProduct:**

### 5.6 用户可以根据关键词搜索商品
#### 5.6.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ----------------- | ---------------------- | ---------------- | ---------- |
| testSearchProduct | 在搜索界面输入正确信息 | 展示所有预期商品 | ***通过*** |
#### 5.6.2 结果截图
**testSearchProduct:**


### 5.7 顾客可以创建并支付订单
#### 5.7.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------- | -------------------------------------- | -------------------------- | ---------- |
| testCreateOrder | 在商品界面点击购买商品,并点击创建订单 | 订单完成创建 | ***通过*** |
| testPayOrder1 | 在创建订单之后直接支付 | 跳入支付宝支付界面完成支付 | ***通过*** |
| testPayOrder2 | 在查看订单界面点击支付订单 | 跳入支付宝支付界面完成支付 | ***通过*** |
#### 5.7.2 结果截图
**testCreateOrder:**


**testPayOrder1:**




**testPayOrder2:**



### 5.8 门店工作人员可以进行订单发货
#### 5.8.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| -------- | ------------------ | -------- | ---------- |
| testSend | 在订单界面点击发货 | 成功发货 | ***通过*** |
#### 5.8.2 结果截图
**testSend:**


### 5.9 顾客可以确认收货并进行评价
#### 5.9.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------- | ---------------------- | -------- | ---------- |
| testReceive | 在订单界面点击确认收货 | 成功收货 | ***通过*** |
| testSendComment | 在订单界面点击去评价 | 成功评价 | ***通过*** |
#### 5.9.2 结果截图
testReceive:


testSendComment:


### 5.10 用户可以查看商品的评论区
#### 5.10.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------- | ------------------------ | -------- | ---------- |
| testReadComment | 在商品界面查看评价和评分 | 可以查看 | ***通过*** |
#### 5.10.2 结果截图
testReadComment:

### 5.11 经理可以查看所有订单的报表
#### 5.11.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ----------------- | ---------------------- | ---------------- | ---------- |
| testReadTable_CEO | 在订单界面点击下载报表 | 下载成功并可查看 | ***通过*** |
#### 5.11.2 结果截图
testReadTable_CEO:



### 5.12 门店工作人员可以查看本门店的报表
#### 5.12.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------- | ---------------------- | ---------------- | ---------- |
| testReadTable_staff | 在订单界面点击下载报表 | 下载成功并可查看 | ***通过*** |
#### 5.12.2 结果截图
testReadTable_staff:



### 5.13 经理可以发布全局优惠券组,查看优惠券组信息
#### 5.13.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ---------------------- | -------------------------- | -------------------------- | ---------- |
| testHandOutCoupon_CEO | 在优惠券界面点击创建优惠券 | 点击可选择数量、种类并添加 | ***通过*** |
| testReadCouponInfo_CEO | 在优惠券界面查看优惠券组 | 可查看优惠券组信息 | ***通过*** |
#### 5.13.2 结果截图
testHandOutCoupon_CEO:

testReadCouponInfo_CEO:

### 5.14 门店工作人员可以发布本门店内的优惠券组,查看优惠券组信息
#### 5.14.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------------------ | -------------------------- | -------------------------- | ---------- |
| testHandOutCoupon_staff | 在优惠券界面点击创建优惠券 | 点击可选择数量、种类并添加 | ***通过*** |
| testReadCouponInfo_staff | 在优惠券界面查看优惠券组 | 可查看优惠券组信息 | ***通过*** |
#### 5.14.2 结果截图
testHandOutCoupon_staff:

testReadCouponInfo_staff:

### 5.15 顾客可以领取并查看优惠券
#### 5.14.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| --------------------------- | -------------------------- | -------------------------- | ---------- |
| testGetCoupon | 在优惠券界面点击获取优惠券 | 点击可选择数量、种类并获取 | ***通过*** |
| testReadCouponInfo_customer | 在优惠券界面查看优惠券组 | 可查看优惠券组信息 | ***通过*** |
#### 5.14.2 结果截图
testGetCoupon:

testReadCouponInfo_customer:

### 5.16 顾客可以在支付时使用优惠券
#### 5.14.1 结果总结
| 测试名称 | 条件 | 预期结果 | 测试结果 |
| ------------- | ---------------------------- | ------------------------ | ---------- |
| testUseCoupon | 在订单确认界面点击获取优惠券 | 点击可选择可使用的优惠券 | ***通过*** |
#### 5.14.2 结果截图
testGetCoupon:


## 6. 测试总结
## 7. 附录
### 7.1 单元测试代码
**UserServiceTests.java**
```java
package com.seecoder.BlueWhale.serviceTests;
import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.serviceImpl.UserServiceImpl;
import com.seecoder.BlueWhale.util.SecurityUtil;
import com.seecoder.BlueWhale.util.TokenUtil;
import com.seecoder.BlueWhale.vo.UserVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
public class UserServiceTests {
@Mock
private UserRepository userRepository;
@Mock
private TokenUtil tokenUtil;
@Mock
private SecurityUtil securityUtil;
@InjectMocks
private UserServiceImpl userService;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testRegister_Success() {
UserVO userVO = new UserVO();
userVO.setPhone("1234567890");
when(userRepository.findByPhone(userVO.getPhone())).thenReturn(null);
assertTrue(userService.register(userVO));
verify(userRepository, times(1)).save(any(User.class));
}
@Test
void testRegister_PhoneAlreadyExists() {
UserVO userVO = new UserVO();
userVO.setPhone("1234567890");
User existingUser = new User();
existingUser.setPhone("1234567890");
when(userRepository.findByPhone(userVO.getPhone())).thenReturn(existingUser);
assertThrows(BlueWhaleException.class, () -> userService.register(userVO));
}
@Test
void testLogin_Success() {
String phone = "1234567890";
String password = "password";
User user = new User();
user.setPhone(phone);
user.setPassword(password);
when(userRepository.findByPhoneAndPassword(phone, password)).thenReturn(user);
when(tokenUtil.getToken(user)).thenReturn("mockToken");
String token = userService.login(phone, password);
assertEquals("mockToken", token);
}
@Test
void testLogin_PhoneOrPasswordError() {
String phone = "1234567890";
String password = "password";
when(userRepository.findByPhoneAndPassword(phone, password)).thenReturn(null);
assertThrows(BlueWhaleException.class, () -> userService.login(phone, password));
}
@Test
void testGetInformation() {
User user = new User();
user.setPhone("1234567890");
when(securityUtil.getCurrentUser()).thenReturn(user);
UserVO userVO = userService.getInformation();
assertNotNull(userVO);
assertEquals(user.getPhone(), userVO.getPhone());
}
@Test
void testUpdateInformation() {
User user = new User();
user.setPhone("1234567890");
when(securityUtil.getCurrentUser()).thenReturn(user);
UserVO userVO = new UserVO();
userVO.setPassword("newPassword");
userVO.setName("newName");
userVO.setAddress("newAddress");
assertTrue(userService.updateInformation(userVO));
verify(userRepository, times(1)).save(user);
assertEquals("newPassword", user.getPassword());
assertEquals("newName", user.getName());
assertEquals("newAddress", user.getAddress());
}
}
```
**StoreServiceTests.java**
```java
package com.seecoder.BlueWhale.serviceTests;
import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.Product;
import com.seecoder.BlueWhale.po.Store;
import com.seecoder.BlueWhale.repository.ProductRepository;
import com.seecoder.BlueWhale.repository.StoreRepository;
import com.seecoder.BlueWhale.serviceImpl.StoreServiceImpl;
import com.seecoder.BlueWhale.vo.ProductVO;
import com.seecoder.BlueWhale.vo.StoreVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
public class StoreServiceTests {
@Mock
private StoreRepository storeRepository;
@Mock
private ProductRepository productRepository;
@InjectMocks
private StoreServiceImpl storeService;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testGetInformation_Success() {
Integer storeId = 1;
Store store = new Store();
store.setId(storeId);
store.setName("Test Store");
when(storeRepository.findById(storeId)).thenReturn(Optional.of(store));
StoreVO storeVO = storeService.getInformation(storeId);
assertNotNull(storeVO);
assertEquals(storeId, storeVO.getId());
assertEquals("Test Store", storeVO.getName());
}
@Test
void testGetInformation_StoreNotFound() {
Integer storeId = 1;
when(storeRepository.findById(storeId)).thenReturn(Optional.empty());
assertThrows(BlueWhaleException.class, () -> storeService.getInformation(storeId));
}
@Test
void testGetAllProducts_Success() {
Integer storeId = 1;
List<Product> products = Arrays.asList(new Product(), new Product());
when(productRepository.findAllByStoreId(storeId)).thenReturn(products);
List<ProductVO> productVOs = storeService.getAllProducts(storeId);
assertNotNull(productVOs);
assertEquals(2, productVOs.size());
}
@Test
void testGetAllProducts_NoProducts() {
Integer storeId = 1;
when(productRepository.findAllByStoreId(storeId)).thenReturn(Collections.emptyList());
List<ProductVO> productVOs = storeService.getAllProducts(storeId);
assertNotNull(productVOs);
assertTrue(productVOs.isEmpty());
}
@Test
void testCreateStore_Success() {
StoreVO storeVO = new StoreVO();
storeVO.setName("New Store");
when(storeRepository.save(any(Store.class))).thenReturn(new Store());
Boolean result = storeService.createStore(storeVO);
assertTrue(result);
verify(storeRepository, times(1)).save(any(Store.class));
}
@Test
void testCreateStore_Exception() {
StoreVO storeVO = new StoreVO();
storeVO.setName("New Store");
when(storeRepository.save(any(Store.class))).thenThrow(new RuntimeException());
assertThrows(RuntimeException.class, () -> storeService.createStore(storeVO));
}
@Test
void testGetAllStore_Success() {
List<Store> stores = Arrays.asList(new Store(), new Store());
when(storeRepository.findAll()).thenReturn(stores);
List<StoreVO> storeVOs = storeService.getAllStore();
assertNotNull(storeVOs);
assertEquals(2, storeVOs.size());
}
@Test
void testGetAllStore_NoStores() {
when(storeRepository.findAll()).thenReturn(Collections.emptyList());
List<StoreVO> storeVOs = storeService.getAllStore();
assertNotNull(storeVOs);
assertTrue(storeVOs.isEmpty());
}
}
```
**ProductServiceTests.java**
```java
package com.seecoder.BlueWhale.serviceTests;
import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.Product;
import com.seecoder.BlueWhale.po.Order;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.OrderRepository;
import com.seecoder.BlueWhale.repository.ProductRepository;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.serviceImpl.ProductServiceImpl;
import com.seecoder.BlueWhale.vo.CommentVO;
import com.seecoder.BlueWhale.vo.ProductVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
public class ProductServiceTests {
@Mock
private ProductRepository productRepository;
@Mock
private OrderRepository orderRepository;
@Mock
private UserRepository userRepository;
@InjectMocks
private ProductServiceImpl productService;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testGetInformation_Success() {
Integer productId = 1;
Product product = new Product();
product.setId(productId);
product.setName("Test Product");
when(productRepository.findById(productId)).thenReturn(Optional.of(product));
ProductVO productVO = productService.getInformation(productId);
assertNotNull(productVO);
assertEquals(productId, productVO.getId());
assertEquals("Test Product", productVO.getName());
}
@Test
void testGetInformation_ProductNotFound() {
Integer productId = 1;
when(productRepository.findById(productId)).thenReturn(Optional.empty());
assertThrows(BlueWhaleException.class, () -> productService.getInformation(productId));
}
@Test
void testSetCurrentNum_Success() {
ProductVO productVO = new ProductVO();
productVO.setId(1);
productVO.setCurrentNum(50);
Product product = new Product();
product.setId(1);
when(productRepository.findById(productVO.getId())).thenReturn(Optional.of(product));
when(productRepository.save(any(Product.class))).thenReturn(product);
Boolean result = productService.setCurrentNum(productVO);
assertTrue(result);
verify(productRepository, times(1)).save(product);
}
@Test
void testSetCurrentNum_ProductNotFound() {
ProductVO productVO = new ProductVO();
productVO.setId(1);
productVO.setCurrentNum(50);
when(productRepository.findById(productVO.getId())).thenReturn(Optional.empty());
assertThrows(BlueWhaleException.class, () -> productService.setCurrentNum(productVO));
}
@Test
void testCreateProduct_Success() {
ProductVO productVO = new ProductVO();
productVO.setName("New Product");
when(productRepository.save(any(Product.class))).thenReturn(new Product());
Boolean result = productService.createProduct(productVO);
assertTrue(result);
verify(productRepository, times(1)).save(any(Product.class));
}
@Test
void testCreateProduct_Exception() {
ProductVO productVO = new ProductVO();
productVO.setName("New Product");
when(productRepository.save(any(Product.class))).thenThrow(new RuntimeException());
assertThrows(RuntimeException.class, () -> productService.createProduct(productVO));
}
@Test
void testGetComment_Success() {
Integer productId = 1;
Order order1 = new Order();
order1.setId(1);
order1.setProductId(productId);
order1.setRating(4.0);
order1.setComment("Good product");
order1.setUserId(1);
Order order2 = new Order();
order2.setId(2);
order2.setProductId(productId);
order2.setRating(5.0);
order2.setComment("Excellent product");
order2.setUserId(2);
User user1 = new User();
user1.setId(1);
user1.setName("User One");
User user2 = new User();
user2.setId(2);
user2.setName("User Two");
when(orderRepository.findByProductIdAndFinishTimeNotNull(productId)).thenReturn(Arrays.asList(order1, order2));
when(userRepository.findById(1)).thenReturn(Optional.of(user1));
when(userRepository.findById(2)).thenReturn(Optional.of(user2));
List<CommentVO> commentVOs = productService.getComment(productId);
assertNotNull(commentVOs);
assertEquals(2, commentVOs.size());
assertEquals("User One", commentVOs.get(0).getUserName());
assertEquals("User Two", commentVOs.get(1).getUserName());
}
@Test
void testGetComment_NoComments() {
Integer productId = 1;
when(orderRepository.findByProductIdAndFinishTimeNotNull(productId)).thenReturn(Collections.emptyList());
List<CommentVO> commentVOs = productService.getComment(productId);
assertNotNull(commentVOs);
assertTrue(commentVOs.isEmpty());
}
@Test
void testFind_Success() {
String name = "Product";
String category = "FOOD";
Double highPrice = 100.0;
Double lowPrice = 10.0;
List<Product> products = Arrays.asList(new Product(), new Product());
when(productRepository.findProductsByNameAndCategory(name, category, highPrice, lowPrice)).thenReturn(products);
List<ProductVO> productVOs = productService.find(name, category, highPrice, lowPrice);
assertNotNull(productVOs);
assertEquals(2, productVOs.size());
}
@Test
void testFind_NoProducts() {
String name = "NoExistingProduct";
String category = "Category";
Double highPrice = 100.0;
Double lowPrice = 10.0;
when(productRepository.findProductsByNameAndCategory(name, category, highPrice, lowPrice)).thenReturn(Collections.emptyList());
List<ProductVO> productVOs = productService.find(name, category, highPrice, lowPrice);
assertNotNull(productVOs);
assertTrue(productVOs.isEmpty());
}
}
```
**OrderServiceTests.java**
```java
package com.seecoder.BlueWhale.serviceTests;
import com.seecoder.BlueWhale.po.*;
import com.seecoder.BlueWhale.repository.*;
import com.seecoder.BlueWhale.serviceImpl.OrderServiceImpl;
import com.seecoder.BlueWhale.vo.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
public class OrderServiceTests {
@Mock
private OrderRepository orderRepository;
@Mock
private CouponRepository couponRepository;
@Mock
private ProductRepository productRepository;
@InjectMocks
private OrderServiceImpl orderService;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testGetAllOrders_Success() {
Integer userId = 1;
String role = "CUSTOMER";
List<Order> orders = Arrays.asList(new Order(), new Order());
when(orderRepository.findAllByUserId(userId)).thenReturn(orders);
List<OrderVO> orderVOs = orderService.getAllOrders(userId, role);
assertNotNull(orderVOs);
assertEquals(2, orderVOs.size());
}
@Test
void testCreateOrder_Success() {
OrderVO orderVO = new OrderVO();
orderVO.setId(1);
orderVO.setUserId(1);
orderVO.setProductId(1);
orderVO.setSalesNum(1);
Order order = new Order();
order.setId(1);
Product product = new Product();
product.setId(1);
product.setPrice(10.0);
when(productRepository.findById(orderVO.getProductId())).thenReturn(Optional.of(product));
when(orderRepository.save(any(Order.class))).thenReturn(order);
Integer result = orderService.createOrder(orderVO);
assertNotNull(result);
assertEquals(order.getId(), result);
}
@Test
void testPaySuccess_Success() {
Integer orderId = 1;
Double actualPrice = 90.0;
Order order = new Order();
order.setId(orderId);
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
orderService.paySuccess(orderId, actualPrice);
verify(orderRepository, times(1)).save(order);
}
@Test
void testSend_Success() {
Integer orderId = 1;
Order order = new Order();
order.setId(orderId);
order.setProductId(1);
order.setSalesNum(1);
Product product = new Product();
product.setId(1);
product.setCurrentNum(10);
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
when(productRepository.findById(order.getProductId())).thenReturn(Optional.of(product));
Boolean result = orderService.send(orderId);
assertTrue(result);
verify(orderRepository, times(1)).save(order);
}
@Test
void testGetProduct_Success() {
Integer orderId = 1;
Order order = new Order();
order.setId(orderId);
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
Boolean result = orderService.getProduct(orderId);
assertTrue(result);
verify(orderRepository, times(1)).save(order);
}
@Test
void testGetOrderInfo_Success() {
Integer orderId = 1;
Order order = new Order();
order.setId(orderId);
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
OrderVO result = orderService.getOrderInfo(orderId);
assertNotNull(result);
assertEquals(orderId, result.getId());
}
}
```
**CouponServiceTests.java**
```java
package com.seecoder.BlueWhale.serviceTests;
import com.seecoder.BlueWhale.po.*;
import com.seecoder.BlueWhale.repository.*;
import com.seecoder.BlueWhale.serviceImpl.CouponServiceImpl;
import com.seecoder.BlueWhale.util.SecurityUtil;
import com.seecoder.BlueWhale.enums.CouponTypeEnum;
import com.seecoder.BlueWhale.enums.RoleEnum;
import com.seecoder.BlueWhale.vo.CouponGroupVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
public class CouponServiceTests {
@Mock
private CouponRepository couponRepository;
@Mock
private OrderRepository orderRepository;
@Mock
SecurityUtil securityUtil;
@Mock
private CouponGroupRepository couponGroupRepository;
@InjectMocks
private CouponServiceImpl couponService;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testSelectCoupon_Success() {
Integer couponId = 1;
Integer orderId = 1;
Coupon coupon = new Coupon();
coupon.setCouponGroupId(1);
when(couponRepository.findById(couponId)).thenReturn(Optional.of(coupon));
Order order = new Order();
order.setTotalPrice(100.0);
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
CouponGroup couponGroup = new CouponGroup();
couponGroup.setCouponType(CouponTypeEnum.FULL_REDUCTION);
couponGroup.setFullNum(50.0);
couponGroup.setReduceNum(10.0);
when(couponGroupRepository.findById(coupon.getCouponGroupId())).thenReturn(Optional.of(couponGroup));
Double result = couponService.selectCoupon(couponId, orderId);
assertEquals(90.0, result);
}
@Test
void testUseCoupon_Success() {
Integer couponId = 1;
Integer orderId = 1;
Coupon coupon = new Coupon();
coupon.setCouponGroupId(1);
coupon.setIsUsed(false);
when(couponRepository.findById(couponId)).thenReturn(Optional.of(coupon));
Order order = new Order();
order.setTotalPrice(100.0);
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
CouponGroup couponGroup = new CouponGroup();
couponGroup.setCouponType(CouponTypeEnum.FULL_REDUCTION);
couponGroup.setFullNum(50.0);
couponGroup.setReduceNum(10.0);
when(couponGroupRepository.findById(coupon.getCouponGroupId())).thenReturn(Optional.of(couponGroup));
Double result = couponService.useCoupon(couponId, orderId);
assertEquals(90.0, result);
verify(couponRepository, times(1)).save(coupon);
}
@Test
void testGetCouponGroups_Success() {
Integer storeId = 1;
User user = new User();
user.setRole(RoleEnum.CEO);
when(securityUtil.getCurrentUser()).thenReturn(user);
List<CouponGroup> couponGroups = Arrays.asList(new CouponGroup(), new CouponGroup());
when(couponGroupRepository.findAll()).thenReturn(couponGroups);
List<CouponGroupVO> result = couponService.getCouponGroups(storeId);
assertNotNull(result);
assertFalse(result.isEmpty());
}
@Test
void testCreateCouponGroup_Success() {
CouponGroupVO couponGroupVO = new CouponGroupVO();
couponGroupVO.setLastCount(10);
CouponGroup couponGroup = couponGroupVO.toPO();
couponGroup.setUsedCount(0);
when(couponGroupRepository.save(any(CouponGroup.class))).thenReturn(couponGroup);
Boolean result = couponService.createCouponGroup(couponGroupVO);
assertTrue(result);
verify(couponRepository, times(10)).save(any(Coupon.class));
}
@Test
void testCreateCouponGroup_Exception() {
CouponGroupVO couponGroupVO = new CouponGroupVO();
when(couponGroupRepository.save(any(CouponGroup.class))).thenThrow(new RuntimeException());
assertThrows(RuntimeException.class, () -> couponService.createCouponGroup(couponGroupVO));
}
}
```
### 7.2 集成测试代码
**UserControllerTests.java**
```java
package com.seecoder.BlueWhale.controllerTests;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.service.UserService;
import com.seecoder.BlueWhale.util.TokenUtil;
import com.seecoder.BlueWhale.vo.UserVO;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private TokenUtil tokenUtil;
@Autowired
UserRepository userRepository;
@Test
public void testRegister() throws Exception {
UserVO userVO = new UserVO();
userVO.setPhone("12345678912");
userVO.setPassword("123456");
String json = "{\"phone\":\"12345678912\",\"password\":\"123456\"}";
mockMvc.perform(MockMvcRequestBuilders
.post("/api/users/register")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print());
}
@Test
public void testLogin() throws Exception {
String phone = "12345678901";
String password = "123456";
mockMvc.perform(MockMvcRequestBuilders
.post("/api/users/login")
.param("phone", phone)
.param("password", password))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print());
}
@Test
public void testGetInformation() throws Exception {
UserVO userVO = new UserVO();
User user = new User();
user.setId(1);
user.setPassword("123456");
String token = tokenUtil.getToken(user);
mockMvc.perform(MockMvcRequestBuilders
.get("/api/users")
.header("token", token)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print());
}
@Test
public void testUpdateInformation() throws Exception {
UserVO userVO = new UserVO();
userVO.setPhone("12345678912");
userVO.setPassword("123456");
User user = userRepository.findByPhone(userVO.getPhone());
String token = tokenUtil.getToken(user);
String json = "{\"phone\":\"12345678901\",\"password\":\"123456\"}";
mockMvc.perform(MockMvcRequestBuilders
.post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.header("token", token))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print());
}
}
```
**StoreControllerTests.java**
```java
package com.seecoder.BlueWhale.controllerTests;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.util.TokenUtil;
import com.seecoder.BlueWhale.vo.StoreVO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class StoreContollerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private UserRepository userRepository;
@Autowired
private TokenUtil tokenUtil;
String tokenCustomer;
String tokenStaff;
@Before
public void setUp() throws Exception {
String phoneCustomer = "15664278996";
User userCustomer = userRepository.findByPhone(phoneCustomer);
tokenCustomer = tokenUtil.getToken(userCustomer);
String phoneStaff = "15555555555";
User userStaff = userRepository.findByPhone(phoneStaff);
tokenStaff = tokenUtil.getToken(userStaff);
}
@Test
public void testGetInformation() throws Exception {
Integer storeId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/stores/detail/getInfo")
.param("id", storeId.toString())
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").exists())
.andDo(print());
}
@Test
public void testGetAllProducts() throws Exception {
Integer storeId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/stores/detail/getAllProducts")
.param("id", storeId.toString())
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
@Test
public void testCreateStore() throws Exception {
StoreVO storeVO = new StoreVO();
storeVO.setName("Test Store");
storeVO.setAddress("Test Address");
String json = objectMapper.writeValueAsString(storeVO);
mockMvc.perform(MockMvcRequestBuilders
.post("/api/stores/allStore/createStore")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
//.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testGetAllStore() throws Exception {
mockMvc.perform(MockMvcRequestBuilders
.get("/api/stores/allStore")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
}
```
**ProductControllerTests.java**
```java
package com.seecoder.BlueWhale.controllerTests;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecoder.BlueWhale.BlueWhaleApplication;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.util.TokenUtil;
import com.seecoder.BlueWhale.vo.CommentVO;
import com.seecoder.BlueWhale.vo.ProductVO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Collections;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class ProductControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private UserRepository userRepository;
@Autowired
private TokenUtil tokenUtil;
String tokenCustomer;
String tokenStaff;
@Before
public void setUp() throws Exception {
String phoneCustomer = "15664278996";
User userCustomer = userRepository.findByPhone(phoneCustomer);
tokenCustomer = tokenUtil.getToken(userCustomer);
String phoneStaff = "15555555555";
User userStaff = userRepository.findByPhone(phoneStaff);
tokenStaff = tokenUtil.getToken(userStaff);
}
@Test
public void testGetInformation() throws Exception {
Integer productId = 2;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/products/detail/getInfo")
.param("id", productId.toString())
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").exists())
.andDo(print());
}
@Test
public void testSetCurrentNum() throws Exception {
ProductVO productVO = new ProductVO();
productVO.setId(2);
productVO.setCurrentNum(100);
String json = objectMapper.writeValueAsString(productVO);
mockMvc.perform(MockMvcRequestBuilders
.post("/api/products/detail/setCurrentNum")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testCreateProduct() throws Exception {
ProductVO productVO = new ProductVO();
productVO.setName("Test Product");
productVO.setPrice(99.99);
productVO.setCurrentNum(100);
String json = objectMapper.writeValueAsString(productVO);
mockMvc.perform(MockMvcRequestBuilders
.post("/api/products/createProduct")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testGetComment() throws Exception {
Integer productId = 2;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/products/getComment")
.param("id", productId.toString())
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
@Test
public void testFind() throws Exception {
MultiValueMap<String, String> requestParam = new LinkedMultiValueMap();
requestParam.add("name", "test");
requestParam.add("category", "");
requestParam.add("highPrice", "200.0");
requestParam.add("lowPrice", "50.0");
mockMvc.perform(MockMvcRequestBuilders
.get("/api/products/find")
.params(requestParam)
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
}
```
**OrderControllerTests.java**
```java
package com.seecoder.BlueWhale.controllerTests;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecoder.BlueWhale.BlueWhaleApplication;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.util.TokenUtil;
import com.seecoder.BlueWhale.vo.OrderVO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.util.Collections;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class OrderControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private UserRepository userRepository;
@Autowired
private TokenUtil tokenUtil;
private String tokenCustomer;
private String tokenStaff;
@Before
public void setUp() throws Exception {
String phoneCustomer = "15664278996";
User userCustomer = userRepository.findByPhone(phoneCustomer);
tokenCustomer = tokenUtil.getToken(userCustomer);
String phoneStaff = "15555555555";
User userStaff = userRepository.findByPhone(phoneStaff);
tokenStaff = tokenUtil.getToken(userStaff);
}
@Test
public void testGetAllOrders() throws Exception {
User userCustomer = userRepository.findByPhone("15664278996");
Integer userId = userCustomer.getId();
String role = userCustomer.getRole().toString();
mockMvc.perform(MockMvcRequestBuilders
.get("/api/orders/allOrder/{id}", userId)
.param("role", role)
.header("token", tokenCustomer)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
@Test
public void testCreateOrder() throws Exception {
User userCustomer = userRepository.findByPhone("15664278996");
OrderVO orderVO = new OrderVO();
orderVO.setProductId(2);
orderVO.setStoreId(1);
orderVO.setUserId(userCustomer.getId());
orderVO.setSalesNum(2);
String json = objectMapper.writeValueAsString(orderVO);
mockMvc.perform(MockMvcRequestBuilders
.post("/api/orders/createOrder")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isNumber())
.andDo(print());
}
@Test
public void testPay() throws Exception {
Integer orderId = 1;
Integer couponId = 4;
mockMvc.perform(MockMvcRequestBuilders
.post("/api/orders/pay")
.param("orderId", orderId.toString())
.param("couponId", couponId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isString())
.andDo(print());
}
@Test
public void testSend() throws Exception {
Integer orderId = 1;
mockMvc.perform(MockMvcRequestBuilders
.post("/api/orders/send")
.param("id", orderId.toString())
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testGetProduct() throws Exception {
Integer orderId = 1;
mockMvc.perform(MockMvcRequestBuilders
.post("/api/orders/getProduct")
.param("id", orderId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testEvaluateOrder() throws Exception {
Integer orderId = 1;
Double rating = 4.5;
String comment = "Great product!";
mockMvc.perform(MockMvcRequestBuilders
.post("/api/orders/comment/{id}", orderId)
.param("rating", rating.toString())
.param("comment", comment)
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testGetOrderInfo() throws Exception {
Integer orderId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/orders/getOrderInfo")
.param("id", orderId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").exists())
.andDo(print());
}
@Test
public void testGetAllSheet() throws Exception {
mockMvc.perform(MockMvcRequestBuilders
.get("/api/orders/getAllSheet")
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isString())
.andDo(print());
}
@Test
public void testGetStoreSheet() throws Exception {
Integer storeId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/orders/getStoreSheet")
.param("id", storeId.toString())
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isString())
.andDo(print());
}
}
```
**CouponControllerTests.java**
```java
package com.seecoder.BlueWhale.controllerTests;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecoder.BlueWhale.enums.CouponTypeEnum;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.repository.UserRepository;
import com.seecoder.BlueWhale.util.TokenUtil;
import com.seecoder.BlueWhale.vo.CouponGroupVO;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class CouponControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private UserRepository userRepository;
@Autowired
private TokenUtil tokenUtil;
private String tokenCustomer;
private String tokenStaff;
@Before
public void setUp() throws Exception {
String phoneCustomer = "15664278996";
User userCustomer = userRepository.findByPhone(phoneCustomer);
tokenCustomer = tokenUtil.getToken(userCustomer);
String phoneStaff = "15555555555";
User userStaff = userRepository.findByPhone(phoneStaff);
tokenStaff = tokenUtil.getToken(userStaff);
}
@Test
public void testCollectCoupon() throws Exception {
Integer couponGroupId = 9;
mockMvc.perform(MockMvcRequestBuilders
.post("/api/coupons/collectCoupon")
.param("couponGroupId", couponGroupId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
@Test
public void testGetAllAvailCoupons() throws Exception {
Integer orderId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/coupons/getAllAvailCoupons")
.param("orderId", orderId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
@Test
public void testSelectCoupon() throws Exception {
Integer couponId = 5;
Integer orderId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/coupons/selectCoupon")
.param("couponId", couponId.toString())
.param("orderId", orderId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isNumber())
.andDo(print());
}
@Test
public void testGetCouponGroups() throws Exception {
Integer storeId = 1;
mockMvc.perform(MockMvcRequestBuilders
.get("/api/coupons/getCouponGroups")
.param("storeId", storeId.toString())
.header("token", tokenCustomer))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").isArray())
.andDo(print());
}
@Test
public void testCreateCouponGroup() throws Exception {
CouponGroupVO couponGroupVO = new CouponGroupVO();
couponGroupVO.setStoreId(1);
couponGroupVO.setCouponType(CouponTypeEnum.FULL_REDUCTION);
couponGroupVO.setFullNum(200.0);
couponGroupVO.setReduceNum(20.0);
couponGroupVO.setLastCount(20);
String json = objectMapper.writeValueAsString(couponGroupVO);
mockMvc.perform(MockMvcRequestBuilders
.post("/api/coupons/createCouponGroup")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.header("token", tokenStaff))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.result").value(true))
.andDo(print());
}
}
```