Merge "correct notification, add community" into main
diff --git a/src/main/java/com/g9/g9backend/controller/ResourceController.java b/src/main/java/com/g9/g9backend/controller/ResourceController.java
index b01898d..c9a573c 100644
--- a/src/main/java/com/g9/g9backend/controller/ResourceController.java
+++ b/src/main/java/com/g9/g9backend/controller/ResourceController.java
@@ -1,9 +1,19 @@
package com.g9.g9backend.controller;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.g9.g9backend.mapper.UserPurchaseMapper;
+import com.g9.g9backend.pojo.*;
+import com.g9.g9backend.pojo.DTO.*;
+import com.g9.g9backend.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
+import java.util.Date;
+
/**
* ResourceController 资源控制器类,处理与资源相关的请求
@@ -14,5 +24,264 @@
@RequestMapping("/resource")
public class ResourceController {
+ private final ResourceService resourceService;
+
+ private final GameplayService gameplayService;
+
+ private final RewardService rewardService;
+
+ private final UserUploadService userUploadService;
+
+ private final CommunityService communityService;
+
+ private final UserService userService;
+
+ private final UserPurchaseService userPurchaseService;
+
+ private final UserLikeService userLikeService;
+
+ private final UserCollectionService userCollectionService;
+
+ private final NotificationService notificationService;
+
+ public ResourceController(ResourceService resourceService, GameplayService gameplayService, RewardService rewardService, UserUploadService userUploadService, CommunityService communityService, UserService userService, UserPurchaseMapper userPurchaseMapper, UserPurchaseService userPurchaseService, UserLikeService userLikeService, UserCollectionService userCollectionService, NotificationService notificationService) {
+ this.resourceService = resourceService;
+ this.gameplayService = gameplayService;
+ this.rewardService = rewardService;
+ this.userUploadService = userUploadService;
+ this.communityService = communityService;
+ this.userService = userService;
+ this.userPurchaseService = userPurchaseService;
+ this.userLikeService = userLikeService;
+ this.userCollectionService = userCollectionService;
+ this.notificationService = notificationService;
+ }
+
private final Logger logger = LoggerFactory.getLogger(ResourceController.class);
-}
+
+ /**
+ * 上传资源
+ *
+ * @param postResourceDTO 上传资源信息
+ * @return 上传资源结果
+ */
+ @PostMapping
+ public ResponseEntity<String> uploadResource(@RequestBody PostResourceDTO postResourceDTO) {
+ // 存资源
+ Resource resource = postResourceDTO.getResource();
+ resourceService.save(resource);
+ // 存玩法列表
+ String[] gameplayList = postResourceDTO.getGameplayList();
+ for (String gameplayName : gameplayList) {
+ Gameplay gameplay = new Gameplay();
+ gameplay.setGameplayName(gameplayName);
+ gameplay.setResourceId(postResourceDTO.getResource().getResourceId());
+ gameplayService.save(gameplay);
+ }
+ // 完成对应悬赏
+ if (postResourceDTO.getCompleteRewardId() != 0) {
+ UpdateWrapper<Reward> rewardUpdate = new UpdateWrapper<>();
+ rewardUpdate.eq("reward_id", postResourceDTO.getCompleteRewardId()).set("completed_by", postResourceDTO.getUserId()).set("completed_at", postResourceDTO.getResource().getUploadTime()).set("resource_id", postResourceDTO.getResource().getResourceId());
+ rewardService.update(rewardUpdate);
+ }
+ // 存用户上传表
+ UserUpload userUpload = new UserUpload();
+ userUpload.setUserId(postResourceDTO.getUserId());
+ userUpload.setResourceId(postResourceDTO.getResource().getResourceId());
+ userUploadService.save(userUpload);
+ // 创建资源社区
+ Community community = new Community();
+ community.setCommunityName(postResourceDTO.getResource().getResourceName());
+ community.setType(postResourceDTO.getResource().getClassify());
+ community.setResourceId(postResourceDTO.getResource().getResourceId());
+ communityService.save(community);
+ return ResponseEntity.ok("");
+ }
+
+ /**
+ * 购买资源
+ *
+ * @param userResourceDTO 购买资源信息
+ * @return 购买资源结果
+ */
+ @PostMapping("purchase")
+ public ResponseEntity<String> purchaseResource(@RequestBody UserResourceDTO userResourceDTO) {
+
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("user_id", userResourceDTO.getUserId());
+ User user = userService.getOne(userQuery);
+
+ QueryWrapper<Resource> ResourceQuery = new QueryWrapper<>();
+ ResourceQuery.eq("resource_id", userResourceDTO.getResourceId());
+ Resource resource = resourceService.getOne(ResourceQuery);
+
+ if (user.getCredits() < resource.getPrice()) {
+ // 积分余额不足
+ logger.info("The balance of points is insufficient to cover the price of this resource: {}", resource.getPrice());
+ return ResponseEntity.status(412).body("");
+ } else {
+ // 扣除用户积分
+ UpdateWrapper<User> userUpdate = new UpdateWrapper<>();
+ userUpdate.eq("user_id", user.getUserId()).set("credits", user.getCredits() - resource.getPrice());
+ userService.update(userUpdate);
+ // 添加购买资源记录
+ UserPurchase userPurchase = new UserPurchase();
+ userPurchase.setUserId(user.getUserId());
+ userPurchase.setResourceId(resource.getResourceId());
+ userPurchaseService.save(userPurchase);
+ // 给上传该资源的用户发送通知
+ Notification notification = new Notification();
+ QueryWrapper<UserUpload> userUploadQuery = new QueryWrapper<>();
+ userUploadQuery.eq("resource_id", userResourceDTO.getResourceId());
+ UserUpload userUpload = userUploadService.getOne(userUploadQuery);
+ notification.setUserId(userUpload.getUserId());
+ notification.setTitle("资源被购买");
+ notification.setContent("你的资源:" + resource.getResourceName() + " 被: " + user.getUsername() + " 购买了!");
+ notification.setCreateAt(new Date());
+ notification.setRead(false);
+ notification.setTriggeredBy(userResourceDTO.getUserId());
+ notification.setRelatedId(userResourceDTO.getResourceId());
+ notificationService.save(notification);
+ return ResponseEntity.ok("");
+ }
+ }
+
+ /**
+ * 点赞资源
+ *
+ * @param userResourceDTO 点赞资源信息
+ * @return 点赞资源结果
+ */
+ @PostMapping("like")
+ public ResponseEntity<String> likeResource(@RequestBody UserResourceDTO userResourceDTO) {
+
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("user_id", userResourceDTO.getUserId());
+ User user = userService.getOne(userQuery);
+
+ QueryWrapper<Resource> ResourceQuery = new QueryWrapper<>();
+ ResourceQuery.eq("resource_id", userResourceDTO.getResourceId());
+ Resource resource = resourceService.getOne(ResourceQuery);
+
+ UserLike userLike = new UserLike();
+ userLike.setUserId(userResourceDTO.getUserId());
+ userLike.setResourceId(userResourceDTO.getResourceId());
+ userLikeService.save(userLike);
+
+ // 给上传该资源的用户发送通知
+ Notification notification = new Notification();
+ QueryWrapper<UserUpload> userUploadQuery = new QueryWrapper<>();
+ userUploadQuery.eq("resource_id", userResourceDTO.getResourceId());
+ UserUpload userUpload = userUploadService.getOne(userUploadQuery);
+ notification.setUserId(userUpload.getUserId());
+ notification.setTitle("资源被点赞");
+ notification.setContent("你的资源:" + resource.getResourceName() + " 被: " + user.getUsername() + " 点赞了!");
+ notification.setCreateAt(new Date());
+ notification.setRead(false);
+ notification.setTriggeredBy(userResourceDTO.getUserId());
+ notification.setRelatedId(userResourceDTO.getResourceId());
+ notificationService.save(notification);
+
+ return ResponseEntity.ok("");
+ }
+
+ /**
+ * 收藏资源
+ *
+ * @param userResourceDTO 收藏资源信息
+ * @return 收藏资源结果
+ */
+ @PostMapping("collection")
+ public ResponseEntity<String> collectResource(@RequestBody UserResourceDTO userResourceDTO) {
+
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("user_id", userResourceDTO.getUserId());
+ User user = userService.getOne(userQuery);
+
+ QueryWrapper<Resource> ResourceQuery = new QueryWrapper<>();
+ ResourceQuery.eq("resource_id", userResourceDTO.getResourceId());
+ Resource resource = resourceService.getOne(ResourceQuery);
+
+ UserCollection userCollection = new UserCollection();
+ userCollection.setUserId(userResourceDTO.getUserId());
+ userCollection.setResourceId(userResourceDTO.getResourceId());
+ userCollectionService.save(userCollection);
+
+
+ // 给上传该资源的用户发送通知
+ Notification notification = new Notification();
+ QueryWrapper<UserUpload> userUploadQuery = new QueryWrapper<>();
+ userUploadQuery.eq("resource_id", userResourceDTO.getResourceId());
+ UserUpload userUpload = userUploadService.getOne(userUploadQuery);
+ notification.setUserId(userUpload.getUserId());
+ notification.setTitle("资源被收藏");
+ notification.setContent("你的资源:" + resource.getResourceName() + " 被: " + user.getUsername() + " 收藏了!");
+ notification.setCreateAt(new Date());
+ notification.setRead(false);
+ notification.setTriggeredBy(userResourceDTO.getUserId());
+ notification.setRelatedId(userResourceDTO.getResourceId());
+ notificationService.save(notification);
+
+ return ResponseEntity.ok("");
+ }
+
+ /**
+ * 删除资源
+ *
+ * @param resourceId 资源id
+ * @param userId 用户id
+ * @param password 密码
+ * @return 删除资源结果
+ */
+ @DeleteMapping
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public ResponseEntity<String> userDelete(@RequestParam int resourceId, @RequestParam int userId, @RequestParam String password) {
+ logger.warn("Delete resource with id: {}", resourceId);
+ // 根据用户id查询该用户
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("user_id", userId);
+ User userCheck = userService.getOne(userQuery);
+
+ // 只允许在用户上传资源页进行删除操作,所以不需要验证该资源是由该用户上传的
+ if (userCheck.getPassword().equals(password)) {
+ // 删除资源
+ resourceService.removeById(resourceId);
+ return ResponseEntity.noContent().build();
+ } else {
+ logger.warn("Delete failed. Incorrect password for account: {}", password);
+ return ResponseEntity.status(408).body("");
+ }
+ }
+
+ /**
+ * 取消点赞
+ *
+ * @param userId 用户id
+ * @param resourceId 资源id
+ * @return 取消点赞结果
+ */
+ @DeleteMapping("like")
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public ResponseEntity<String> likeDelete(@RequestParam int userId, @RequestParam int resourceId) {
+ QueryWrapper<UserLike> userLikeQuery = new QueryWrapper<>();
+ userLikeQuery.eq("user_id", userId).eq("resource_id", resourceId);
+ userLikeService.remove(userLikeQuery);
+ return ResponseEntity.noContent().build();
+ }
+
+ /**
+ * 取消收藏
+ *
+ * @param userId 用户id
+ * @param resourceId 资源id
+ * @return 取消收藏结果
+ */
+ @DeleteMapping("collection")
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public ResponseEntity<String> collectionDelete(@RequestParam int userId, @RequestParam int resourceId) {
+ QueryWrapper<UserCollection> userCollectionQuery = new QueryWrapper<>();
+ userCollectionQuery.eq("user_id", userId).eq("resource_id", resourceId);
+ userCollectionService.remove(userCollectionQuery);
+ return ResponseEntity.noContent().build();
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/g9/g9backend/controller/UserController.java b/src/main/java/com/g9/g9backend/controller/UserController.java
index 1be4222..9315e8e 100644
--- a/src/main/java/com/g9/g9backend/controller/UserController.java
+++ b/src/main/java/com/g9/g9backend/controller/UserController.java
@@ -2,14 +2,20 @@
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.g9.g9backend.pojo.*;
import com.g9.g9backend.pojo.DTO.*;
import com.g9.g9backend.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* UserController 用户控制器类,处理与用户相关的请求
*
@@ -25,12 +31,31 @@
private final SubscriptionService subscriptionService;
- public UserController(UserService userService, InvitationService invitationService, SubscriptionService subscriptionService) {
+ private final SearchHistoryService searchHistoryService;
+
+ private final RewardService rewardService;
+
+ private final UserCollectionService userCollectionService;
+
+ private final UserUploadService userUploadService;
+
+ private final UserPurchaseService userPurchaseService;
+
+ private final ResourceService resourceService;
+
+ public UserController(UserService userService, InvitationService invitationService, SubscriptionService subscriptionService, SearchHistoryService searchHistoryService, RewardService rewardService, UserCollectionService userCollectionService, UserUploadService userUploadService, UserPurchaseService userPurchaseService, ResourceService resourceService) {
this.userService = userService;
this.invitationService = invitationService;
this.subscriptionService = subscriptionService;
+ this.searchHistoryService = searchHistoryService;
+ this.rewardService = rewardService;
+ this.userCollectionService = userCollectionService;
+ this.userUploadService = userUploadService;
+ this.userPurchaseService = userPurchaseService;
+ this.resourceService = resourceService;
}
+
private final Logger logger = LoggerFactory.getLogger(UserController.class);
/**
@@ -82,9 +107,9 @@
User userGetId = userService.getOne(userQuery);
int newUserId = userGetId.getUserId();
- UpdateWrapper<Invitation> updateWrapper = new UpdateWrapper<>();
- updateWrapper.eq("invitation_code", invitationCode).set("invitee_id", newUserId);
- invitationService.update(updateWrapper);
+ UpdateWrapper<Invitation> invitationUpdate = new UpdateWrapper<>();
+ invitationUpdate.eq("invitation_code", invitationCode).set("invitee_id", newUserId);
+ invitationService.update(invitationUpdate);
// 生成五个邀请码并分配给新用户
String[] invitationCodes = invitationService.generateInvitationCode();
@@ -143,4 +168,378 @@
subscriptionService.save(subscription);
return ResponseEntity.ok("");
}
+
+ /**
+ * 注销账户
+ *
+ * @param userId 用户id
+ * @param password 密码
+ * @return 注销结果
+ */
+ @DeleteMapping
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public ResponseEntity<String> userDelete(@RequestParam int userId, @RequestParam String password) {
+ logger.warn("Delete user with id: {}", userId);
+ // 根据用户id查询该用户
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("user_id", userId);
+ User userCheck = userService.getOne(userQuery);
+
+ if (userCheck.getPassword().equals(password)) {
+ // 注销账户(自动清除与该用户相关的记录,注意会回收分配给该用户的邀请码)
+ userService.remove(userQuery);
+
+ return ResponseEntity.noContent().build();
+ } else {
+ logger.warn("Delete failed. Incorrect password for account: {}", password);
+ return ResponseEntity.status(408).body("");
+ }
+ }
+
+ /**
+ * 删除用户搜索历史
+ *
+ * @param searchHistoryId 搜索历史id
+ * @return 删除用户搜索历史结果
+ */
+ @DeleteMapping("/search")
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public ResponseEntity<String> searchDelete(@RequestParam int searchHistoryId) {
+ searchHistoryService.removeById(searchHistoryId);
+ return ResponseEntity.noContent().build();
+ }
+
+ /**
+ * 取消关注
+ *
+ * @param userId 被关注者id
+ * @param followerId 关注被人者id
+ * @return 取消关注结果
+ */
+ @DeleteMapping("/subscription")
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public ResponseEntity<String> subscriptionDelete(@RequestParam int userId, @RequestParam int followerId) {
+ QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
+ subscriptionQuery.eq("user_id", userId).eq("follower_id", followerId);
+ subscriptionService.remove(subscriptionQuery);
+ return ResponseEntity.noContent().build();
+ }
+
+
+ /**
+ * 获取用户ID
+ *
+ * @param username 用户名
+ * @param password 密码
+ * @return 获取邀请码结果
+ */
+ @GetMapping("/getId")
+ public ResponseEntity<Integer> getUserId(@RequestParam String username, @RequestParam String password) {
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("username", username).eq("password", password);
+ User user = userService.getOne(userQuery);
+ return ResponseEntity.ok(user.getUserId());
+ }
+
+ /**
+ * 获取邀请码
+ *
+ * @param userId 用户id
+ * @return 获取邀请码结果
+ */
+ @GetMapping("/invitation-code")
+ public ResponseEntity<GetInvitationCodeDTO> getInvitationCode(@RequestParam int userId) {
+ QueryWrapper<Invitation> invitationQuery = new QueryWrapper<>();
+ invitationQuery.eq("user_id", userId).eq("invitee_id", 0); // 获取未被使用过的分配给该用户的邀请码
+ invitationQuery.select("invitation_code");
+ List<Invitation> invitationList = invitationService.list(invitationQuery);
+ GetInvitationCodeDTO getInvitationCodeDTO = new GetInvitationCodeDTO(invitationList);
+ return ResponseEntity.ok(getInvitationCodeDTO);
+ }
+
+ /**
+ * 获取用户信息
+ *
+ * @param userId 用户id
+ * @return 获取用户信息结果
+ */
+ @GetMapping("/info")
+ public ResponseEntity<User> getUserInfo(@RequestParam int userId) {
+ User user = userService.getById(userId);
+ return ResponseEntity.ok(user);
+ }
+
+ /**
+ * 获取用户悬赏
+ *
+ * @param userId 用户id
+ * @param pageNumber 页数
+ * @param rows 行数
+ * @return 获取用户悬赏结果
+ */
+ @GetMapping("/reward")
+ public ResponseEntity<GetUserRewardDTO> getUserReward(@RequestParam int userId, @RequestParam int pageNumber, @RequestParam int rows) {
+ IPage<Reward> page = new Page<>(pageNumber, rows);
+ QueryWrapper<Reward> rewardQuery = new QueryWrapper<>();
+ rewardQuery.eq("user_id", userId);
+ IPage<Reward> rewardPage = rewardService.page(page, rewardQuery);
+ List<Reward> rewardList = rewardPage.getRecords();
+ long total = rewardPage.getTotal();
+ long pages = rewardPage.getPages();
+ long current = rewardPage.getCurrent();
+ long size = rewardPage.getSize();
+
+ GetUserRewardDTO getUserRewardDTO = new GetUserRewardDTO(rewardList, total, pages, current, size);
+ return ResponseEntity.ok(getUserRewardDTO);
+ }
+
+ /**
+ * 获取用户收藏资源
+ *
+ * @param userId 用户id
+ * @param pageNumber 页数
+ * @param rows 行数
+ * @return 获取用户收藏结果
+ */
+ @GetMapping("/collection")
+ public ResponseEntity<GetUserResourceListDTO> getUserCollection(@RequestParam int userId, @RequestParam int pageNumber, @RequestParam int rows) {
+ IPage<UserCollection> page = new Page<>(pageNumber, rows);
+ QueryWrapper<UserCollection> userCollectionQuery = new QueryWrapper<>();
+ userCollectionQuery.eq("user_id", userId);
+ IPage<UserCollection> userCollectionPage = userCollectionService.page(page, userCollectionQuery);
+ List<UserCollection> resourceList = userCollectionPage.getRecords();
+ List<Resource> collectionList = new ArrayList<>();
+ for (UserCollection userCollection : resourceList) {
+ Resource resource = resourceService.getById(userCollection.getResourceId());
+ collectionList.add(resource);
+ }
+ long total = userCollectionPage.getTotal();
+ long pages = userCollectionPage.getPages();
+ long current = userCollectionPage.getCurrent();
+ long size = userCollectionPage.getSize();
+
+ GetUserResourceListDTO getUserResourceListDTO = new GetUserResourceListDTO(collectionList, total, pages, current, size);
+ return ResponseEntity.ok(getUserResourceListDTO);
+ }
+
+ /**
+ * 获取用户上传资源
+ *
+ * @param userId 用户id
+ * @param pageNumber 页数
+ * @param rows 行数
+ * @return 获取用户上传资源结果
+ */
+ @GetMapping("/upload")
+ public ResponseEntity<GetUserResourceListDTO> getUserUpload(@RequestParam int userId, @RequestParam int pageNumber, @RequestParam int rows) {
+ IPage<UserUpload> page = new Page<>(pageNumber, rows);
+ QueryWrapper<UserUpload> userUploadQuery = new QueryWrapper<>();
+ userUploadQuery.eq("user_id", userId);
+ IPage<UserUpload> userUploadPage = userUploadService.page(page, userUploadQuery);
+ List<UserUpload> resourceList = userUploadPage.getRecords();
+ List<Resource> uploadList = new ArrayList<>();
+ for (UserUpload userUpload : resourceList) {
+ Resource resource = resourceService.getById(userUpload.getResourceId());
+ uploadList.add(resource);
+ }
+ long total = userUploadPage.getTotal();
+ long pages = userUploadPage.getPages();
+ long current = userUploadPage.getCurrent();
+ long size = userUploadPage.getSize();
+
+ GetUserResourceListDTO getUserResourceListDTO = new GetUserResourceListDTO(uploadList, total, pages, current, size);
+ return ResponseEntity.ok(getUserResourceListDTO);
+ }
+
+ /**
+ * 获取用户购买资源
+ *
+ * @param userId 用户id
+ * @param pageNumber 页数
+ * @param rows 行数
+ * @return 获取用户购买资源结果
+ */
+ @GetMapping("/purchase")
+ public ResponseEntity<GetUserResourceListDTO> getUserPurchase(@RequestParam int userId, @RequestParam int pageNumber, @RequestParam int rows) {
+ IPage<UserPurchase> page = new Page<>(pageNumber, rows);
+ QueryWrapper<UserPurchase> userPurchaseQuery = new QueryWrapper<>();
+ userPurchaseQuery.eq("user_id", userId);
+ IPage<UserPurchase> userPurchasePage = userPurchaseService.page(page, userPurchaseQuery);
+ List<UserPurchase> resourceList = userPurchasePage.getRecords();
+ List<Resource> purchaseList = new ArrayList<>();
+ for (UserPurchase userPurchase : resourceList) {
+ Resource resource = resourceService.getById(userPurchase.getResourceId());
+ purchaseList.add(resource);
+ }
+ long total = userPurchasePage.getTotal();
+ long pages = userPurchasePage.getPages();
+ long current = userPurchasePage.getCurrent();
+ long size = userPurchasePage.getSize();
+
+ GetUserResourceListDTO getUserResourceListDTO = new GetUserResourceListDTO(purchaseList, total, pages, current, size);
+ return ResponseEntity.ok(getUserResourceListDTO);
+ }
+
+ /**
+ * 获取用户搜索历史
+ *
+ * @param userId 用户id
+ * @return 获取用户搜索历史结果
+ */
+ @GetMapping("/search")
+ public ResponseEntity<GetUserSearchHistoryDTO> getUserSearchHistory(@RequestParam int userId) {
+ QueryWrapper<SearchHistory> SearchHistoryQuery = new QueryWrapper<>();
+ SearchHistoryQuery.eq("user_id", userId).orderByDesc("search_history_id").last("LIMIT 10");
+ List<SearchHistory> searchHistoryList = searchHistoryService.list(SearchHistoryQuery);
+
+ GetUserSearchHistoryDTO getUserSearchHistoryDTO = new GetUserSearchHistoryDTO(searchHistoryList);
+ return ResponseEntity.ok(getUserSearchHistoryDTO);
+ }
+
+ /**
+ * 获取用户数据
+ *
+ * @param userId 用户id
+ * @return 获取用户数据结果
+ */
+ @GetMapping("/data")
+ public ResponseEntity<GetUserDataDTO> getUserData(@RequestParam int userId) {
+ User user = userService.getById(userId);
+ int subscriberCount = user.getSubscriberCount();
+ int uploadAmount = user.getUploadAmount();
+
+ QueryWrapper<UserUpload> UserUploadQuery = new QueryWrapper<>();
+ UserUploadQuery.eq("user_id", userId);
+ List<UserUpload> UserUpload = userUploadService.list(UserUploadQuery);
+ int beDownloadedAmount = 0; // 上传资源被下载量
+ float[] seedPercentageList = new float[4]; // 上传资源类型百分比,0-1区间的小数
+ int resourcePackAmount = 0;
+ int modAmount = 0;
+ int modPackAmount = 0;
+ int mapAmount = 0;
+ for (UserUpload userUpload : UserUpload) {
+ Resource resource = resourceService.getById(userUpload.getResourceId());
+ beDownloadedAmount += resource.getDownloads();
+ switch (resource.getClassify()) {
+ case "resourcePack":
+ resourcePackAmount++;
+ break;
+ case "mod":
+ modAmount++;
+ break;
+ case "modPack":
+ modPackAmount++;
+ break;
+ case "map":
+ mapAmount++;
+ break;
+ }
+ }
+ int totalAmount = resourcePackAmount + modAmount + modPackAmount + mapAmount;
+ seedPercentageList[0] = (float) resourcePackAmount / totalAmount;
+ seedPercentageList[1] = (float) modAmount / totalAmount;
+ seedPercentageList[2] = (float) modPackAmount / totalAmount;
+ seedPercentageList[3] = (float) mapAmount / totalAmount;
+
+ GetUserDataDTO getUserDataDTO = new GetUserDataDTO(subscriberCount, uploadAmount, beDownloadedAmount, seedPercentageList);
+ return ResponseEntity.ok(getUserDataDTO);
+ }
+
+ /**
+ * 获取关注列表
+ *
+ * @param userId 用户id
+ * @return 获取关注列表结果
+ */
+ @GetMapping("/subscriber")
+ public ResponseEntity<GetUserDTO> getUserSubscriber(@RequestParam int userId) {
+ QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
+ subscriptionQuery.eq("follower_id", userId);
+ List<Subscription> subscriptionList = subscriptionService.list(subscriptionQuery);
+
+ List<User> subscriberList = new ArrayList<>();
+ for (Subscription subscription : subscriptionList) {
+ User user = userService.getById(subscription.getUserId());
+ subscriberList.add(user);
+ }
+
+ GetUserDTO getUserDTO = new GetUserDTO(subscriberList);
+ return ResponseEntity.ok(getUserDTO);
+ }
+
+ /**
+ * 获取粉丝列表
+ *
+ * @param userId 用户id
+ * @return 获取粉丝列表结果
+ */
+ @GetMapping("/follower")
+ public ResponseEntity<GetUserDTO> getUserFollower(@RequestParam int userId) {
+ QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
+ subscriptionQuery.eq("user_id", userId);
+ List<Subscription> subscriptionList = subscriptionService.list(subscriptionQuery);
+
+ List<User> subscriberList = new ArrayList<>();
+ for (Subscription subscription : subscriptionList) {
+ User user = userService.getById(subscription.getUserId());
+ subscriberList.add(user);
+ }
+
+ GetUserDTO getUserDTO = new GetUserDTO(subscriberList);
+ return ResponseEntity.ok(getUserDTO);
+ }
+
+ /**
+ * 修改用户签名
+ *
+ * @param user 用户信息
+ * @return 用户签名修改结果
+ */
+ @PutMapping("/signature")
+ public ResponseEntity<String> modifySignature(@RequestBody User user) {
+ UpdateWrapper<User> userUpdate = new UpdateWrapper<>();
+ userUpdate.eq("user_id", user.getUserId()).set("signature", user.getSignature());
+ userService.update(userUpdate);
+
+ return ResponseEntity.ok("");
+ }
+
+ /**
+ * 修改用户密码
+ *
+ * @param modifyPasswordDTO 用户信息
+ * @return 用户密码修改结果
+ */
+ @PutMapping("/password")
+ public ResponseEntity<String> modifyPassword(@RequestBody ModifyPasswordDTO modifyPasswordDTO) {
+ // 检查密码是否正确
+ QueryWrapper<User> userQuery = new QueryWrapper<>();
+ userQuery.eq("user_id", modifyPasswordDTO.getUserId());
+ User user = userService.getOne(userQuery);
+ if (user.getPassword().equals(modifyPasswordDTO.getPassword())) {
+ UpdateWrapper<User> userUpdate = new UpdateWrapper<>();
+ userUpdate.eq("user_id", modifyPasswordDTO.getUserId()).set("password", modifyPasswordDTO.getNewPassword());
+ userService.update(userUpdate);
+ return ResponseEntity.ok("");
+ } else {
+ // 密码错误
+ logger.warn("Modify failed. Incorrect password for userID: {}", modifyPasswordDTO.getUserId());
+ return ResponseEntity.status(408).body("");
+ }
+ }
+
+ /**
+ * 修改用户头像
+ *
+ * @param user 用户信息
+ * @return 用户头像修改结果
+ */
+ @PutMapping("/avatar")
+ public ResponseEntity<String> modifyAvatar(@RequestBody User user) {
+ UpdateWrapper<User> userUpdate = new UpdateWrapper<>();
+ userUpdate.eq("user_id", user.getUserId()).set("avatar", user.getAvatar());
+ userService.update(userUpdate);
+
+ return ResponseEntity.ok("");
+ }
}
\ No newline at end of file
diff --git a/src/test/java/com/g9/g9backend/controller/ResourceControllerTest.java b/src/test/java/com/g9/g9backend/controller/ResourceControllerTest.java
index c02be49..9d7c908 100644
--- a/src/test/java/com/g9/g9backend/controller/ResourceControllerTest.java
+++ b/src/test/java/com/g9/g9backend/controller/ResourceControllerTest.java
@@ -1,5 +1,256 @@
package com.g9.g9backend.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.g9.g9backend.pojo.*;
+import com.g9.g9backend.pojo.DTO.*;
+import com.g9.g9backend.service.*;
+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.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Date;
+
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/*
+ @SpringBootTest 启动一个完整的 Spring 应用上下文,用来测试整个应用的行为
+ @AutoConfigureMockMvc 自动配置 MockMvc 对象,MockMvc 是 Spring 提供的工具,用来模拟 HTTP 请求,从而不需要启动真正的服务器来发送HTTP请求就能进行测试
+ 注意@SpringBootTest 已经自动配置了 Mockito 或 Spring 的 Mock 环境,再在setup中手动调用 openMocks(this) 可能导致 Mock 对象被重复初始化
+ 出现状态丢失问题(如 when().thenReturn() 规则失效),所以改为使用 JUnit 5 默认运行器,不需要在这里写注解
+*/
public class ResourceControllerTest {
+ // MockMvc对象
+ private MockMvc mockMvc;
+
+ // @InjectMocks告诉测试框架(Mockito)创建 ResourceController 的实例,并自动将标注了 @Mock 的依赖注入到这个实例中
+ @InjectMocks
+ private ResourceController resourceController;
+
+ // @Mock告诉 Mockito 创建这些依赖的“模拟对象”,用来模拟服务行为,和controller层使用的service依赖一一对应即可
+ @Mock
+ private ResourceService resourceService;
+
+ @Mock
+ private GameplayService gameplayService;
+
+ @Mock
+ private RewardService rewardService;
+
+ @Mock
+ private UserUploadService userUploadService;
+
+ @Mock
+ private CommunityService communityService;
+
+ @Mock
+ private UserService userService;
+
+ @Mock
+ private UserPurchaseService userPurchaseService;
+
+ @Mock
+ private UserLikeService userLikeService;
+
+ @Mock
+ private UserCollectionService userCollectionService;
+
+ @Mock
+ private NotificationService notificationService;
+
+ // ObjectMapper对象用于将 Java 对象和 JSON 字符串互相转换 ,因为在测试中,需要把请求参数或返回响应转换成 JSON 字符串形式来传输
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ // 这个方法会在每个测试方法执行之前运行。用来设置测试的初始化逻辑
+ @BeforeEach
+ public void setup() {
+ MockitoAnnotations.openMocks(this);
+ mockMvc = MockMvcBuilders.standaloneSetup(resourceController).build();
+ }
+
+ // 以下是对各接口的测试,注意测试方法是要对每个接口的每个响应测试(如果一个接口有三种响应,就写三个测试方法)
+ // 上传资源
+ @Test
+ public void testUploadResource() throws Exception {
+
+ // 创建测试用的请求数据
+ PostResourceDTO postResourceDTO = new PostResourceDTO();
+ Resource resource = new Resource();
+ resource.setResourceId(1);
+ resource.setResourceName("Test Resource");
+ resource.setUploadTime(new Date());
+ resource.setLastUpdateTime(new Date());
+ resource.setPrice(1);
+ resource.setClassify("map");
+ postResourceDTO.setResource(resource);
+ postResourceDTO.setGameplayList(new String[]{"Gameplay1", "Gameplay2"});
+ postResourceDTO.setUserId(1);
+
+ /*
+ 模拟服务层的行为,when(...).thenReturn(...)表示当某个服务方法被调用时,返回一个指定的结果(注意mybatis-plus的这些方法一般返回是boolean类型,所以写true不能写null)
+ 同样是测试方法,测试粒度有区别
+ 有简单写法:when(gameplayService.save(any())).thenReturn(true);只验证方法是否被调用(间接验证逻辑是否执行到该服务方法),不关心方法调用的次数和传递的参数
+ 也有复杂写法:额外用 verify 验证调用次数和 ArgumentCaptor 验证参数是否传递正确和InOrder 来验证方法的调用顺序是否正确...
+ */
+
+ // 测试主是要测试传参是否能正确接收,接口调用过程是否使用过这些方法(所以使用到的方法一般来说应该按顺序写在这,不能缺不能多也不能乱序,但是这里实际因为测试粒度不够细,没有对方法调用过程的验证,所以即是方法缺少或调用过程有问题,也不会报错),返回响应是否发送正确
+ when(resourceService.save(any())).thenReturn(true);
+ when(gameplayService.save(any())).thenReturn(true);
+ when(userUploadService.save(any())).thenReturn(true);
+ when(communityService.save(any())).thenReturn(true);
+ when(rewardService.update(any())).thenReturn(true);
+
+ // 模拟 HTTP 请求
+ mockMvc.perform(post("/resource") // 使用 MockMvc 模拟用户提交 POST 请求到 /resource 接口
+ .contentType(MediaType.APPLICATION_JSON) // 设置请求体是 JSON 格式
+ .content(objectMapper.writeValueAsString(postResourceDTO))) //把请求参数对象:postResourceDTO 转成 JSON 字符串,作为请求体内容发送
+ .andExpect(status().isOk()); // 期望接口返回 HTTP 状态码 200(成功)
+ }
+
+ // 购买资源
+ @Test
+ public void testPurchaseResource_success() throws Exception {
+
+ // 用户积分足够
+ User user = new User();
+ user.setUserId(1);
+ user.setCredits(100);
+ Resource resource = new Resource();
+ resource.setResourceId(1);
+ resource.setPrice(50);
+
+ when(userService.getOne(any())).thenReturn(user);
+ when(resourceService.getOne(any())).thenReturn(resource);
+ when(userService.update(any())).thenReturn(true);
+ when(userPurchaseService.save(any())).thenReturn(true);
+ when(userUploadService.getOne(any())).thenReturn(new UserUpload(2, 1));
+ when(notificationService.save(any())).thenReturn(true);
+
+ mockMvc.perform(post("/resource/purchase")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(new UserResourceDTO(1, 1))))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ public void testPurchaseResource_purchaseFailed() throws Exception {
+
+ //用户积分不足
+ User user = new User();
+ user.setUserId(1);
+ user.setCredits(10);
+ Resource resource = new Resource();
+ resource.setResourceId(1);
+ resource.setPrice(50);
+
+ when(userService.getOne(any())).thenReturn(user);
+ when(resourceService.getOne(any())).thenReturn(resource);
+
+ mockMvc.perform(post("/resource/purchase")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(new UserResourceDTO(1, 1))))
+ .andExpect(status().is(412));
+ }
+
+ // 点赞资源
+ @Test
+ public void testLikeResource() throws Exception {
+
+ User user = new User();
+ user.setUserId(1);
+ Resource resource = new Resource();
+ resource.setResourceId(1);
+
+ when(userService.getOne(any())).thenReturn(user);
+ when(resourceService.getOne(any())).thenReturn(resource);
+ when(userLikeService.save(any())).thenReturn(true);
+ when(userUploadService.getOne(any())).thenReturn(new UserUpload(2, 1));
+ when(notificationService.save(any())).thenReturn(true);
+
+ mockMvc.perform(post("/resource/like")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(new UserResourceDTO(1, 1))))
+ .andExpect(status().isOk());
+ }
+
+ // 收藏资源
+ @Test
+ public void testCollectResource() throws Exception {
+
+ User user = new User();
+ user.setUserId(1);
+ Resource resource = new Resource();
+ resource.setResourceId(1);
+
+ when(userService.getOne(any())).thenReturn(user);
+ when(resourceService.getOne(any())).thenReturn(resource);
+ when(userCollectionService.save(any())).thenReturn(true);
+ when(userUploadService.getOne(any())).thenReturn(new UserUpload(2, 1));
+ when(notificationService.save(any())).thenReturn(true);
+
+ mockMvc.perform(post("/resource/collection")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(new UserResourceDTO(1, 1))))
+ .andExpect(status().isOk());
+ }
+
+ // 删除资源
+ @Test
+ public void testDeleteResource_success() throws Exception {
+
+ // 密码正确
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+ when(resourceService.removeById(1)).thenReturn(true);
+
+ mockMvc.perform(delete("/resource")
+ .param("resourceId", "1")
+ .param("userId", "1")
+ .param("password", "123"))
+ .andExpect(status().isNoContent());
+ }
+
+ @Test
+ public void testDeleteResource_wrongPassword() throws Exception {
+
+ // 密码错误
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(delete("/resource")
+ .param("resourceId", "1")
+ .param("userId", "1")
+ .param("password", "wrong"))
+ .andExpect(status().is(408));
+ }
+
+ // 取消点赞
+ @Test
+ public void testLikeDelete() throws Exception {
+
+ when(userLikeService.remove(any())).thenReturn(true);
+
+ mockMvc.perform(delete("/resource/like")
+ .param("userId", "1")
+ .param("resourceId", "1"))
+ .andExpect(status().isNoContent());
+ }
+
+ // 取消收藏
+ @Test
+ public void testCollectionDelete() throws Exception {
+
+ when(userCollectionService.remove(any())).thenReturn(true);
+
+ mockMvc.perform(delete("/resource/collection")
+ .param("userId", "1")
+ .param("resourceId", "1"))
+ .andExpect(status().isNoContent());
+ }
}
\ No newline at end of file
diff --git a/src/test/java/com/g9/g9backend/controller/UserControllerTest.java b/src/test/java/com/g9/g9backend/controller/UserControllerTest.java
index 208645c..d390dea 100644
--- a/src/test/java/com/g9/g9backend/controller/UserControllerTest.java
+++ b/src/test/java/com/g9/g9backend/controller/UserControllerTest.java
@@ -1,5 +1,7 @@
package com.g9.g9backend.controller;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.g9.g9backend.pojo.*;
import com.g9.g9backend.pojo.DTO.*;
@@ -13,6 +15,10 @@
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@@ -34,6 +40,24 @@
@Mock
private SubscriptionService subscriptionService;
+ @Mock
+ private SearchHistoryService searchHistoryService;
+
+ @Mock
+ private RewardService rewardService;
+
+ @Mock
+ private UserCollectionService userCollectionService;
+
+ @Mock
+ private UserUploadService userUploadService;
+
+ @Mock
+ private UserPurchaseService userPurchaseService;
+
+ @Mock
+ private ResourceService resourceService;
+
private final ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
@@ -169,4 +193,275 @@
.content(objectMapper.writeValueAsString(new Subscription(1, 2))))
.andExpect(status().isOk());
}
+
+ // 注销
+ @Test
+ public void testUserDelete_success() throws Exception {
+
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(delete("/user")
+ .param("userId", "1")
+ .param("password", "123"))
+ .andExpect(status().isNoContent());
+ }
+
+ @Test
+ public void testUserDelete_wrongPassword() throws Exception {
+
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(delete("/user")
+ .param("userId", "1")
+ .param("password", "wrong"))
+ .andExpect(status().is(408));
+ }
+
+ // 删除搜索历史
+ @Test
+ public void testSearchDelete() throws Exception {
+
+ when(searchHistoryService.removeById(anyInt())).thenReturn(true);
+
+ mockMvc.perform(delete("/user/search")
+ .param("searchHistoryId", "1"))
+ .andExpect(status().isNoContent());
+ }
+
+ // 取消关注
+ @Test
+ public void testSubscriptionDelete() throws Exception {
+
+ when(subscriptionService.remove(any())).thenReturn(true);
+
+ mockMvc.perform(delete("/user/subscription")
+ .param("userId", "1")
+ .param("followerId", "2"))
+ .andExpect(status().isNoContent());
+ }
+
+ // 获取用户ID
+ @Test
+ public void testGetUserId() throws Exception {
+
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(get("/user/getId")
+ .param("username", "hcy")
+ .param("password", "123"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取邀请码
+ @Test
+ public void testGetInvitationCode() throws Exception {
+
+ List<Invitation> invitationList = new ArrayList<>();
+ invitationList.add(new Invitation("1RCA7Y8J", 0, 0));
+ invitationList.add(new Invitation("2RCA7Y8J", 0, 0));
+ invitationList.add(new Invitation("3RCA7Y8J", 0, 0));
+ invitationList.add(new Invitation("4RCA7Y8J", 0, 0));
+ invitationList.add(new Invitation("5RCA7Y8J", 0, 0));
+
+ QueryWrapper<Invitation> invitationQuery = new QueryWrapper<>();
+ invitationQuery.eq("user_id", 1).eq("invitee_id", 0);
+ invitationQuery.select("invitation_code");
+
+ when(invitationService.list(invitationQuery)).thenReturn(invitationList); //这里用any()无法识别,因为list有多种参数可能
+
+ mockMvc.perform(get("/user/invitation-code")
+ .param("userId", "1"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取用户信息
+ @Test
+ public void testGetUserInfo() throws Exception {
+
+ when(userService.getById(anyInt())).thenReturn(new User(1, "user", "pass", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(get("/user/info")
+ .param("userId", "1"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取悬赏
+ @Test
+ public void testGetUserReward() throws Exception {
+
+ when(rewardService.page(any(), any())).thenReturn(new Page<>(1, 2));
+
+ mockMvc.perform(get("/user/reward")
+ .param("userId", "1")
+ .param("pageNumber", "2")
+ .param("rows", "2"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取收藏
+ @Test
+ public void testGetUserCollection() throws Exception {
+
+ when(userCollectionService.page(any(), any())).thenReturn(new Page<>(1, 2));
+ when(resourceService.getById(anyInt())).thenReturn(new Resource(1, "a", null, null, null, new Date(), new Date(), 100, 0, 0, 0, 0, 0, "mod"));
+
+ mockMvc.perform(get("/user/collection")
+ .param("userId", "1")
+ .param("pageNumber", "1")
+ .param("rows", "2"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取上传
+ @Test
+ public void testGetUserUpload() throws Exception {
+
+ when(userUploadService.page(any(), any())).thenReturn(new Page<>(1, 2));
+ when(resourceService.getById(anyInt())).thenReturn(new Resource(1, "a", null, null, null, new Date(), new Date(), 100, 0, 0, 0, 0, 0, "mod"));
+
+ mockMvc.perform(get("/user/upload")
+ .param("userId", "1")
+ .param("pageNumber", "1")
+ .param("rows", "2"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取购买
+ @Test
+ public void testGetUserPurchase() throws Exception {
+
+ when(userPurchaseService.page(any(), any())).thenReturn(new Page<>(1, 2));
+ when(resourceService.getById(anyInt())).thenReturn(new Resource(1, "a", null, null, null, new Date(), new Date(), 100, 0, 0, 0, 0, 0, "mod"));
+
+ mockMvc.perform(get("/user/purchase")
+ .param("userId", "1")
+ .param("pageNumber", "1")
+ .param("rows", "2"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取搜索历史
+ @Test
+ public void testGetUserSearchHistory() throws Exception {
+
+ List<SearchHistory> searchHistoryList = new ArrayList<>();
+
+ QueryWrapper<SearchHistory> searchHistoryQuery = new QueryWrapper<>();
+ searchHistoryQuery.eq("user_id", 1).orderByDesc("search_history_id").last("LIMIT 10");
+
+ when(searchHistoryService.list(searchHistoryQuery)).thenReturn(searchHistoryList);
+
+ mockMvc.perform(get("/user/search")
+ .param("userId", "1"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取用户数据
+ @Test
+ public void testGetUserData() throws Exception {
+
+ when(userService.getById(1)).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ List<UserUpload> UserUpload = new ArrayList<>();
+ QueryWrapper<UserUpload> userUploadQuery = new QueryWrapper<>();
+ userUploadQuery.eq("user_id", 1);
+ when(userUploadService.list(userUploadQuery)).thenReturn(UserUpload);
+
+ when(resourceService.getById(anyInt())).thenReturn(new Resource());
+
+ mockMvc.perform(get("/user/data")
+ .param("userId", "1"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取关注列表
+ @Test
+ public void testGetUserSubscriber() throws Exception {
+
+ QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
+ subscriptionQuery.eq("follower_id", 1);
+ List<Subscription> subscriptionList = new ArrayList<>();
+
+ when(subscriptionService.list(subscriptionQuery)).thenReturn(subscriptionList);
+ when(userService.getById(1)).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(get("/user/subscriber")
+ .param("userId", "1"))
+ .andExpect(status().isOk());
+ }
+
+ // 获取粉丝列表
+ @Test
+ public void testGetUserFollower() throws Exception {
+
+ QueryWrapper<Subscription> subscriptionQuery = new QueryWrapper<>();
+ subscriptionQuery.eq("user_id", 1);
+ List<Subscription> subscriptionList = new ArrayList<>();
+
+ when(subscriptionService.list(subscriptionQuery)).thenReturn(subscriptionList);
+ when(userService.getById(1)).thenReturn(new User(1, "hcy", "123", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(get("/user/follower")
+ .param("userId", "1"))
+ .andExpect(status().isOk());
+ }
+
+ // 修改签名
+ @Test
+ public void testModifySignature() throws Exception {
+
+ User user = new User();
+ user.setUserId(1);
+ user.setSignature("New Signature");
+
+ when(userService.update(any())).thenReturn(true);
+
+ mockMvc.perform(put("/user/signature")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(user)))
+ .andExpect(status().isOk());
+ }
+
+ // 修改密码
+ @Test
+ public void testModifyPassword_success() throws Exception {
+
+ // 密码正确
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "oldPass", null, 0, 0, null, 0, 0, 0));
+ when(userService.update(any())).thenReturn(true);
+
+ mockMvc.perform(put("/user/password")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(new ModifyPasswordDTO(1, "oldPass", "newPass"))))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ public void testModifyPassword_wrongPassword() throws Exception {
+
+ // 密码错误
+ when(userService.getOne(any())).thenReturn(new User(1, "hcy", "oldPass", null, 0, 0, null, 0, 0, 0));
+
+ mockMvc.perform(put("/user/password")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(new ModifyPasswordDTO(1, "wrongPassword", "newPass"))))
+ .andExpect(status().is(408));
+ }
+
+ // 修改头像
+ @Test
+ public void testModifyAvatar() throws Exception {
+
+ // 设置请求参数
+ User user = new User();
+ user.setUserId(1);
+ user.setAvatar("avatar.png");
+
+ when(userService.update(any())).thenReturn(true);
+
+ mockMvc.perform(put("/user/avatar")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(user)))
+ .andExpect(status().isOk());
+ }
}
\ No newline at end of file