feat(test): 新增ArticleService部分单元测试,部分功能优化,sql文件新增测试数据

涵盖ArticleService单元测试方法:
postArticle
findArticles
findArticleDTOById
findUserArticlesByIdUser
incrementArticleViewCount
updatePerfect
delete

ArticleService将用户获取逻辑转移到Controller中
sql文件新增用户测试数据
This commit is contained in:
kould.li 2022-08-04 15:51:09 +08:00
parent bc395e2997
commit a907571ac6
14 changed files with 303 additions and 36 deletions

View File

@ -292,6 +292,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>

View File

@ -2,7 +2,10 @@ package com.rymcu.forest.dto;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -11,6 +14,9 @@ import java.util.List;
* @author ronger * @author ronger
*/ */
@Data @Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ArticleDTO { public class ArticleDTO {
@JsonFormat(shape = JsonFormat.Shape.STRING) @JsonFormat(shape = JsonFormat.Shape.STRING)
private Long idArticle; private Long idArticle;

View File

@ -1,12 +1,18 @@
package com.rymcu.forest.dto; package com.rymcu.forest.dto;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor;
/** /**
* @author ronger * @author ronger
*/ */
@Data @Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ArticleTagDTO { public class ArticleTagDTO {
@JsonFormat(shape = JsonFormat.Shape.STRING) @JsonFormat(shape = JsonFormat.Shape.STRING)
private Long idArticleTag; private Long idArticleTag;

View File

@ -1,12 +1,18 @@
package com.rymcu.forest.dto; package com.rymcu.forest.dto;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor;
/** /**
* @author ronger * @author ronger
*/ */
@Data @Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Author { public class Author {
@JsonFormat(shape = JsonFormat.Shape.STRING) @JsonFormat(shape = JsonFormat.Shape.STRING)

View File

@ -65,7 +65,8 @@ public class LuceneServiceImpl implements LuceneService {
try { try {
int totalCount = list.size(); int totalCount = list.size();
int perThreadCount = 3000; int perThreadCount = 3000;
int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); // 加1避免线程池的参数为0
int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1) + 1;
ExecutorService pool = Executors.newFixedThreadPool(threadCount); ExecutorService pool = Executors.newFixedThreadPool(threadCount);
CountDownLatch countDownLatch1 = new CountDownLatch(1); CountDownLatch countDownLatch1 = new CountDownLatch(1);
CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); CountDownLatch countDownLatch2 = new CountDownLatch(threadCount);

View File

@ -55,7 +55,8 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService {
try { try {
int totalCount = list.size(); int totalCount = list.size();
int perThreadCount = 3000; int perThreadCount = 3000;
int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); // 加1避免线程池的参数为0
int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1) + 1;
ExecutorService pool = Executors.newFixedThreadPool(threadCount); ExecutorService pool = Executors.newFixedThreadPool(threadCount);
CountDownLatch countDownLatch1 = new CountDownLatch(1); CountDownLatch countDownLatch1 = new CountDownLatch(1);
CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); CountDownLatch countDownLatch2 = new CountDownLatch(threadCount);

View File

@ -24,6 +24,9 @@ public class ArticleIndexUtil {
private static final String PATH = private static final String PATH =
System.getProperty("user.dir") + StrUtil.SLASH + LucenePath.ARTICLE_INDEX_PATH; System.getProperty("user.dir") + StrUtil.SLASH + LucenePath.ARTICLE_INDEX_PATH;
private static final String WINDOW_PATH =
System.getProperty("user.dir") + StrUtil.BACKSLASH + "lucene\\index\\article";
/** 删除所有运行中保存的索引 */ /** 删除所有运行中保存的索引 */
public static void deleteAllIndex() { public static void deleteAllIndex() {
if (FileUtil.exist(LucenePath.ARTICLE_INCREMENT_INDEX_PATH)) { if (FileUtil.exist(LucenePath.ARTICLE_INCREMENT_INDEX_PATH)) {

View File

@ -4,12 +4,11 @@ import com.rymcu.forest.core.service.Service;
import com.rymcu.forest.dto.ArticleDTO; import com.rymcu.forest.dto.ArticleDTO;
import com.rymcu.forest.dto.ArticleSearchDTO; import com.rymcu.forest.dto.ArticleSearchDTO;
import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.Article;
import com.rymcu.forest.entity.User;
import com.rymcu.forest.web.api.exception.BaseApiException; import com.rymcu.forest.web.api.exception.BaseApiException;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* @author ronger * @author ronger
@ -55,12 +54,12 @@ public interface ArticleService extends Service<Article> {
/** /**
* 新增/更新文章 * 新增/更新文章
* @param article * @param article
* @param request * @param user
* @throws UnsupportedEncodingException * @throws UnsupportedEncodingException
* @throws BaseApiException * @throws BaseApiException
* @return * @return
* */ * */
Long postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException; Long postArticle(ArticleDTO article, User user) throws UnsupportedEncodingException, BaseApiException;
/** /**
* 删除文章 * 删除文章
@ -86,10 +85,9 @@ public interface ArticleService extends Service<Article> {
/** /**
* 查询草稿文章类别 * 查询草稿文章类别
* @throws BaseApiException
* @return * @return
*/ */
List<ArticleDTO> findDrafts() throws BaseApiException; List<ArticleDTO> findDrafts(Long userId);
/** /**
* 查询作品集下文章 * 查询作品集下文章
@ -111,11 +109,12 @@ public interface ArticleService extends Service<Article> {
* 更新文章标签 * 更新文章标签
* @param idArticle * @param idArticle
* @param tags * @param tags
* @param userId
* @return * @return
* @throws UnsupportedEncodingException * @throws UnsupportedEncodingException
* @throws BaseApiException * @throws BaseApiException
*/ */
Boolean updateTags(Long idArticle, String tags) throws UnsupportedEncodingException, BaseApiException; Boolean updateTags(Long idArticle, String tags, Long userId) throws UnsupportedEncodingException, BaseApiException;
/** /**
* 更新文章优选状态 * 更新文章优选状态

View File

@ -23,7 +23,7 @@ public interface TagService extends Service<Tag> {
* @throws BaseApiException * @throws BaseApiException
* @return * @return
* */ * */
Integer saveTagArticle(Article article, String articleContentHtml) throws UnsupportedEncodingException, BaseApiException; Integer saveTagArticle(Article article, String articleContentHtml, Long userId) throws UnsupportedEncodingException, BaseApiException;
/** /**
* 清除未使用标签 * 清除未使用标签

View File

@ -101,16 +101,12 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
@Override @Override
@Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class}) @Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class})
public Long postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException { public Long postArticle(ArticleDTO article, User user) throws UnsupportedEncodingException, BaseApiException {
boolean isUpdate = false; boolean isUpdate = false;
String articleTitle = article.getArticleTitle(); String articleTitle = article.getArticleTitle();
String articleTags = article.getArticleTags(); String articleTags = article.getArticleTags();
String articleContent = article.getArticleContent(); String articleContent = article.getArticleContent();
String articleContentHtml = XssUtils.filterHtmlCode(article.getArticleContentHtml()); String articleContentHtml = XssUtils.filterHtmlCode(article.getArticleContentHtml());
User user = UserUtils.getCurrentUserByToken();
if (Objects.isNull(user)) {
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
String reservedTag = checkTags(articleTags); String reservedTag = checkTags(articleTags);
boolean notification = false; boolean notification = false;
if (StringUtils.isNotBlank(reservedTag)) { if (StringUtils.isNotBlank(reservedTag)) {
@ -178,7 +174,7 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
newArticle.setArticlePermalink(domain + "/draft/" + newArticleId); newArticle.setArticlePermalink(domain + "/draft/" + newArticleId);
newArticle.setArticleLink("/draft/" + newArticleId); newArticle.setArticleLink("/draft/" + newArticleId);
} }
tagService.saveTagArticle(newArticle, articleContentHtml); tagService.saveTagArticle(newArticle, articleContentHtml, user.getIdUser());
if (StringUtils.isNotBlank(articleContentHtml)) { if (StringUtils.isNotBlank(articleContentHtml)) {
String previewContent = Html2TextUtil.getContent(articleContentHtml); String previewContent = Html2TextUtil.getContent(articleContentHtml);
@ -237,12 +233,8 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
} }
@Override @Override
public List<ArticleDTO> findDrafts() throws BaseApiException { public List<ArticleDTO> findDrafts(Long userId) {
User user = UserUtils.getCurrentUserByToken(); List<ArticleDTO> list = articleMapper.selectDrafts(userId);
if (Objects.isNull(user)) {
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
List<ArticleDTO> list = articleMapper.selectDrafts(user.getIdUser());
list.forEach(articleDTO -> genArticle(articleDTO, 0)); list.forEach(articleDTO -> genArticle(articleDTO, 0));
return list; return list;
} }
@ -263,14 +255,14 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Boolean updateTags(Long idArticle, String tags) throws UnsupportedEncodingException, BaseApiException { public Boolean updateTags(Long idArticle, String tags, Long userId) throws UnsupportedEncodingException, BaseApiException {
Article article = articleMapper.selectByPrimaryKey(idArticle); Article article = articleMapper.selectByPrimaryKey(idArticle);
if (!Objects.nonNull(article)) { if (!Objects.nonNull(article)) {
throw new ContentNotExistException("更新失败,文章不存在!"); throw new ContentNotExistException("更新失败,文章不存在!");
} }
article.setArticleTags(tags); article.setArticleTags(tags);
articleMapper.updateArticleTags(idArticle, tags); articleMapper.updateArticleTags(idArticle, tags);
tagService.saveTagArticle(article, ""); tagService.saveTagArticle(article, "", userId);
return true; return true;
} }

View File

@ -42,8 +42,7 @@ public class TagServiceImpl extends AbstractService<Tag> implements TagService {
@Override @Override
@Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class}) @Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class})
public Integer saveTagArticle(Article article, String articleContentHtml) throws UnsupportedEncodingException, BaseApiException { public Integer saveTagArticle(Article article, String articleContentHtml, Long userId) throws UnsupportedEncodingException, BaseApiException {
User user = UserUtils.getCurrentUserByToken();
String articleTags = article.getArticleTags(); String articleTags = article.getArticleTags();
if (StringUtils.isNotBlank(articleTags)) { if (StringUtils.isNotBlank(articleTags)) {
String[] tags = articleTags.split(","); String[] tags = articleTags.split(",");
@ -80,7 +79,7 @@ public class TagServiceImpl extends AbstractService<Tag> implements TagService {
tagMapper.updateByPrimaryKeySelective(tag); tagMapper.updateByPrimaryKeySelective(tag);
addTagArticle = true; addTagArticle = true;
} }
Integer countUserTag = tagMapper.selectCountUserTagById(user.getIdUser(), tag.getIdTag()); Integer countUserTag = tagMapper.selectCountUserTagById(userId, tag.getIdTag());
if (countUserTag == 0) { if (countUserTag == 0) {
addUserTag = true; addUserTag = true;
} }
@ -92,7 +91,7 @@ public class TagServiceImpl extends AbstractService<Tag> implements TagService {
tagMapper.insertTagArticle(tag.getIdTag(), article.getIdArticle()); tagMapper.insertTagArticle(tag.getIdTag(), article.getIdArticle());
} }
if (addUserTag) { if (addUserTag) {
tagMapper.insertUserTag(tag.getIdTag(), user.getIdUser(), 1); tagMapper.insertUserTag(tag.getIdTag(), userId, 1);
} }
} }
return 1; return 1;
@ -108,7 +107,7 @@ public class TagServiceImpl extends AbstractService<Tag> implements TagService {
} else { } else {
article.setArticleTags("待分类"); article.setArticleTags("待分类");
} }
saveTagArticle(article, articleContentHtml); saveTagArticle(article, articleContentHtml, userId);
} }
} }
return 0; return 0;

View File

@ -10,19 +10,22 @@ import com.rymcu.forest.dto.CommentDTO;
import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.Article;
import com.rymcu.forest.entity.ArticleThumbsUp; import com.rymcu.forest.entity.ArticleThumbsUp;
import com.rymcu.forest.entity.Sponsor; import com.rymcu.forest.entity.Sponsor;
import com.rymcu.forest.entity.User;
import com.rymcu.forest.enumerate.Module; import com.rymcu.forest.enumerate.Module;
import com.rymcu.forest.service.ArticleService; import com.rymcu.forest.service.ArticleService;
import com.rymcu.forest.service.ArticleThumbsUpService; import com.rymcu.forest.service.ArticleThumbsUpService;
import com.rymcu.forest.service.CommentService; import com.rymcu.forest.service.CommentService;
import com.rymcu.forest.service.SponsorService; import com.rymcu.forest.service.SponsorService;
import com.rymcu.forest.util.UserUtils;
import com.rymcu.forest.web.api.exception.BaseApiException; import com.rymcu.forest.web.api.exception.BaseApiException;
import com.rymcu.forest.web.api.exception.ErrorCode;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* @author ronger * @author ronger
@ -47,14 +50,22 @@ public class ArticleController {
} }
@PostMapping("/post") @PostMapping("/post")
public GlobalResult<Long> postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { public GlobalResult<Long> postArticle(@RequestBody ArticleDTO article) throws BaseApiException, UnsupportedEncodingException {
return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, request)); User user = UserUtils.getCurrentUserByToken();
if (Objects.isNull(user)) {
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, user));
} }
@PutMapping("/post") @PutMapping("/post")
@AuthorshipInterceptor(moduleName = Module.ARTICLE) @AuthorshipInterceptor(moduleName = Module.ARTICLE)
public GlobalResult<Long> updateArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { public GlobalResult<Long> updateArticle(@RequestBody ArticleDTO article) throws BaseApiException, UnsupportedEncodingException {
return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, request)); User user = UserUtils.getCurrentUserByToken();
if (Objects.isNull(user)) {
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, user));
} }
@DeleteMapping("/delete/{idArticle}") @DeleteMapping("/delete/{idArticle}")
@ -71,7 +82,11 @@ public class ArticleController {
@GetMapping("/drafts") @GetMapping("/drafts")
public GlobalResult<PageInfo<ArticleDTO>> drafts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { public GlobalResult<PageInfo<ArticleDTO>> drafts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException {
PageHelper.startPage(page, rows); PageHelper.startPage(page, rows);
List<ArticleDTO> list = articleService.findDrafts(); User user = UserUtils.getCurrentUserByToken();
if (Objects.isNull(user)) {
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
List<ArticleDTO> list = articleService.findDrafts(user.getIdUser());
PageInfo<ArticleDTO> pageInfo = new PageInfo<>(list); PageInfo<ArticleDTO> pageInfo = new PageInfo<>(list);
return GlobalResultGenerator.genSuccessResult(pageInfo); return GlobalResultGenerator.genSuccessResult(pageInfo);
} }
@ -86,7 +101,8 @@ public class ArticleController {
public GlobalResult<Boolean> updateTags(@RequestBody Article article) throws BaseApiException, UnsupportedEncodingException { public GlobalResult<Boolean> updateTags(@RequestBody Article article) throws BaseApiException, UnsupportedEncodingException {
Long idArticle = article.getIdArticle(); Long idArticle = article.getIdArticle();
String articleTags = article.getArticleTags(); String articleTags = article.getArticleTags();
return GlobalResultGenerator.genSuccessResult(articleService.updateTags(idArticle, articleTags)); User user = UserUtils.getCurrentUserByToken();
return GlobalResultGenerator.genSuccessResult(articleService.updateTags(idArticle, articleTags, user.getIdUser()));
} }
@PostMapping("/thumbs-up") @PostMapping("/thumbs-up")

View File

@ -342,6 +342,10 @@ insert into forest.forest_user (id, account, password, nickname, real_name, sex,
status, created_time, updated_time, last_login_time, signature) status, created_time, updated_time, last_login_time, signature)
values (1, 'admin', '8ce2dd866238958ac4f07870766813cdaa39a9b83a8c75e26aa50f23', 'admin', 'admin', '0', '0', null, 'admin@rymcu.com', values (1, 'admin', '8ce2dd866238958ac4f07870766813cdaa39a9b83a8c75e26aa50f23', 'admin', 'admin', '0', '0', null, 'admin@rymcu.com',
null, '0', '2021-01-25 18:21:51', '2021-01-25 18:21:54', null, null); null, '0', '2021-01-25 18:21:51', '2021-01-25 18:21:54', null, null);
insert into forest.forest_user (id, account, password, nickname, real_name, sex, avatar_type, avatar_url, email, phone,
status, created_time, updated_time, last_login_time, signature)
values (2, 'testUser', '8ce2dd866238958ac4f07870766813cdaa39a9b83a8c75e26aa50f23', 'testUser', 'testUser', '0', '0', null, 'testUser@rymcu.com',
null, '0', '2021-01-25 18:21:51', '2021-01-25 18:21:54', null, null);
insert into forest.forest_user_role (id_user, id_role, created_time) insert into forest.forest_user_role (id_user, id_role, created_time)
values (1, 1, '2021-01-25 18:22:12'); values (1, 1, '2021-01-25 18:22:12');

View File

@ -0,0 +1,229 @@
package com.rymcu.forest.service;
import com.rymcu.forest.dto.ArticleDTO;
import com.rymcu.forest.dto.ArticleSearchDTO;
import com.rymcu.forest.dto.ArticleTagDTO;
import com.rymcu.forest.dto.Author;
import com.rymcu.forest.entity.User;
import com.rymcu.forest.web.api.exception.BaseApiException;
import org.junit.FixMethodOrder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
// 顺序执行单元测试
@FixMethodOrder(MethodSorters.DEFAULT)
class ArticleServiceTest {
/**
* 测试用的Article数据用于该单元测试的一系列操作
*/
private final ArticleDTO testArticle;
/**
* 与Article相关联的测试User数据(建表时提前放入)
*/
private final User testUser = new User();
{
// 构建数据之间的关联结构
Author testAuthor = Author.builder()
.idUser(2L)
.userArticleCount("0")
.userAccount("testUser")
.userNickname("testUser")
.userAvatarURL(null)
.build();
BeanUtils.copyProperties(testAuthor, testUser);
ArticleTagDTO tagDTO = ArticleTagDTO.builder()
.tagTitle("Test")
.tagDescription("Test")
.idTag(111)
.tagAuthorId(testUser.getIdUser())
.build();
List<ArticleTagDTO> tags = new ArrayList<>();
tags.add(tagDTO);
testArticle = ArticleDTO.builder()
.articleAuthor(testAuthor)
.articleAuthorId(testAuthor.getIdUser())
.articleContent("Test")
.articleLink("Test")
.articlePerfect("0")
.articlePermalink("Test")
.articleAuthorName(testAuthor.getUserNickname())
.articleCommentCount(0)
.articleStatus("0")
.articleTags("Test")
.articleContentHtml("<h1>Test</h1>")
.articleTitle("Test")
.articleType("0")
.articlePreviewContent("Test")
.articleSponsorCount(12)
.articlePermalink("Test")
.articleViewCount(0)
.tags(tags)
.build();
}
@Autowired
private ArticleService articleService;
/**
* 将测试用的Article数据插入数据库中会回滚的:)
*
* 测试数据是否会返回Article的Id并且Id会填充到测试数据中
* @throws UnsupportedEncodingException
* @throws BaseApiException
*/
@Test
@BeforeEach
public void postArticle() throws UnsupportedEncodingException, BaseApiException {
Long articleId = articleService.postArticle(testArticle, testUser);
testArticle.setIdArticle(articleId);
assertNotNull(articleId);
}
/**
* 测试条件查询
* <p>
* 无参数时返回所有Article
*/
@Test
void findArticles() {
// 无参数时返回参数不应为EmptyList
List<ArticleDTO> articlesAll = articleService.findArticles(new ArticleSearchDTO());
assertNotNull(articlesAll);
assertNotEquals(Collections.emptyList(), articlesAll);
// 测试条件查询是否含有目标数据
ArticleSearchDTO articleSearchDTO = new ArticleSearchDTO();
articleSearchDTO.setSearchText(testArticle.getArticleContent());
Map<Long, ArticleDTO> idArticleMap = articleService.findArticles(articleSearchDTO)
.stream()
.collect(Collectors.toMap(ArticleDTO::getIdArticle, item -> item));
assertNotNull(idArticleMap.get(testArticle.getIdArticle()));
}
/**
* 测试通过Id获取Article
*/
@Test
void findArticleDTOById() {
// 测试参数为
ArticleDTO articleDTOByIdNull = articleService.findArticleDTOById(null, 0);
assertNull(articleDTOByIdNull);
ArticleDTO articleDTOById = articleService.findArticleDTOById(testArticle.getIdArticle(), 0);
assertNotNull(articleDTOById);
}
// @Test
// void findArticlesByTopicUri() {
// List<ArticleDTO> articlesByTopicUri = articleService.findArticlesByTopicUri();
// }
// @Test
// void findArticlesByTagName() {
// List<ArticleDTO> articlesByTagName = articleService.findArticlesByTagName();
// }
/**
* 通过UserId获取对应的Articles
*/
@Test
void findUserArticlesByIdUser() {
List<ArticleDTO> userArticlesByIdUser = articleService.findUserArticlesByIdUser(testArticle.getArticleAuthorId());
assertNotEquals(Collections.emptyList(), userArticlesByIdUser);
}
/**
* 测试文章浏览增量后是否成功
*/
@Test
void incrementArticleViewCount() {
ArticleDTO articleDTOByIdBefore = articleService.findArticleDTOById(testArticle.getIdArticle(), 0);
articleService.incrementArticleViewCount(testArticle.getIdArticle());
ArticleDTO articleDTOByIdAfter = articleService.findArticleDTOById(testArticle.getIdArticle(), 0);
assertEquals(articleDTOByIdBefore.getArticleViewCount() + 1, articleDTOByIdAfter.getArticleViewCount());
}
// @Test
// void share() {
// String share = articleService.share();
// }
// @Test
// void findDrafts() {
// List<ArticleDTO> drafts = articleService.findDrafts(testArticle.getArticleAuthorId());
// }
// @Test
// void findArticlesByIdPortfolio() {
// List<ArticleDTO> articlesByIdPortfolio = articleService.findArticlesByIdPortfolio();
// }
// @Test
// void selectUnbindArticles() {
// List<ArticleDTO> articleDTOS = articleService.selectUnbindArticles();
// }
// @Test
// void findAnnouncements() {
// List<ArticleDTO> announcements = articleService.findAnnouncements();
// }
// @Test
// void updateTags() {
// Boolean aBoolean = articleService.updateTags();
// }
/**
* 测试更新文章为优选\非优选
*/
@Test
void updatePerfect() {
articleService.updatePerfect(testArticle.getIdArticle(), "1");
ArticleDTO articleDTOByIdAfter1 = articleService.findArticleDTOById(testArticle.getIdArticle(), 0);
assertEquals("1", articleDTOByIdAfter1.getArticlePerfect());
articleService.updatePerfect(testArticle.getIdArticle(), "0");
ArticleDTO articleDTOByIdAfter2 = articleService.findArticleDTOById(testArticle.getIdArticle(), 0);
assertEquals("0", articleDTOByIdAfter2.getArticlePerfect());
}
/**
* 测试数据删除是否成功
* <p>
* 运行该测试时可能会产生以下错误
* cn.hutool.core.io.IORuntimeException: Path [xxxxxxx] is not directory!
* 这是由于Lucene的路径通配符默认为linux的解决方式
* 将ArticleIndexUtil.deleteIndex()方法中的PATH改为WINDOW_PATH即可 :)
* @throws BaseApiException 基础Api错误
*/
@Test
void delete() throws BaseApiException {
articleService.delete(testArticle.getIdArticle());
ArticleDTO articleDTOByIdAfter = articleService.findArticleDTOById(testArticle.getIdArticle(), 0);
assertNull(articleDTOByIdAfter);
}
}